// minimal script to control setup process


/// <reference path="GDNote.ui.js" />
/// <reference path="GoogleDocsNote.js" />

var ScriptVersionInit = "201004121314";

var GearsAvailable = false;
var ConnectionAvailable = true;
var GearsEnabled = true;
var AllNotebooks = null;

var GDNoteConnectionAvailable = true;
var GoogleConnectionAvailable = true;

var LoadMessageStatus = false;

function UpdateOnlineStatus(gdnoteavailable, googleavailable) {
    if (gdnoteavailable != GDNoteConnectionAvailable) {
        GDNoteConnectionAvailable = gdnoteavailable;
        if (gdnoteavailable == true) {
            // Just reconnected - try commit/update
            CommitLocalChanges();
        }
        else {
            // Ping Failed
            ShowErrorMessage("Running in offline mode. Click to retry connection", DoReconnect);
        }
    }
    if (googleavailable != GoogleConnectionAvailable) {
        GoogleConnectionAvailable = googleavailable;
        if (googleavailable == true) {
            // reauth succeeded - hide any error message
            HideErrorMessage();
        }
        else {
            // token expired or missing
            // if in full loading screen, redirect immediately
            // otherwise just display a link as we may be offline

            var lp = document.getElementById("loadingpage");

            if (lp.style.display != "none") {

                var url = document.getElementById("hfAuthSubUrl").value;
                document.location = url;
            }
            else {
                ShowErrorMessage("Google login error - Click to reauthenticate", DoReauth);
            }

        }
    }
}

function DoReauth() {
    scoo("lastUser", "", 1000);
    var url = document.getElementById("hfAuthSubUrl").value;
    document.location = url;
}

function DoReconnect() {
//    alert("reconnect");
    GDNote.Web.GDNoteService.Ping(PingSucceeded, PingFailed);
}

function SetUpGearsDB() {
    if (window.google && google.gears) {
        try {
            db = google.gears.factory.create('beta.database');
            server = google.gears.factory.create('beta.localserver');
            store = server.createManagedStore('GDNote');

            store.manifestUrl = 'manifest.txt';

            if (db) {
                db.open('GDNote');

                db.execute('create table if not exists Settings' +
                   ' (SettingKey varchar(255), SettingValue varchar(255))');

                db.execute('create table if not exists NotesFolder' +
                   ' (Email varchar(255), NotesFolderId varchar(255), SelectedNotebookId varchar(255), IsPaid bit, SubscriptionExpiry datetime, LastSync datetime, AuthSubToken varchar(255), BlanksFolderId varchar(255), TagsFolderId varchar(255), ArchivedFolderId varchar(255))');


                db.execute('create table if not exists Notebooks' +
                   ' (Email varchar(255), NotebookId varchar(255), Title varchar(255), FolderId varchar(255), SelectedSectionId varchar(255), LastSync datetime, MovedOrCreated bit, MetadataChanged bit, Deleted bit, Archived bit, ReadOnly bit)');

                db.execute('create table if not exists Sections' +
                   ' (Email varchar(255), SectionId varchar(255), NotebookId varchar(255), Title varchar(255), FolderId varchar(255), SelectedPageId varchar(255), LastSync datetime, MovedOrCreated bit, OldNotebookId varchar(255), MetadataChanged bit, Deleted bit, Archived bit, ReadOnly bit)');

                db.execute('create table if not exists Pages' +
                   ' (Email varchar(255), PageId varchar(255), SectionId varchar(255), Title varchar(255), EditUrl varchar(255), MovedOrCreated bit, OldSectionId varchar(255), MetadataChanged bit, Deleted bit, Archived bit, ReadOnly bit)');

                GearsAvailable = true;
                // Initialize the UI at startup.


                //                SelectNotebook(null);
            }

        } catch (ex) {
            alert('Could not create database: ' + ex.message);
        }
    }
}

function UpdateGearsLocalServer() {
    if (!GearsAvailable) return false;

    ShowLoadMessage("Updating Gears Local Server");

    store.checkForUpdate();


    HideLoadMessage();
}


// return true if local db contains at least one notebook
function GearsContainsData(userEmail) {
    if (!GearsAvailable) return false;

    var rs = db.execute('select * from Notebooks where Email = ?', [userEmail])

    if (rs.isValidRow()) {
        return true;
    }

    return false;
}

// return true if local db contains at least one notebook
function GearsContainsUsers() {
    if (!GearsAvailable) return false;

    var rs = db.execute('select * from Notebooks')

    if (rs.isValidRow()) {
        return true;
    }

    return false;
}


function ShowContentPage() {

    var cv = document.getElementById("contentpage").style.display;
    if (cv == "none") {
        document.getElementById("loadingpage").style.display = "none";
        document.getElementById("contentpage").style.display = "block";

        initContainer("#divNotebooks", AddNewNotebook, ToggleArchivedNotebooks);
        initContainer("#divSections", AddNewSection, ToggleArchivedSections);
        initContainer("#divPages", AddNewPage, ToggleArchivedPages);

        ResizeElements();

        $(window).resize(ResizeElements);





        $('.logo').contextMenu('mnuDebug', {

            bindings: {

              
                'miCommit': function() {

                    CommitLocalChanges();
                }



            }
        });

    }

    RenderAllNotebooks();
    ShowSelectedPage();

}

function ShowLoadMessage(msg) {
    HideErrorMessage();
    LoadMessageStatus = true;

    var lp = document.getElementById("loadingpage");
    var lm1 = document.getElementById("initialloadmessage");
    var lm1a = document.getElementById("initialloadmessagetext");
    var lm2 = document.getElementById("loadmessage");
    var lm2a = document.getElementById("loadmessagetext");


    if (lp.style.display != "none") {
        lm1.style.display = "block";
        lm1a.innerHTML = msg;
    }
    else {
        lm2.style.display = "block";
        lm2a.innerHTML = msg;

        var ww = 500;

        if (window.innerWidth) {
            ww = window.innerWidth;
        }
        else {
            ww = document.body.clientWidth;
        }
        lm2.style.width = (lm2a.offsetWidth - 0 + 120) + "px";

        lm2.style.left = (ww - lm2.offsetWidth - 5) + "px";


    }

}

function HideLoadMessage() {
    var lm1 = document.getElementById("initialloadmessage");
    var lm2 = document.getElementById("loadmessage");

    lm1.style.display = "none";
    lm2.style.display = "none";

    LoadMessageStatus = false;
}


function ShowErrorMessage(msg, clickhandler) {
    HideLoadMessage();
    var lp = document.getElementById("loadingpage");
    var lm1 = document.getElementById("initialerrormessage");
    var lm2 = document.getElementById("errormessage");


    if (lp.style.display != "none") {
        lm1.style.display = "block";
        lm1.innerHTML = msg;
    }
    else {
        lm2.style.display = "block";
        lm2.innerHTML = msg;

        var ww = 500;

        if (window.innerWidth) {
            ww = window.innerWidth;
        }
        else {
            ww = document.body.clientWidth;
        }
//        lm2.style.width = (lm2.offsetWidth - 0 + 120) + "px";

        lm2.style.left = (ww - lm2.offsetWidth - 5) + "px";
        if (clickhandler) {            
            $(lm2).click(clickhandler);
        }
        else {
            $(lm2).unbind('click');        
        }
    }



}

function HideErrorMessage() {
    var lm1 = document.getElementById("initialerrormessage");
    var lm2 = document.getElementById("errormessage");

    lm1.style.display = "none";
    lm2.style.display = "none";
}


function CheckAuthSubToken() {
    // check that we have a token from google docs. if not, redirect to auth page

    var token = gcoo("GoogleDocsToken");
    if ((token == null) || (token == "")) {
        UpdateOnlineStatus(GDNoteConnectionAvailable, false);
    }

}




function load() {
    try {
        if (ScriptVersionInit != ScriptVersionMain || ScriptVersionInit != ScriptVersionUI) {
            alert("Scripts are out of sync. Please refresh.");
            return;
        }

            $("#closePopupSection").click(function() {
                disablePopup();
            });
            $("#addSection").click(AddNewSection);
            $("#backgroundPopup").click(function() {
                disablePopup();
            });


            var userEmail = gcoo("lastUser");

        
        //scoo("lastUser", userEmail, null);
        // todo: get this from cookie

        GearsEnabled = GetBool(gcoo("gears_authorised"));
        ShowLoadMessage("Checking Gears status");
        if (GearsEnabled == true) {
            //            alert("ge -" + window.google + " " + google.gears);
            if (window.google && google.gears) {
                ShowLoadMessage("Enabling Gears DB");
                SetUpGearsDB();
                UpdateGearsLocalServer();
            }
        }
        //        alert(userEmail);
        // load scripts, css, images - this can be implemented later

        // if data is available from gears, we can show it whether or not we are online
        if (GearsContainsData(userEmail)) {
            // TODO: if gears contains data for multiple users, display selection ui
            // unless email is specified in the query string
            UpdateAllNotebooksFromGears(userEmail);
            if (AllNotebooks != null)
                ShowContentPage();
        }
        // now start the online portion of the load
        // first check that authentication token is available
        ShowLoadMessage("Checking authentication token");
        CheckAuthSubToken();
        try {
            CommitLocalChanges();
        }
        catch (e2) {
// this probably can't happen due to catch block in CommitLocalChanges
            GDNote.Web.GDNoteService.LogJSError2(
                "" + (e2.name + ""),
                "" + e2.message,
                "" + (e2.fileName ? e2.fileName : "GDNote.init"),
                "" + (e2.line ? e2.line : e2.lineNumber ? e2.lineNumber : "351(Load)"),
                "" + e2.stack,
                "" + ScriptVersionMain,
                "" + navigator.userAgent,
                "" + gcoo("lastUser")
                );

            // error loading allnotebooks
            // several cases to handle here:

            // timeout/connection error - we are offline. ignore if gears is available

            // authsub error - display auth link if using gears, redirect otherwise

            // subscription error - display link to subscribe

            // other error - display try later message

            ShowErrorMessage("" + e.message);
        }



        //        HideLoadMessage();

    }
    catch (e1) {

        GDNote.Web.GDNoteService.LogJSError2(
                "" + (e1.name + ""),
                "" + e1.message,
                "" + (e1.fileName ? e1.fileName : "GDNote.Init"),
                "" + (e1.line ? e1.line : e1.lineNumber ? e1.lineNumber : "383 (load)"),
                "" + e1.stack,
                "" + ScriptVersionMain,
                "" + navigator.userAgent,
                "" + gcoo("lastUser")
                );

        ShowErrorMessage("" + e1.message);


        
    }

}


function GetUsersInGears() {
    var result = new Array();
    var rs = db.execute('select * from NotesFolder');
    while (rs.isValidRow()) {
        result[result.length] = rs.field(0);
        rs.next();
    }
    return result;
}

function EnableOfflineAccess() {
    alert("enabling");

    SetUpGearsDB();
    store.checkForUpdate();

    var timerId = window.setInterval(function() {
        // When the currentVersion property has a value, all of the resources
        // listed in the manifest file for that version are captured. There is
        // an open bug to surface this state change as an event.
        if (store.currentVersion) {
            window.clearInterval(timerId);
            alert("The documents are now available offline.\n" +
              "With your browser offline, load the document at " +
              "its normal online URL to see the locally stored " +
			        "version. The version stored is: " +
              store.currentVersion);
        } else if (store.updateStatus == 3) {
        window.clearInterval(timerId);
        alert("Error: " + store.lastErrorMessage);
        }
    }, 500);  

    
    if (GearsAvailable == true) {
        scoo("gears_authorised", "true", 1000);
    }
    initHomepage();
}


function OpenNotebook(u) {
    scoo("lastUser", u, 1000);
    document.location = "NotebookPage.aspx";
}

function DoGoogleLogin(url) {
    scoo("lastUser", "", 1000);
    document.location =  url;
}