/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JIM.
 *
 * The Initial Developer of the Original Code is
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * scripts.uiscripts.AddAccount
 *
 *
 */
ML.load("utils/misc.js");

function AddAccountHandler()
{
    this.bundle = getStringBundle("chrome://jim/locale/jim.properties");
}

AddAccountHandler.prototype =
{
    modeAdvance: function()
    {
        if (document.getElementById("mode-radio-create").selected)
            document.getElementById("mode").next="select-server";
        else
            document.getElementById("mode").next="account-info";
    },

    finish: function()
    {
        var server, port, user, pass, name, resource, rememberPass;

        if (document.getElementById("add-account-wizard").currentPage.id == "account-creation-result") {
            var tags = document.getElementById("new-account-info-deck-main").getElementsByTagName("textbox");

            server = document.getElementById("select-server-server").value;
            port = document.getElementById("select-server-port").value;
            useSSL = document.getElementById("select-use-ssl").checked;
            name = document.getElementById("account-creation-result-name").value;
            resource = document.getElementById("account-creation-result-resource").value;
            rememberPass = document.getElementById("account-creation-result-remember-pass").checked;

            for (i = 0; i < tags.length; i++)
                if (tags[i].getAttribute("name") == "username")
                    user = tags[i].value;
                else if (tags[i].getAttribute("name") == "password")
                    pass = tags[i].value;
        } else if (document.getElementById("add-account-wizard").currentPage.id == "account-info") {
            name = document.getElementById("account-info-name").value;
            user = document.getElementById("account-info-username").value;
            pass = document.getElementById("account-info-password").value;
            server = document.getElementById("account-info-server").value;
            port = document.getElementById("account-info-port").value;
            resource = document.getElementById("account-info-resource").value;
            rememberPass = document.getElementById("account-info-remember-pass").checked;
            useSSL = document.getElementById("account-info-use-ssl").checked;
        }

        if (server && port && user && (!rememberPass || pass) && name && resource) {
            if (jabberService.core.highlevel.accounts.hasAccountInfo(name)) {
                alert(this.bundle.GetStringFromName("addAccountAccountExists"));
                return false;
            }
            jabberService.core.highlevel.accounts.setAccountInfo(name, user, rememberPass ? pass : null,
                resource, server, port, useSSL);
            return true;
        }
        alert(this.bundle.GetStringFromName("addAccountIncompleteAccountInfo"));
        return false;
    },

    createServerValidate: function(event)
    {
        if (document.getElementById("select-server-port").value && 
            document.getElementById("select-server-server").value)
        {
            if (document.getElementById("select-server-port").value.search(/^\d+$/) != -1)
                return true;
            alert(this.bundle.GetStringFromName("addAccountInvalidPortFormat"));
            return false;
        } else {
            alert(this.bundle.GetStringFromName("addAccountInvalidServerPort"));
            return false;
        }
    },

    newAccountInfoValidate: function(event)
    {
        var el, tags = [], tag;

        if (document.getElementById("new-account-info-deck").selectedIndex == 0) {
            alert(this.bundle.GetStringFromName("addAccountNewAccountWait"));
            return false;
        }
        if (document.getElementById("new-account-info-deck").selectedIndex == 2) {
            alert(this.bundle.GetStringFromName("addAccountNewAccountError"));
            return false;
        }

        el = document.getElementById("new-account-info-deck-main").getElementsByTagName("textbox");

        for (i = 0; i < el.length; i++) {
            tag = DB.createElement("jabber:iq:register", el[i].getAttribute("name"));
            tag.addText(el[i].value);
            tags.push(tag);
        }

        jabberService.core.iq.register.registerTag(null, tags);
        return true;
    },

    useSSLChecked: function(checkBox, textBox)
    {
        var state = checkBox.checked;
        var port = document.getElementById(textBox);

        if (state && port.value == 5222)
            port.value = 5223;
        else if (!state && port.value == 5223)
            port.value = 5222;
    },

    getRegistrationInfo: function()
    {
        document.getElementById("new-account-info-deck").selectedIndex = 0;
        jabberService.disconnect();
        setTimeout("addAccountHandler.lazyGetRegistrationInfo()", 100);
    },

    lazyGetRegistrationInfo: function()
    {
        if (jabberService.connected)
            setTimeout("addAccountHandler.lazyGetRegistrationInfo()", 100);
        else {
            jabberService.connect(document.getElementById("select-server-server").value,
                document.getElementById("select-server-port").value,
                document.getElementById("select-use-ssl").checked);
            jabberService.core.iq.register.getInfo();
        }
    },

    onLoad: function()
    {
        jabberService.core.iq.register.addObserver(this);
    },

    onUnload: function()
    {
        jabberService.core.iq.register.removeObserver(this);
        jabberService.disconnect();
    },

    onIQRegisterInfo: function(from, queryTag)
    {
        var el = document.getElementById("new-account-info-deck-main");
        var tag;
        var ct;
        var tags = [];

        while (el.hasChildNodes())
            el.removeChild(el.firstChild);

        if (ct = queryTag.getElementsByTagName("instructions")[0]) {
            tag = document.createElement("description");
            tag.appendChild(document.createTextNode(domToText(ct)));
            el.appendChild(tag);
        }

        for (i = 0; i < queryTag.childNodes.length; i++)
            if (queryTag.childNodes[i].nodeType == queryTag.ELEMENT_NODE &&
                queryTag.childNodes[i].nodeName != "instructions")
                tags.push(queryTag.childNodes[i].nodeName);

        tags.sort(function (a,b) { if (a == "username") return -1; if (b == "username") return 1;
            if (a == "password") return -1; if (b == "password") return 1; return a < b ? -1 : a == b ? 0 : 1;
        });

        for (i = 0; i < tags.length; i++) {
            tag = document.createElement("label");
            tag.setAttribute("value", tags[i]);
            el.appendChild(tag);
            tag = document.createElement("textbox");
            tag.setAttribute("name", tags[i]);
            if (tags[i] == "password")
                tag.setAttribute("type", "password");
            el.appendChild(tag);
        }
        document.getElementById("new-account-info-deck").selectedIndex = 1;
    },

    onIQRegisterError: function(from, errorCode, errorText)
    {
        if (document.getElementById("add-account-wizard").currentPage == 
            document.getElementById("new-account-info")) 
        {
            document.getElementById("new-account-info-deck-error").value = this.bundle.formatStringFromName(
                "error", [errorCode, errorText], 2);
            document.getElementById("new-account-info-deck").selectedIndex = 2;
        } else if (document.getElementById("add-account-wizard").currentPage == 
            document.getElementById("account-creation-result"))
        {
            document.getElementById("account-creation-result-deck-error").value = this.bundle.formatStringFromName(
                "error", [errorCode, errorText], 2);
            document.getElementById("account-creation-result-deck").selectedIndex = 2;
        }
    },

    onIQRegister: function(from)
    {
        if (document.getElementById("add-account-wizard").currentPage == 
            document.getElementById("account-creation-result"))
        {
            document.getElementById("account-creation-result-deck").selectedIndex = 1;
        }
    },

}

var addAccountHandler = new AddAccountHandler();