/*
 Copyright 2005-2010 Xmarks Inc.

 foxmarks-dialog.js: Implements the main foxmarks options dialog.

 */

// TO DO:
// * Use synchronize method for preferences

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var dialogMgr = {
    showPane: function(name) {
        document.getElementById("foxmarks-settings").showPane(
            document.getElementById("foxmarks-" + name));
    },

    panes: {
        // Status Tab
        status: {
            onSetup: function(mgr){
                var os = Cc["@mozilla.org/observer-service;1"].
                    getService(Ci.nsIObserverService);
                os.addObserver(this, "foxmarks-service", false);
                os.addObserver(this, "foxmarks-statechange", false);
                os.addObserver(this, "xmarks-loginchange", false);
                this.doc = document;
                this.window = window;
                this.updateStatus();
                this.updateLoginStatus();
                dialogMgr.panes.advanced.useOwnServerChanged();
            },
            onUnload: function(){
                var os = Cc["@mozilla.org/observer-service;1"].
                    getService(Ci.nsIObserverService);
                try {
                    os.removeObserver(this, "foxmarks-service");
                    os.removeObserver(this, "foxmarks-statechange");
                    os.removeObserver(this, "xmarks-loginchange");
                } catch (e) {
                    Xmarks.LogWrite("Warning: removeObserver failed.");
                }
            },
            onOK: function(){},
            onCancel: function(){},
            setErrorMessaging: function(addThem,err){
                if(addThem){
                    var box = this.doc.getElementById('errorbox');
                    if(box){
                        box.parentNode.removeChild(box);
                    }
                    box = this.doc.createElement('groupbox');
                    box.setAttribute('width', '50');
                    box.setAttribute('style', 'padding-left: 42px;');
                    
                    var label = this.doc.createElement('label');
                    label.setAttribute('value',
                        Xmarks.MapError(err) +"\n"
                    );
                    label.setAttribute('style',
                        'font-weight: bold; margin-left: -2px;'

                    );
                    box.appendChild(label);
                    var errMessage = Xmarks.MapErrorMessage(err);
                    var errUrl = Xmarks.MapErrorUrl(err);
                    if(errMessage.length > 0){
                        var desc = this.doc.createElement('description');
                        var textNode = this.doc.createTextNode(
                            Xmarks.MapErrorMessage(err)
                        );
                        desc.appendChild(textNode);
                        box.appendChild(desc);
                    }

                    
                    if(errUrl.length > 0){
                        var box2 = this.doc.createElement('vbox');
                        box2.setAttribute('flex', '1');
                        box2.setAttribute('align', 'end');

                        var button = this.doc.createElement('button');
                        button.setAttribute('label',
                        Xmarks.Bundle().GetStringFromName("dialog.status.button")
                        );
                        button.setAttribute('oncommand', 
                            'dialogMgr.panes.status.moreInfo("' + errUrl + '");'
                        );
                        box2.appendChild(button);
                        box.appendChild(box2);
                    }
                    box.setAttribute('id', 'errorbox');
                    this.doc.getElementById('statusbox').appendChild(box);
                   // this.window.sizeToContent();
                } else {
                    var box = this.doc.getElementById('errorbox');
                    if(box){
                        box.parentNode.removeChild(box);
                    }
                    // this.window.sizeToContent();
                }
            },

            observe: function(subject, topic, data) {
                if(topic == "foxmarks-service"){
                    var result = eval(data);
                    switch(result.status){
                        case 0: this.updateStatus('ready'); break;
                        case 1: this.updateStatus('working'); break;
                        case 2: this.updateStatus('dirty'); break;
                        default: this.updateStatus('error', result.status);
                            break;
                    }
               } else if(topic == "foxmarks-statechange"){
                    switch(data){
                        case 'ready':
                        case 'dirty':
                        case 'working':
                        case 'error':
                            this.updateStatus(data);
                            break;
                    }
                } else if (topic == "xmarks-loginchange") {
                    this.updateLoginStatus();
                }
            },
            moreInfo: function(err){
                Xmarks.OpenInNewWindow(err);
            },
            updateLoginStatus: function() {
                // If we have an authToken, we're logged in.
                // Otherwise we're not.
                if (Xmarks.gSettings.auth) {
                    var authHandler = Xmarks.gSettings.user.authtype || 
                            "xmarks";
                    try {
                        authHandler = Xmarks.Bundle().
                            GetStringFromName("auth." + authHandler);
                    } catch(e) {}
                    var displayStr = Xmarks.Bundle().
                        GetStringFromName("dialog.loginmsg").
                        replace("$0", Xmarks.gSettings.user.displayname).
                        replace("$1", authHandler);
                    this.doc.getElementById('login-status').value = displayStr;
                    this.doc.getElementById('login-button').hidden = true;
                    this.doc.getElementById('logout-button').hidden = false;
                } else {
                    this.doc.getElementById('login-status').value =
                        Xmarks.Bundle().GetStringFromName("dialog.loggedout");
                    this.doc.getElementById('login-button').hidden = false;
                    this.doc.getElementById('logout-button').hidden = true;
                }
            },
            updateStatus: function(state, errorStatus){
                if(state === undefined){
                    state = Xmarks.fms.getState();
                }
                var image = this.doc.getElementById('status-image');
                var text = this.doc.getElementById('status-text');
                if(errorStatus === undefined){
                    errorStatus = Xmarks.gSettings.lastError;
                }
                switch(state){
                    case 'ready':
                        this.setErrorMessaging(false);
                        image.setAttribute('src',
                            "chrome://foxmarks/skin/images/status-good.png");
                        text.setAttribute('value',
                            Xmarks.Bundle().GetStringFromName("dialog.status.good")
                            );
                        break;
                    case 'dirty':
                        this.setErrorMessaging(false);
                        image.setAttribute('src',
                            "chrome://foxmarks/skin/images/status-dirty.png");
                        text.setAttribute('value',
                            Xmarks.Bundle().GetStringFromName("dialog.status.dirty")
                            );
                        break;
                    case 'working':
                        this.setErrorMessaging(false);
                        image.setAttribute('src',
                            "chrome://foxmarks/skin/images/wheel36x28.gif");
                        text.setAttribute('value',
                            Xmarks.Bundle().GetStringFromName("dialog.status.working")
                            );
                        break;
                    case 'error':
                        image.setAttribute('src',
                            "chrome://foxmarks/skin/images/status-bad.png");
                        text.setAttribute('value',
                            Xmarks.Bundle().GetStringFromName("dialog.status.bad")
                            );
                        this.setErrorMessaging(true, errorStatus);
                        break;
                }
                this.doc.getElementById('sync-now').hidden = 
                    (state == 'working');
                this.doc.getElementById('sync-cancel').hidden =
                    (state != 'working');
            }
        },
        // General Tab
        general: { 
           onSetup: function(mgr){
                this.data = {
                    rememberPassword: Xmarks.gSettings.rememberPassword,
                    synchOnTimer: Xmarks.gSettings.synchOnTimer,
                    syncOnShutdown: Xmarks.gSettings.syncOnShutdown,
                    syncOnShutdownAsk: Xmarks.gSettings.syncOnShutdownAsk,
                };
                // Settings that are too complex to handle via prefwindow
                document.getElementById("synconshutdown").checked =
                    Xmarks.gSettings.syncOnShutdown;
                document.getElementById("askfirst").checked =
                    Xmarks.gSettings.syncOnShutdownAsk;
                this.syncOnShutdownChanged();
           },
           onOK: function(){
           },

           onCancel: function(){
                var name;
                for(name in this.data){
                    if(this.data.hasOwnProperty(name)){
                        Xmarks.gSettings[name] = this.data[name];
                    }
                }
           },
           syncOnShutdownChanged: function() {
                document.getElementById("askfirst").disabled =
                    !document.getElementById("synconshutdown").checked;
           },
           syncOnShutdownToPreference: function() {
                if (document.getElementById("synconshutdown").checked) {
                    return 1;
                }
                return 0;
           }
        },
        sync: { // sync tab
           onSetup: function(mgr){
            this.mgr = mgr;

            this.resetSyncTypes();
           },
           
           resetSyncTypes: function(){
            this.data = {
               bookmarks: Xmarks.gSettings.isSyncEnabled("bookmarks"),
               history: Xmarks.gSettings.isSyncEnabled("history"),
               passwords: Xmarks.gSettings.isSyncEnabled("passwords"),
               tabs: Xmarks.gSettings.isSyncEnabled("tabs")
            };
            // Settings for passwords
            var passwordSyncEnabled = Xmarks.gSettings.isSyncEnabled("passwords");

            document.getElementById("sync-passwords").checked =
                passwordSyncEnabled;
            document.getElementById("sync-resetpin").disabled =
                !passwordSyncEnabled; 
            document.getElementById("sync-deletepasswords").disabled =
                !passwordSyncEnabled;
            if(Xmarks.gSettings.useOwnServer){
                document.getElementById("sync-deletepasswords").disabled = true;
            }
                
            document.getElementById("sync-bookmarks").checked = 
                this.data.bookmarks;
            document.getElementById("sync-history").checked = this.data.history;
            document.getElementById("sync-tabs").checked = this.data.tabs;
            document.getElementById("sync-tabs-div").hidden =
                !this.data.tabs;

            if ("@mozilla.org/login-manager;1" in Cc) {
                document.getElementById("onlyFF3").hidden = true;
            }
            else {
                document.getElementById("sync-resetpin").disabled = true;
                document.getElementById("sync-deletepasswords").disabled = true;
                document.getElementById("sync-passwords").disabled = true;
            }

           },
           onOK: function(){

           },
           onCancel: function(){
                Xmarks.gSettings.setSyncEnabled("passwords",
                    this.data.passwords); 
                Xmarks.gSettings.setSyncEnabled("bookmarks",
                    this.data.bookmarks); 
                Xmarks.gSettings.setSyncEnabled("history",this.data.history); 
                Xmarks.gSettings.setSyncEnabled("tabs", this.data.tabs);
           },
           handlePasswordSync: function(){
                var d = document;
                var passwordSyncEnabled =
                    d.getElementById("sync-passwords").checked; 
                var result = {
                    doSync: false
                };
                if(passwordSyncEnabled){
                        Xmarks.ModalDialog(function()
                            window.openDialog(
                                "chrome://foxmarks/content/foxmarks-setup.xul",
                                "Xmarks", "chrome,dialog,modal,centerscreen",
                                true,
                                "getpin",
                                result
                            ));
                        passwordSyncEnabled = Xmarks.gSettings.pinNoPrompt != null;
                        if(!passwordSyncEnabled){
                            d.getElementById("sync-passwords").checked = false; 
                        }
                        if(result.doSync){
                            Xmarks.gSettings.setSyncEnabled("passwords",
                                passwordSyncEnabled);
                            if(Xmarks.gSettings.securityLevel == -1){
                                Xmarks.Alert(Xmarks.Bundle().GetStringFromName
                                    ("msg.resetpin.securitylevelchange"));
                            }
                            Xmarks.gSettings.securityLevel = 1;
                            d.getElementById("encrypt").setAttribute(
                                "value", "1");
                            if(this.mgr.synchronizeNow()){
                                var prefwindow = 
                                    document.getElementById("foxmarks-settings");
                                prefwindow.showPane(
                                    document.getElementById("foxmarks-mainpane")
                                );
                            }
                        }
                }
                else {
                    Xmarks.gSettings.removePIN();
                }

                Xmarks.gSettings.setSyncEnabled("passwords",passwordSyncEnabled); 
                d.getElementById("sync-deletepasswords").disabled =
                    !passwordSyncEnabled; 
                d.getElementById("sync-resetpin").disabled =
                    !passwordSyncEnabled; 
           },
           handleBookmarkSync: function(){
                var d = document;
                var enabled = d.getElementById("sync-bookmarks").checked; 
                Xmarks.gSettings.setSyncEnabled("bookmarks",enabled); 
           },
           handleHistorySync: function() {
               var d = document;
               var enabled = d.getElementById("sync-history").checked;
               Xmarks.gSettings.setSyncEnabled("history", enabled);
           },

           handleTabSync: function() {
               var d = document;
               var checked = d.getElementById("sync-tabs").checked;
               d.getElementById("sync-tabs-div").hidden = !checked;
               Xmarks.gSettings.setSyncEnabled("tabs", checked);
           },

           doDeletePasswords: function(){
                var ps = Components.classes
                    ["@mozilla.org/embedcomp/prompt-service;1"]
                    .getService(Components.interfaces.nsIPromptService);
               if(ps.confirm(null,"Xmarks", Xmarks.Bundle().
                    GetStringFromName("msg.deletepasswords.confirm"))
               ){
                    this.mgr.onOK();
                    if(!Xmarks.PerformAction("deletepasswords", null)){
                        Xmarks.gSettings.setSyncEnabled("passwords", false);
                        document.getElementById("sync-passwords").checked = 
                            false; 
                        document.getElementById("sync-resetpin").disabled =
                            true;
                        document.getElementById("sync-deletepasswords").
                            disabled = true;
                        Xmarks.gSettings.removePIN();
                        ps.alert(null, "Xmarks", Xmarks.Bundle().
                                GetStringFromName("msg.deletepasswords.success")
                        );
                    }
                    else {
                        var prefwindow = 
                            document.getElementById("foxmarks-settings");
                        prefwindow.showPane(
                                document.getElementById("foxmarks-mainpane")
                        );
                    }
               }

           },
           doResetPIN: function(){
                var result = {
                    doSync: false
                };
                window.openDialog(
                    "chrome://foxmarks/content/foxmarks-resetpin.xul",
                    "_blank",
                    "chrome,dialog,modal,centerscreen", result);
                if(result.doSync){
                    Xmarks.gSettings.setSyncEnabled("passwords",true); 
                   Xmarks.gSettings.setMustUpload("passwords", true);
                   if(!this.mgr.synchronizeNow()){
                        Xmarks.Alert(Xmarks.Bundle().
                            GetStringFromName("msg.resetpin.success"));
                   }
                    else {
                        var prefwindow = 
                            document.getElementById("foxmarks-settings");
                        prefwindow.showPane(
                                document.getElementById("foxmarks-mainpane")
                        );
                    }
                }
            },
            moreSyncSoon: function(){
                Xmarks.OpenInNewWindow("http://wiki.xmarks.com/wiki/Foxmarks:_More_Syncing_Coming_Soon"); 
            }
        },
        restore: { // restore tab
            _data: null,
            onSetup: function(mgr){
                this.mgr = mgr;
                this.box = document.getElementById("foxmarks-restorelist");
                var self = this;

                this.box.addEventListener(
                    "select",
                    function(e){
                        self.onSelect(e);
                    },
                    true
                );
            },
            _currItem: null,
            onSelect: function(e){
                var i = this.box.getSelectedItem(0);
                if(this._currItem){
                    this._currItem.setAttribute("image", 
                        "chrome://foxmarks/skin/images/restore_icon.png");
                }
                this._currItem = i;
                this._currItem.setAttribute("image", 
                    "chrome://foxmarks/skin/images/restore_icon_selected.png");
            },
            onSyncComplete: function(){
                if(this.box && this._data){
                    var item = this.box.getItemAtIndex(0);
                    if(item){
                        var currVersion = Xmarks.gSettings.GetSyncRevision("bookmarks");
                        if(item.value != currVersion){
                            var formatString = Xmarks.Bundle().GetStringFromName(
                                "restore.formatstring"
                            );
                            var d = new Date(Xmarks.gSettings.lastSynchDate);
                            var s = d.toLocaleFormat(formatString);
                            var i = this.box.insertItemAt(0, s, currVersion);
                            i.className = "listitem-iconic";
                            i.style.paddingLeft = "6px";
                            i.setAttribute("image",  "chrome://foxmarks/skin/images/restore_icon.png");
                            this.box.selectItem(
                                this.box.getItemAtIndex(0)
                            );
                        }
                    }
                }
            },
            onShow: function(){
                if(!Xmarks.gSettings.getHaveSynced("bookmarks") ||
                    Xmarks.gSettings.viewId != 0 || 
                    Xmarks.gSettings.useOwnServer){
                    document.getElementById("foxmarks-restoredesc").hidden=true;
                    document.getElementById("foxmarks-restorebox").hidden=true;
                    if(Xmarks.gSettings.viewId){
                        document.getElementById("foxmarks-restoreprofile").
                            hidden=false;
                    } else if(Xmarks.gSettings.useOwnServer){
                        document.getElementById("foxmarks-restoreownuser").
                            hidden=false;
                    } else {
                        document.getElementById("foxmarks-restorenewuser").
                            hidden=false;
                    }
                } else {
                    document.getElementById("foxmarks-restoredesc").hidden=
                        false;
                    document.getElementById("foxmarks-restorebox").hidden=
                        false;
                    document.getElementById("foxmarks-restorenewuser").hidden=true;
                    document.getElementById("foxmarks-restoreownuser").hidden=true;
                    if(!this._data){
                        var self = this;
                        Xmarks.FetchRevisions(
                            function(data){
                                self.loadRevisions(data);
                            }
                        );
                    } else {
                        this.box.focus();
                    }
                }
            },
            loadRevisions: function(response){
                this.box.removeItemAt(0);
                if (response.status != 0) {
                    this.box.appendItem(
                            Xmarks.Bundle().GetStringFromName(
                                "err.revisionserror"));
                    this._data = true;
                    return;
                }
                else if (!response.revisions || response.revisions.length == 0){
                    this.box.appendItem(
                            Xmarks.Bundle().GetStringFromName(
                                "err.norevisionsloaded"));
                    this._data = true;;
                    return;

                }

                var list = response.revisions;
                list.sort(
                    function(a,b){
                        return b.revision - a.revision;
                    }
                );

                this._data = list;
                var len = list.length;
                var formatString = Xmarks.Bundle().GetStringFromName(
                    "restore.formatstring"
                );
                for(x = 0; x < len; x++){
                    var item = list[x];
                    var d = new Date(item.created * 1000 );
                    var s = d.toLocaleFormat(formatString);
                    var i = this.box.appendItem(s, item.revision);
                    i.className = "listitem-iconic";
                    i.style.paddingLeft = "6px";
                    i.setAttribute("image",  "chrome://foxmarks/skin/images/restore_icon.png");
                }
                this.box.disabled = false;
                this.box.selectItem(
                    this.box.getItemAtIndex(0)
                );
                this.box.focus();
                document.getElementById("foxmarks-viewrestore").disabled
                    = false;
                document.getElementById("foxmarks-dorestore").disabled = false;
            },
            onOK: function(){

            },
            onCancel: function(){

            },
            select: function(){
                    return false;
            },
            restore: function(){
                var item = this.box.getSelectedItem(0);
                var val = item.value;
                this.box.focus();
                if(this.box.getIndexOfItem(item) == 0){
                    this.mgr.downloadNow(false, true);
                } else {
                    this.mgr.restore(val);
                }
            },
            viewRestore: function(){
                var item = this.box.getSelectedItem(0);
                var val = item.value;
                this.box.focus();

                Xmarks.OpenInNewTabAuth(
                    Xmarks.gSettings.httpProtocol +  Xmarks.gSettings.myHost +
                    "/bookmarks/view/" + val + "/", 
                    true,
                    Xmarks.gSettings.auth
                );
            }
        },
        profile: { // profiles tab
           onSetup: function(mgr){
                this.mgr = mgr;
                this.settingChanged();
           },
           onOK: function(){

           },

           onCancel: function(){

           },
           myFoxmarks: function(){
                if(Xmarks.gSettings.securityLevel == 1){
                    Xmarks.OpenInNewTab("https://my.xmarks.com/?mode=profiles", true);
                } else { 
                    Xmarks.OpenInNewTab("http://my.xmarks.com/?mode=profiles", true);
                }
           },
           changeProfile: function() {
                var retval = {};
                if (Xmarks.DoModalAuth(false, true))
                    return;
                window.openDialog(
                    "chrome://foxmarks/content/foxmarks-changeprofile.xul",
                    "Xmarks", "modal,centerscreen", retval
                );

                if (retval.newProfileId &&
                    retval.newProfileId != Xmarks.gSettings.viewId) {
                    var ps = Components.
                        classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
                    if (ps.confirm(null, "Xmarks",
                        Xmarks.Bundle().GetStringFromName("msg.profilechanged"))) {
                        if (this.mgr.synchronizeNow()) {
                            var prefwindow = 
                                document.getElementById("foxmarks-settings");
                            prefwindow.showPane(
                                document.getElementById("foxmarks-mainpane")
                            );
                            return;
                        }
                        Xmarks.gSettings.viewId = retval.newProfileId;
                        Xmarks.gSettings.viewName = retval.newProfileName;
                        this.mgr.downloadNow(true);
                        this.settingChanged();
                    }
                }
            },
            settingChanged: function() {
                document.getElementById("profileName").value =
                    Xmarks.gSettings.viewName;
                document.getElementById("useview-control").disabled =
                    Xmarks.gSettings.viewId == 0;
            }
        },
        // Advanced tab
        /*
        discover: { 
           onSearchBoostChanged: function(){
                this.onOK();
           },
           onSetup: function(mgr){
                document.getElementById("tagsuggest").checked =
                    Xmarks.gSettings.tagSuggestionsEnabled;
                document.getElementById("siteboost").checked =
                    Xmarks.gSettings.simsiteEnabled;
                document.getElementById("searchboost").checked = 
                    Xmarks.gSettings.serpEnabled;
                this.data = {
                    tagSuggestionsEnabled: 
                        Xmarks.gSettings.tagSuggestionsEnabled,
                    serpEnabled: Xmarks.gSettings.serpEnabled,
                    simsiteEnabled: Xmarks.gSettings.simsiteEnabled
                };
           },
           onOK: function(){
                Xmarks.gSettings.tagSuggestionsEnabled = 
                    document.getElementById("tagsuggest").checked;
                Xmarks.gSettings.serpEnabled = 
                    document.getElementById("searchboost").checked;
                Xmarks.gSettings.simsiteEnabled = 
                    document.getElementById("siteboost").checked;
                Xmarks.gSettings.tagSuggestionsEnabled = 
                    document.getElementById("tagsuggest").checked;
           },
           onCancel: function(){
                var name;
                for(name in this.data){
                    if(this.data.hasOwnProperty(name)){
                        Xmarks.gSettings[name] = this.data[name];
                    }
                }
           }
        },
        */
        // Advanced tab
        advanced: { 
           onSetup: function(mgr){
                this.data = {
                    enableLogging: Xmarks.gSettings.enableLogging,
                    securityLevel: Xmarks.gSettings.securityLevel,
                    url: Xmarks.gSettings.url,
                    passwordurl: Xmarks.gSettings.passwordurl,
                    useOwnServer: Xmarks.gSettings.useOwnServer
                };
                this.useOwnServerChanged();
           },
           verifyOK: function(){
                var uo = document.getElementById("useown").checked;

                if(uo){
                    var s = document.getElementById("url").value;
                    if(s.length == 0){
                        Xmarks.Alert(Xmarks.Bundle().
                            GetStringFromName("error.nourlownserver"));
                        return false;
                    }
                    var exp = /(.*):\/\/([^\/]*)/;
                    var result = s.match(exp);
                    if (!result || result.length < 2) {
                        Xmarks.Alert(Xmarks.Bundle().
                            GetStringFromName("error.nourlownserver"));
                        return false;
                    }
                    Xmarks.gSettings.useOwnServer = uo;
                }

                return true;
           },
           onOK: function(){
                var uo = document.getElementById("useown").checked;
                Xmarks.gSettings.useOwnServer = uo;
                if(uo){
                    Xmarks.gSettings.url = document.getElementById("url").value;
                    Xmarks.gSettings.passwordurl =
                        document.getElementById("passwordurl").value;
                }
           },
           onCancel: function(){
                var name;
                for(name in this.data){
                    if(this.data.hasOwnProperty(name)){
                        Xmarks.gSettings[name] = this.data[name];
                    }
                }
           },
           displayLogFile: function() {
                var ios = Cc["@mozilla.org/network/io-service;1"].
                    getService(Ci.nsIIOService);
                var file = Cc['@mozilla.org/file/directory_service;1']
                    .getService(Ci.nsIProperties) .get('ProfD', Ci.nsIFile);

                file.append("xmarks.log");
                var uri = ios.newFileURI(file);
                Xmarks.OpenInNewWindow(uri.spec);
           },
           useOwnServerChanged: function() {
                var uo = document.getElementById("useown").checked;
                document.getElementById("useown-grid").hidden = !uo;
                document.getElementById("encrypt").disabled = uo;
                document.getElementById("profileChangeButton").disabled = uo;
                document.getElementById("sync-tabs").disabled = uo;
                document.getElementById("sync-history").disabled = uo;
                document.getElementById("sync-tabs-div").hidden = uo ||
                    !document.getElementById("sync-tabs").checked;
                document.getElementById("foxmarks-statusdeck").selectedIndex =
                    (!Xmarks.gSettings.haveSynced && 
                        !Xmarks.gSettings.username && !uo) ? 1 : 0;
                document.getElementById("accountdeck").selectedIndex =
                    uo ? 1 : 0;
                document.getElementById("ownserver-edit").hidden = !uo;

                dialogMgr._lastSyncDateChanged();
            },
           useOwnServer: function(){
                var uo = document.getElementById("useown").checked;
                if(!uo){
                    return true;
                }
                    
                var params = {
                    url: document.getElementById("url").value,
                    purl: document.getElementById("passwordurl").value,
                    psync: document.getElementById("sync-passwords").checked,
                    username: Xmarks.gSettings.username,
                    password: Xmarks.gSettings.passwordNoPrompt,
                    remember: Xmarks.gSettings.rememberPassword,
                    result: false
                };
                window.openDialog(
                    "chrome://foxmarks/content/foxmarks-ownserverdlg.xul",
                    "_blank",
                    "chrome,dialog,modal,centerscreen", params);
                if(params.result){
                    document.getElementById("url").value = params.url;
                    document.getElementById("passwordurl").value = params.purl;
                    Xmarks.gSettings.username = params.username;
                    Xmarks.gSettings.rememberPassword = params.remember;
                    Xmarks.gSettings.password = params.password;
                } else {
                    if (!document.getElementById("url").value && 
                            !document.getElementById("passwordurl").value) {
                        document.getElementById("useown").checked = false;
                    }
                }
                this.useOwnServerChanged();
                return true;
           },
           moreOwnServer: function(){
                Xmarks.OpenInNewWindow("http://wiki.xmarks.com/wiki/Foxmarks:_Frequently_Asked_Questions#Using_Other_Servers"); 
           }
        }
    },

    _forEachPane: function(method, args){
        var name;
        for(name in this.panes){
            if(this.panes.hasOwnProperty(name)){
                var pane = this.panes[name];
                if(typeof(method) == "string"){
                    pane[method].apply(pane, args);
                }
                else {
                    if(args === undefined){
                        args = [];

                    }
                    args.splice(0,0,this.panes[name]);
                    method.apply(pane, args);
                }
            }
        }
    },

    onSetup: function(){
        this._forEachPane("onSetup", [this]);

        // Set styles for Mac OS X
        if (navigator.platform.toLowerCase().indexOf('mac') > -1 ||
            navigator.platform.toLowerCase().indexOf('linux') > -1) {
            document.getElementById("foxmarks-settings").className = 
                "xmarks macosx";
        }
        // Set server ping
        if (!Xmarks.gSettings.useOwnServer) {
            var attrs = [];
            attrs.push("app="       + "jezebel");
            attrs.push("mid="       + Xmarks.gSettings.machineId);
            attrs.push("page="      + "settings");
            attrs.push("username="  + Xmarks.gSettings.username);
            attrs.push("no_cache="  + Date.now().toString(36));
            var query = attrs.join("&");

            document.getElementById("ping").src = 
                "http://tr.xmarks.com/tracking/impressions.gif?" + query; 
        }

        // Info that is read-only
        this._lastSyncDateChanged();
        document.getElementById("version").value = 
            "v"
            + Xmarks.FoxmarksVersion();
        try {
            window.sizeToContent();
        } catch(e) {}

        var prefwindow = document.getElementById("foxmarks-settings");
        var self = this;
        prefwindow.onclick = function(e) { self.onClick(e);};
        prefwindow.showPane(
            document.getElementById(window.arguments[0] || 
                "foxmarks-mainpane"));
        Cu.import("resource://xmarks/service.jsm", Xmarks);

        // XXX: Takemeout
        Xmarks.history = {};
        Cu.import("resource://Xmarks/history.jsm", Xmarks.history);

    },
    onOK: function(){
        if(!this.panes.advanced.verifyOK()){
           return false;
        }
        this._forEachPane("onOK");
        var os = Cc["@mozilla.org/observer-service;1"]
            .getService(Ci.nsIObserverService);
        os.notifyObservers(null, "foxmarks-settingschange","");
        return true;
    },
    onCancel: function(){
        if (navigator.platform.toLowerCase().indexOf('mac') > -1 ||
            navigator.platform.toLowerCase().indexOf('linux') > -1) {
            if(!this.panes.advanced.verifyOK()){
                return false;
            }
            this._forEachPane("onOK");
            var os = Cc["@mozilla.org/observer-service;1"]
                .getService(Ci.nsIObserverService);
            os.notifyObservers(null, "foxmarks-settingschange","");
        }
        else {
            this._forEachPane("onCancel");
        }
        return true;
    },
    onHelp: function(){
        Xmarks.OpenInNewWindow("http://wiki.xmarks.com/wiki/Foxmarks:_Help");
    },
    login: function() {
        Xmarks.DoModalAuth(false, false);
    },
    logout: function() {
        Xmarks.gSettings.Logout(true);
    },
    runSetupWizard: function(){
        this.onOK();
        if(Xmarks.gSettings.useOwnServer){
            Xmarks.Alert(Xmarks.Bundle().
                GetStringFromName("error.nowizforownserver"));
        } else {
            if (Xmarks.OpenWizard(true))
                return;
            window.close();
        }
    },
    onSyncComplete: function(){
        this._lastSyncDateChanged();
        this.panes.restore.onSyncComplete();
    },
    synchronizeNow: function() {
        var retval = 0;
        this.onOK();
        var retval = Xmarks.PerformAction("synch", null);
        this.onSyncComplete();
        this.panes.sync.resetSyncTypes();
        return retval;
    },
    cancel: function() {
        Xmarks.fms.cancel();
    },
    _lastSyncDateChanged: function() {
        document.getElementById("lastSynchDate").value = 
            Xmarks.gSettings.lastSynchDisplayDate;
    },
    uploadNow: function(){
        var retval = 0;
        var ps = Components.classes
            ["@mozilla.org/embedcomp/prompt-service;1"]
            .getService(Components.interfaces.nsIPromptService);
        if (ps.confirm(null, "Xmarks",
            Xmarks.Bundle().GetStringFromName("msg.overwriteremote"))) {
            this.onOK();
            retval = Xmarks.PerformAction("upload", null);
            if(retval){
               var prefwindow = document.getElementById("foxmarks-settings");
               prefwindow.showPane(
                    document.getElementById("foxmarks-mainpane")
               );
            }
            this.onSyncComplete();
        }
        return retval;
    },
    restore: function(rev){
        var retval = 0;
        var ps = Components.classes
            ["@mozilla.org/embedcomp/prompt-service;1"]
            .getService(Components.interfaces.nsIPromptService);
        if (ps.confirm(null, "Xmarks",
                Xmarks.Bundle().GetStringFromName("restore.confirm"))) {
            this.onOK();
            retval = Xmarks.PerformAction("restore", rev);
            if(retval){
               var prefwindow = document.getElementById("foxmarks-settings");
               prefwindow.showPane(
                    document.getElementById("foxmarks-mainpane")
               );
            }
            ps.alert(null, "Xmarks", Xmarks.Bundle().
                    GetStringFromName("restore.success"));
            this.onSyncComplete();
        }
        return retval;

    },
    downloadNow: function(silent, isrestore){
        var retval = 0;
        var ps = Components.classes
            ["@mozilla.org/embedcomp/prompt-service;1"]
            .getService(Components.interfaces.nsIPromptService);
        if (silent
            || ps.confirm(null, "Xmarks",
                Xmarks.Bundle().GetStringFromName(
                    isrestore ? "restore.confirm" :"msg.overwritelocal"))) {
            this.onOK();
            retval = Xmarks.PerformAction("download", null);
            if(retval){
               var prefwindow = document.getElementById("foxmarks-settings");
               prefwindow.showPane(
                    document.getElementById("foxmarks-mainpane")
               );
            }
            this.onSyncComplete();
        }
        return retval;

    },
    onClick: function(e){
        if(e && e.target && e.target.id == "foxmarks-settings"){
            var self = this;
            var prefwindow = document.getElementById("foxmarks-settings");
            window.setTimeout(
                function(){
                    if(prefwindow.currentPane.id == "foxmarks-restorepane"){
                        self.panes.restore.onShow();
                    }
                },
                0
            );
        }
    },
    onUnload: function(){
        this.panes.status.onUnload();
    }
};



function SynchronizeForever() {
    while (!SynchronizeNow()) { };
}


