/* 
 Copyright 2009 Foxmarks Inc.

 foxmarks-uitools.js: Various and sundry UI functions. 

 */

var Xmarks;
if(Xmarks === undefined){
    Xmarks = {};
}

var Cc = Components.classes;
var Ci = Components.interfaces;
var CCon = Components.Constructor;

(function() {
var xm = Xmarks;

xm.OpenWindowByType = function(inType, uri, features, args) {
    var wm = Cc['@mozilla.org/appshell/window-mediator;1'].
        getService(Ci.nsIWindowMediator);
    var topWindow = wm.getMostRecentWindow(inType);

    if (topWindow) {
        topWindow.focus();
    } else {
        topWindow = wm.getMostRecentWindow(null);
        var win = topWindow.openDialog(uri, "_blank", features || "chrome",
            args);
    }
};

xm.OpenInNewTabAuth = function(url, focus, auth){
    var wm = Cc['@mozilla.org/appshell/window-mediator;1'].
        getService(Ci.nsIWindowMediator);
    var topWindow = wm.getMostRecentWindow('navigator:browser');
    if (topWindow) {
        var content = topWindow.document.getElementById('content');
        if(auth !== undefined){
            var pd = Cc["@mozilla.org/network/mime-input-stream;1"].
                           createInstance(Ci.nsIMIMEInputStream);
            pd.addHeader("Authorization", "XMAuth "+ auth);
            pd.addHeader("X-Xmarks-Auth", auth);

            content.selectedTab =
                content.addTab(url, null,null , pd);
        } else {
            content.selectedTab =
                content.addTab(url);
        }
        if (focus) {
            topWindow.focus();
        }
    }
};

xm.OpenInNewTab = function(url, focus, postData) {
    var wm = Cc['@mozilla.org/appshell/window-mediator;1'].
        getService(Ci.nsIWindowMediator);
    var topWindow = wm.getMostRecentWindow('navigator:browser');
    if (topWindow) {
        var content = topWindow.document.getElementById('content');
        if(postData !== undefined){
            var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
                createInstance(Ci.nsIStringInputStream);
            var txt = postData.toJSONString();
            if ("data" in stringStream) // Gecko 1.9 or newer
                    stringStream.data = txt;
            else // 1.8 or older
                stringStream.setData(txt, txt.length);
                               
            var pd = Cc["@mozilla.org/network/mime-input-stream;1"].
                           createInstance(Ci.nsIMIMEInputStream);
            pd.addHeader("Content-Type", "application/json");
            pd.addContentLength = true;
            pd.setData(stringStream);

            content.selectedTab =
                content.addTab(url, null,null , pd);
        } else {
            content.selectedTab =
                content.addTab(url);
        }
        if (focus) {
            topWindow.focus();
        }
    }
};

xm.OpenInNewWindow = function(url) {
    return openDialog("chrome://browser/content/browser.xul", "_blank",
        "chrome,all,dialog=no", url);
};

xm.OpenFoxmarksSettingsDialog = function(pane) {
    xm.OpenWindowByType("foxmarks:settings",
        "chrome://foxmarks/content/foxmarks-dialog.xul", 
        "chrome,toolbar,centerscreen",
        [pane || "foxmarks-mainpane"]);
};

xm.MyFoxmarks = function() {
    if(xm.gSettings.securityLevel == 1){
        xm.OpenInNewTab("https://my.xmarks.com/", true);
    } else {
        xm.OpenInNewTab("http://my.xmarks.com/", true);
    }
};

xm.OpenWizard = function(manual, skipAuth) {
    if (skipAuth) {
        xm.OpenWindowByType("foxmarks:setup",
            "chrome://foxmarks/content/foxmarks-setup.xul",
            "chrome,centerscreen,dialog=no", manual);
    } else {
        xm.OpenWindowByType("foxmarks:login", 
            "chrome://foxmarks/content/foxmarks-login.xul",
            "chrome,centerscreen,dialog=no", manual);
    }
};

xm.OnWizardCancel = function() {
    var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
        .getService(Components.interfaces.nsIPromptService);

    var checkResult = {};
    checkResult.value = xm.gSettings.wizardSuppress;
    var sb = xm.Bundle();

    var ret = ps.confirmCheck(window, sb.GetStringFromName("title.cancelsetup"),
            sb.GetStringFromName("msg.cancelsetup"),
            sb.GetStringFromName("msg.nowizard"),
            checkResult);

    xm.gSettings.wizardSuppress = checkResult.value;
    xm.gSettings.majorVersion = 3;

    return ret;
};

xm.Synch = function() {
    xm.PerformAction("synch");
};

xm.PerformAction = function(action, arg) {
    var retval = { helpurl: null };

    try {
        var win = window.openDialog(
            "chrome://foxmarks/content/foxmarks-progress.xul", "_blank",
            "chrome,dialog,modal,centerscreen", action, retval, arg);
        if (retval.helpurl) {
            xm.OpenInNewWindow(retval.helpurl);   
        }
    } catch (e) {
        // pass through
    }
    return retval.status;
};

var XmarksDataServiceObserver = {
    os: Cc["@mozilla.org/observer-service;1"].
        getService(Ci.nsIObserverService),

    observe: function(subject, topic, data) {
        var result = eval("(" + data + ")");
        this.os.removeObserver(this, "foxmarks-dataservice");
        if (this.spinner) {
            this.spinner.hidden = true;
        }
        if (this.callback) {
            var callback = this.callback;
            this.callback = null;
            callback(result);
        }
    },

    start: function(text, spinner, callback) {
        this.os.addObserver(this, 
                "foxmarks-dataservice", false);
        this.text = text;
        this.spinner = spinner;
        this.callback = callback;
        if (this.spinner) {
            this.spinner.hidden = false;
        }
    }
};
var XmarksServiceObserver = {
    os: Cc["@mozilla.org/observer-service;1"].
        getService(Ci.nsIObserverService),

    observe: function(subject, topic, data) {
        var result = eval("(" + data + ")");
        if (this.text) {
            this.text.value = result.msg;
        }
        if (result.status != 1 && result.status != 3) {
            this.os.removeObserver(this, "foxmarks-service");
            if (this.spinner) {
                this.spinner.hidden = true;
            }
            if (this.callback) {
                var callback = this.callback;
                this.callback = null;
                callback(result);
            }
        }
    },

    start: function(text, spinner, callback) {
        this.os.addObserver(XmarksServiceObserver, "foxmarks-service", false);
        this.text = text;
        this.spinner = spinner;
        this.callback = callback;
        if (this.spinner) {
            this.spinner.hidden = false;
        }
    }
}

xm.TurboTagsCancel = function() {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    fms.datacancel();
};

xm.FetchTurboTags = function(url, text, spinner, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksDataServiceObserver.start(text, spinner, callback);
    if (!fms.getTurboTags(url)) {
        callback({status: 2, msg: "Whoops! We're busy!" });
    }
    return true;
};

xm.UpdateReview = function(url, url_id, title, description, rating, review, 
        post_to_fb, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksDataServiceObserver.start(null, null, callback);
    if (!fms.updateReview(url, url_id, title, description, rating, review, 
            post_to_fb)) {
        callback({status: 2, msg: "Whoops! We're busy!" });
    }
    return true;
};


xm.SimilarSitesCancel = function() {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    fms.datacancel();
};

xm.FetchSimilarSites = function(url, text, spinner, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksDataServiceObserver.start(text, spinner, callback);
    if (!fms.getSimilarSites(url)) {
        callback({status: 2, msg: "Whoops! We're busy!" });
    }
    return true;
};

xm.FetchProfileNames = function(text, spinner, menuPopup, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksServiceObserver.start(text, spinner, FetchProfileNamesCallback);
    if (!fms.getProfileNames()) {
        callback({status: 2, msg: "Whoops! We're busy!" });
    }

    function FetchProfileNamesCallback(response) {
        if (response.profiles) {
            var profiles = response.profiles;
            var count = 0;
            for (var i = 1; i < menuPopup.childNodes.length; ++i) {
                if (profiles[String(i)]) {
                    var name = profiles[String(i)];
                    menuPopup.childNodes[i].label = name;
                    menuPopup.childNodes[i].hidden = false;
                    count++;
                } else {
                    menuPopup.childNodes[i].hidden = true;
                }
            }
            if (callback) {
                callback({ status: response.status, count: count, 
                        profiles: profiles });
            }
        }
    }
};

xm.VerifyPINStatus = function(pin, text, spinner, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksServiceObserver.start(text, spinner, callback);
    fms.verifypin(pin);
};

xm.FetchAccountStatus = function(syncType, text, spinner, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksServiceObserver.start(text, spinner, callback);
    try {
        fms.status(syncType);
    } catch (e) {
        Xmarks.LogWrite("FetchAccountStatus failed: " + e.toSource());
        callback(typeof(e) == "number" ? e : 4);
    }
};

xm.FetchRevision = function(rev,callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksServiceObserver.start("", null, callback);
    fms.getrevision(rev);
};

xm.FetchRevisions = function(callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksServiceObserver.start("", null, callback);
    fms.getrevisions();
};
xm.FetchAccountExtStatus = function(syncType, text, spinner, callback) {
    var fms = Cc["@foxcloud.com/extensions/foxmarks;1"].
        getService(Ci.nsIFoxmarksService);
    XmarksServiceObserver.start(text, spinner, callback);
    fms.extstatus(syncType);
};

var inputTimer;
xm.handlePasswordMeter = function(id){
    if(inputTimer){
        window.clearTimeout(inputTimer);
        inputTimer = undefined;
    }

    inputTimer = window.setTimeout(function(){
        var txt = document.getElementById(id).value;
        var result = TestPassword(txt);

        if(result * 5 > 200 || result > 24){
            result = 40;
        }
        document.getElementById('passwordmeter').width = result * 5;
        if(txt.length < 4){
            document.getElementById('passwordStrength').style.color = 
                "#333";
            document.getElementById('passwordmeter').style.backgroundColor = 
                "#999";

            document.getElementById('passwordStrength').value =
                xm.Bundle().GetStringFromName("password.tooshort");
        }
        else if(result < 17){
            document.getElementById('passwordStrength').value =
                xm.Bundle().GetStringFromName("password.weak");
            document.getElementById('passwordStrength').style.color = 
                "#57040F";
            document.getElementById('passwordmeter').style.backgroundColor = 
                "#57040F";
        }
        else if(result < 24){
            document.getElementById('passwordStrength').value =
                xm.Bundle().GetStringFromName("password.good");
            document.getElementById('passwordStrength').style.color = 
                "#ED9D2B";
            document.getElementById('passwordmeter').style.backgroundColor = 
                "#ED9D2B";
        }
        else {
            document.getElementById('passwordStrength').value =
                xm.Bundle().GetStringFromName("password.strong");
            document.getElementById('passwordStrength').style.color = 
                "#2A911B";
            document.getElementById('passwordmeter').style.backgroundColor = 
                "#2A911B";

        }
        inputTimer = undefined;
    }, 500);
};

})();
