/* ***** 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.Search
 *
 *
 */
ML.load("utils/misc.js");

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

SearchHandler.prototype =
{
    validateSearchData: function()
    {
        if (document.getElementById("search-data-deck").selectedIndex == 0) {
            alert(this.bundle.GetStringFromName("search.wait"));
            return false;
        }

        if (document.getElementById("search-data-deck").selectedIndex == 2)
            return true;

        el = document.getElementById("search-data-main").getElementsByTagName("textbox");

        for (i = 0; i < el.length; i++)
            if (el[i].value)
                break;

        if (i == el.length) {
            alert(this.bundle.GetStringFromName("search.invalid-data"));
            return false;
        }
        return true;
    },

    getSearchResults: function()
    {
        var el, i, tag;
        var tags = new Array();

        document.getElementById("search-results-deck").selectedIndex = 0;

        if (this.transport) {
            el = document.getElementById("search-data-main").getElementsByTagName("textbox");

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

            jabberService.core.iq.search.searchTag(this.transport, tags);
        }
    },

    showVCard: function()
    {
        var wmediator, it, w, win;
        var jid;

        w = document.getElementById("serch-result-tree");

        if (w.currentIndex < 0)
            return;

        wmediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].
            getService(Components.interfaces.nsIWindowMediator);

        jid = w.contentView.getItemAtIndex(w.currentIndex).firstChild.
            childNodes[4].getAttribute("label");

        it = wmediator.getEnumerator("jim:vcard");

        while (it.hasMoreElements()) {
            w = it.getNext();
            if (w.contact == jid) {
                win = w;
                break;
            }
        }

        if (win)
            win.focus();
        else
            openDialog("chrome://jim/content/vcard.xul", 
                "_blank", "chrome,all,dialog=no", jid);
    },

    addContact: function()
    {
        var wmediator, win, jid;

        win = document.getElementById("serch-result-tree");

        if (win.currentIndex < 0)
            return;

        jid = win.contentView.getItemAtIndex(win.currentIndex).firstChild.
            childNodes[4].getAttribute("label");
        wmediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].
            getService(Components.interfaces.nsIWindowMediator);
        win = wmediator.getMostRecentWindow("jim:add-contact");

        if (win)
            win.focus();
        else
            openDialog("chrome://jim/content/addcontact.xul",
                "_blank", "chrome,all,dialog=yes,modal", jid);
    },

    __getWindowSpec: function(type, from)
    {
        var wmediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].
            getService(Components.interfaces.nsIWindowMediator);
        var it, win;

        it = wmediator.getEnumerator(type);

        while (it.hasMoreElements()) {
            win = it.getNext();
            if (win.contact == from)
                return win;
        }
        return null;
    },

    onLoad: function()
    {
        this.transport = window.arguments[0];
        window.contact = this.transport;

        jabberService.core.iq.search.addObserver(this);

        if (this.transport) {
            setTimeout("window.title='"+this.bundle.formatStringFromName(
                "search.window-title", [this.transport], 1)+"'",0);
            jabberService.core.iq.search.getInfo(this.transport);
        }
    },

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

    onIQSearchInfo: function(from, queryTag)
    {
        var el = document.getElementById("search-data-main");
        var tag;
        var ct;
        var tags = [];

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

        if (ct = queryTag.getElementsByTagName("instructions").item(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();

        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]);
            el.appendChild(tag);
        }
        document.getElementById("search-data-deck").selectedIndex = 1;
    },

    onIQSearchError: function(from, errorCode, errorText)
    {
        if (document.getElementById("search-wizard").currentPage == 
            document.getElementById("search-data"))
        {
            document.getElementById("search-data-error").value =
                this.bundle.formatStringFromName(
                    "error", [errorCode, errorText], 2);
            document.getElementById("search-data-deck").selectedIndex = 2;
            document.getElementById("search-data").next = null;
        } else {
            document.getElementById("search-results-error").value =
                this.bundle.formatStringFromName(
                    "error", [errorCode, errorText], 2);
            document.getElementById("search-results-deck").selectedIndex = 2;
        }

    },

    onIQSearch: function(from, tag)
    {
        var root = document.getElementById("search-result-treechildren");
        var item, row, cell, el;
        var items = tag.getElementsByTagName("item"), i;

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

        for (i = 0; i < items.length; i++) {
            item = document.createElement("treeitem");
            row = document.createElement("treerow");
            item.appendChild(row);

            el = items[i].getElementsByTagName("first").item(0);
            cell = document.createElement("treecell");
            cell.setAttribute("label", el ? domToText(el) : "");
            row.appendChild(cell);

            el = items[i].getElementsByTagName("last").item(0);
            cell = document.createElement("treecell");
            cell.setAttribute("label", el ? domToText(el) : "");
            row.appendChild(cell);

            el = items[i].getElementsByTagName("nick").item(0);
            cell = document.createElement("treecell");
            cell.setAttribute("label", el ? domToText(el) : "");
            row.appendChild(cell);

            el = items[i].getElementsByTagName("email").item(0);
            cell = document.createElement("treecell");
            cell.setAttribute("label", el ? domToText(el) : "");
            row.appendChild(cell);

            cell = document.createElement("treecell");
            cell.setAttribute("label", items[i].getAttribute("jid"));
            row.appendChild(cell);

            root.appendChild(item);
        }

        document.getElementById("search-results-deck").selectedIndex = 1;
    },
}

var searchHandler = new SearchHandler();