/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Stefan Preuss <stefan.preuss@open-xchange.com>
 * 
 */

ox.gui.initToppanel = function () {
        
    /*
     * Module Icons
     */
    //var today = new Date(now()).getUTCDate();
    var modules = ox.api.ui.listModules();
    var moduleNodes = {}, selectedModule;
    
    $("#header").css({
        height: "30px",
        backgroundImage: "url('" + getFullImgSrc("img/toolbar/toolbar30.png") + "')"
    }).empty();

    
    $("#notheader").css({
        top: "30px"
    });
    
    var topPanel = ox.widgets.toppanel = new ox.gui.Container("ox-top").
        addTo(ox.desktop).
        setParentDOMNode($("#header")[0]).
        css({
            position: "absolute", right: "18px", 
            bottom: "0px", left: "0px", top: "0px"
        }).
        setLayout(new ox.gui.BorderLayout());
    
    ox.widgets.toppanel.hide = function() {
        this.setVisible(false);
        jQuery("#header").hide();
        jQuery("#notheader").css({ top: "0px" });
    };
    
    ox.widgets.toppanel.show = function() {
        this.setVisible(true);
        jQuery("#notheader").css({ top: "30px" });
        jQuery("#header").show();
    };
    
    var moduleContainer = ox.widgets.moduleNavigation = new ox.gui.Container("ox-modules").
        addTo(topPanel).
        setLayout(new ox.gui.BorderLayout()).
        setLayoutParam({ position: "center" }).
        css({ left: "5px", bottom: "1px" });
   
    
    var changeIconState = ox.UIController.changeIconState = function (name) {
        
        // visual selection
        var select = function (name) {
            $(moduleNodes[name].dom.node).
                css({
                    borderLeft: "1px inset silver",
                    borderRight: "1px inset silver"
                }).
                addClass("background-color-PMG-selection-elements");
        };
        
        var deselect = function (name) {
         // fixed: changed from null to "" due to ie problem
            $(moduleNodes[name].dom.node).
                css({ border: "" }).removeClass("background-color-PMG-selection-elements");
        };
        
        // if module selection hasn't change, return!
        if (selectedModule === name) {
            return;
        }
        
        // remove styles on all nodes first except for expert tree (if active)
        for (var i in moduleNodes) {
            deselect(i);
        }
        
        // update module selection
        if (ox.api.ui.moduleExists(name)) {
            // set selection
            select(name);
            selectedModule = name;
        }
    }
    
    // TODO rename to something not global or move into ox.UIController.
    expertSelection = new ox.gui.Custom(function() {
        var input = this.input = $("<input/>").css({ "float": "left", border: "0px none" }).
        attr({ type: "checkbox", id: "expert-tree" }).
        bind("click", function(event) {
            var flag = $(this).attr("checked");
            track({
                type: "Changed expert mode ",
                text: flag ? "Change to expert mode" : "Change to non-expert mode"
            });
            ox.UIController.setExpertTree(flag);
        });
        
        $(this.dom.node).
        append(input).
        append($("<div/>").css({ "float": "left" }).
                append($("<label/>").attr({ "for": "expert-tree" }).
                        append(addTranslated(_("Expert mode"))))
        );
        // initial state
        if (ox.UIController.showExpertTree) {
            input.attr("checked", "checked");
        }
    });
    
    
    ox.UIController.dispatcher.bind("expertchanged", function (e) {
        // change status only if != current status
        if (expertSelection && expertSelection.input && 
                expertSelection.input.attr("checked") != e.enabled) {
            expertSelection.input.attr("checked", e.enabled);
        }
    });
    
    ox.UIController.bind("modulechange", function (e) {
        changeIconState(e.module);
    });
    
    // loop
    var i = 0, $l = modules.length;
    var factory = function (module) {
        // set icons if not already done
        if (module.icons === undefined) {
            module.icons = ["icons/24/mod_" + module.name + ".png"];
        }
        
        var img = new ox.gui.Image().
        	addCSSClass("ox-top-module-icons").
            setSrc(getFullImgSrc(module.icons[0])).
            setTitle(module.title).
            setLayoutParam({ position: "left", width: 30, textAlign: "center" }).
            css({ padding: "2px" });
                
        // module activated?
        if (module.disabled) {
            // change opacity
            img.css({ opacity: 0.25 });
        	// trigger upsell if feature is disabled
        	img.addListener("click", function (e) {
                triggerEvent("Feature_Not_Available", "modules/" + module.name);
        	});
        } else {
        	// bind click to icon
            img.css({ cursor: "pointer" }).
            addListener("click", function (e) {
                
                track({
                    type: "Click on module icon",
                    text: "Change to module " + module.name
                });
                
                ox.UIController.setModule({ module: module.name, folder: "auto" });
            });
        }

        // add image to container
        moduleContainer.add(img);
        moduleNodes[module.name] = img;
    };
    
    for (; i < $l; i++) {
        factory(modules[i]);
    }

    // adding checkbox to toggle expert
    moduleContainer.add(
            expertSelection.
            setLayoutParam({ position: "center" }).
            css({ margin: "5px 0 0 20px" })
    );


    //---- Logout button

    new ox.gui.Button("ox-topbar-logout", _("Logout"), function() {
        triggerEvent("Logout");
    }).addTo(topPanel).
    setLayoutParam({ position: "right", width: 120, valign: "top", align: "right" }).
    css({ position: "absolute", top: "5px", right: "0px" });
    
    //----- search bar
    ox.widgets.searchField = {
            active: function() {
                if (this[ox.api.ui.getActiveModule()])
                    return this[ox.api.ui.getActiveModule()];
                else
                    return this.top;
            }
    }
    
    ox.widgets.searchField.top = new ox.gui.SearchField("ox-topbar-search", { disabled: true }).
    addTo(topPanel).
    setLayoutParam({ position: "right", width: "260px" }).
    css({ position: "absolute", top: "5px", bottom: "4px", left: "0px", right: "0px" }).
    addListener("widget:search", function(e) {
        triggerEvent("OX_New_Search", ox.api.ui.getActiveModule(), e.data.value);
    });
    
    
    //----- buttons
    
    var buttons = new ox.gui.Container("ox-buttons").
    addTo(topPanel).
    setLayout(new ox.gui.HBoxLayout()).
    setLayoutParam({ position: "right", width: "200px" }).
    css({ position: "absolute", top: "3px", right: "10px" });
    
    
    var loading = new ox.gui.Image().
    addCSSClass("ox-top-module-buttons").
    css({ cursor: "pointer" }).
    setLayoutParam({ width: "20px" }).
    setSrc(getFullImgSrc("img/toolbar/tb_loading.gif")).
    setTitle(_("Refresh")).
    addListener("click", function (e) {
        triggerEvent("OX_Refresh");
    });
    
    buttons.add(loading);
    
    setLoading = function(enabled) {
        loading.setSrc(getFullImgSrc(enabled ? 
                "img/toolbar/ox_animated.gif" : "img/toolbar/tb_loading.gif"));
        loading.setTitle(enabled ? _("Loading...") : _("No activity"));
    };
    
    var cursor = null;
    setLoadingCursor = function(enabled) {
        if (IE) return; // Changing the cursor triggers mouseup in IE
        if (enabled) {
            if (!cursor){
                cursor = setMouseCursor("wait");
            }
        } else if (cursor) {
            removeMouseCursor(cursor);
            cursor = null;
        }
    };
    
    // Listen to legacy event.
    register("Loading", function(isLoading) {
        setLoading(enabled);
        setLoadingCursor(enabled);
    });
    
    var help = new ox.gui.Image().
    addCSSClass("ox-top-module-buttons").
    css({ cursor: "pointer" }).
    setLayoutParam({ width: "20px" }).
    setSrc(getFullImgSrc("img/toolbar/help.gif")).
    setTitle(_("Help"));

    buttons.add(help);
    
    var menu = globalContextMenus.help = new PulldownMenu(help.dom.node);
    menu.addItem(new MenuItem(_("Help"),
        function() { triggerEvent("OX_Show_Help", help_location); }));
    menu.addItem(new MenuItem(_("Error messages"),
        function() { showErrorinPopup(); }));
    menu.addItem(new MenuItem(_("About"),
        function() { triggerEvent("OX_Show_About"); }));

};