/*
 Copyright 2008-2010 Xmarks Inc.

 foxmarks-login.js: Implements the client-side behavior for Account Manager.

 */


var firstTime = true;
var Cc = Components.classes;
var Ci = Components.interfaces;
var JSON = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);

function OnLoad() {
    var iframe = document.getElementById("login-iframe");
    iframe.addEventListener("DOMContentLoaded", FoxmarksIFrameOnLoad, true);
    timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    timer.initWithCallback(timerEvent, 100, Ci.nsITimer.TYPE_REPEATING_SLACK);
    StartIFrame();
}

function OnUnload() {
    if (timer)
        timer.cancel();
}

function StartIFrame() {
    var iframe = document.getElementById("login-iframe");

    var url = Xmarks.gSettings.authUrl;
    var params = [];
    var args = window.arguments[0] || {};
    if (Xmarks.gSettings.username) {
        params.push("_username=" + Xmarks.gSettings.username);
    }
    params.push("_ua=" + Xmarks.FoxmarksVersion());
    params.push("_app=jezebel");
    params.push("_version=" + Xmarks.FoxmarksVersion()); 
    params.push("_remempw=" + (Xmarks.gSettings.rememberPassword ?
            "on" : "off"));
    params.push("_mid=" + Xmarks.gSettings.machineId);
    params.push("_manual=" + String(args.manual == true));
    params.push("_reauth=" + String(args.reauth == true));
    params.push("_express=" + String(args.express == true));
    params.push("_newuser=" + String(args.newuser == true));
    Xmarks.gSettings.sessionID = Date.now().toString(36);
    params.push("_sess=" + Xmarks.gSettings.sessionID);
    params.push("_userjson=" + JSON.encode(Xmarks.gSettings.user));

    if (params.length) {
        url += ("?" + params.join("&"));
    }

    iframe.setAttribute("src", url);
}

var timer;
var isClosing = false;
var timerEvent = { notify: function() { CheckSize(); } }
function CheckSize() {
    if (isClosing) return;  // Don't bother with resize after we've decided
                            // to close.

    var iframe = document.getElementById("login-deck").selectedPanel;
    var width = iframe.contentDocument.body.offsetWidth;
    var height = iframe.contentDocument.body.offsetHeight;

    if (CheckSize.height != height) {
        var newHeight = height + window.outerHeight - window.innerHeight;
        window.resizeTo(window.outerWidth, newHeight ? (newHeight + 1) : 0);
        CheckSize.height = height;
        CheckSize.width = width;
    }
}

function DoCancel() {
    isClosing = true;
    window.arguments[0].status = 2;    // 2 is cancel
    window.close();
}

function DoRetry() {
    document.getElementById("login-deck").selectedIndex = 0;
    StartIFrame();
}

function FoxmarksIFrameOnLoad(event) {
    var pathname = event.originalTarget.location.pathname;
    var query = event.originalTarget.location.search;

    // Extract values from DOM.
    try {
        var form = event.originalTarget.getElementById("user_account_form");
        var formKids = form.childNodes;
    } catch (e) {
        document.getElementById("login-deck").selectedIndex = 2;
        return;
    }

    document.getElementById("login-deck").selectedIndex = 1;

    var obj = {};
    for (var i = 0; i < formKids.length; ++i) {
        if (formKids[i].name) {
            obj[formKids[i].name] = formKids[i].value;
        }
    }

    if (obj["_flag"] == 'cancel') {
        DoCancel();
    } else if (obj["_flag"] == 'done') {
        var user = JSON.decode(obj["_userjson"]);
        Xmarks.gSettings.username = user.xmarksuserid; // Save first.
        Xmarks.gSettings.rememberPassword = obj["_remempw"] == "on";
        Xmarks.gSettings.auth = obj["_auth"];
        Xmarks.gSettings.user = user;                   // Save last.
        isClosing = true;
        window.arguments[0].status = 0;
        window.close();
    } else if (obj["_flag"] == 'url') {
        Xmarks.OpenInNewTab(obj["_url"], true);
        DoCancel();
    }
}

