/**
 * 
 * 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) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Matthias Biggeleben <matthias.biggeleben@open-xchange.com>
 * 
 */

/*jslint bitwise: false, nomen: false, onevar: false, plusplus: false, regexp: false, white: true, browser: true, devel: true, evil: true, forin: true, undef: true, eqeqeq: true, immed: true */

/*global ox, jQuery, $, triggerEvent, menuswitchMailView */

ox.gui.initToolBarInfoStore = function ($p) {
    
    var NAME = "infostore";
    
    /*
     * Meta data
     */
    var meta = $.extend(ox.widgets.toolBar.meta, {
        /*
         * InfoStore
         */
        infostore: {
            compose: {
                title: _("New Infoitem"),
                icons: ["mod_infostore.png"],
                big: true
            },
            "edit": {
                title: _("Edit"),
                icons: ["edit.png"],
                big: true,
                requires: function(ability, selection) {
                    return ability.one && ability.modify &&
                        selection.length == menucountlockable +
                                            menucounteditable;
                }
            },
            "delete": {
                title: _("Delete"),
                icons: ["delete.png"],
                big: true,
                requires: function(ability, selection) {
                    return ability.some && ability["delete"] &&
                        selection.length == menucountlockable +
                                            menucounteditable;
                }
            },
            "print": {
                title: _("Print"),
                icons: ["print.png"],
                big: true,
                requires: function() {
                    return isPrintableView(currentpath2.join('/'));
                }
            },
            "move": {
                title: _("Move"),
                icons: ["infostore_move.png"],
                requires: function(ability, selection) {
                    return ability.some && ability["delete"] &&
                        selection.length == menucountlockable +
                                            menucounteditable;
                }
            },
            "lock": {
                title: _("Lock"),
                icons: ["lock.png"],
                selection: "lockable",
                requires: function(ability, selection) {
                    return ability.some && ability.modify &&
                        menucountlockable == selection.length;
                }
            },
            "unlock": {
                title: _("Unlock"),
                icons: ["unlock.png"],
                selection: "lockable",
                requires: function(ability, selection) {
                    return ability.some && ability.modify &&
                        menucountunlockable == selection.length;
                }
            },
            "as-link": {
                title: _("Send as link"),
                icons: ["send_as_attachment.png"],
                requires: function(ability) {
                    return ox.api.config.get("modules.mail.module") && ability.some;
                },
                mousedown: function (options, e) {
                    if (ox.api.config.get("modules.mail.module") == false) {
                        corewindow.triggerEvent("Feature_Not_Available", 
                                "modules/infostore/send_as_link", window);
                    }
                }
            },
            "as-attachment": {
                title: _("Send as attachment"),
                icons: ["send_as_attachment.png"],
                requires: function (ability, selection) {
                    // module mail disabled or na?
                    if (ox.api.config.get("modules.mail.module") === false) {
                        return false;
                    }
                    // check if selection only contain real files
                    for (var i in selection) {
                        if (selection[i].filename == undefined) {
                            return false;
                        }
                    }
                    return ability.some;
                },
                mousedown: function (options, e) {
                    if (ox.api.config.get("modules.mail.module") === false) {
                        corewindow.triggerEvent("Feature_Not_Available", 
                                "modules/infostore/send_as_attachment", window);
                    }
                }
            },
            /*Version*/
            "version-current": {
                title: _("Current"),
                icons: ["current_version.png"],
                selection: "version",
                requires: function(ability) {
                    return ability.one && ability.modify &&
                        menucountselected == menucountlockable +
                                             menucounteditable;
                }
            },
            "version-delete": {
                title: _("Delete"),
                icons: ["delete.png"],
                selection: "version",
                requires: function(ability) {
                    return ability.some && ability["delete"] &&
                        menucountselected == menucountlockable +
                                             menucounteditable;
                }
            },
            // Views
            "hsplit": {
                title: _("H-Split"),
                icons: ["h_split_view.png"],
                big: true,
                behavior: "radio",
                group: "split-views",
                checked: function () {
                    return currentpath[1] === "split";
                }
            },
            "list": {
                title: _("List"),
                icons: ["list_view.png"],
                big: true,
                behavior: "radio",
                group: "split-views",
                checked: function () {
                    return currentpath[1] === "list";
                }
            }
        }
    });
    
    // toggles attachment section
    var toggleVersionSection = function () {
        if (currentpath[0] === "infostore") {
            // get parent tab
            var tab = ox.widgets.toolBar.tabs.infostoreEdit;
            var section = tab.children[3];
            var visible = section.isVisible();
            // in version tab?
            if (currentpath[2] === "version") {
                if (!visible) {
                    section.setVisible(true);
                    tab.validate();
                }
            } else if (visible) {
                section.setVisible(false);
                tab.validate();
            }
        }
    };
    
    /*
     * Add widgets
     */
    
    // vars
    var tabs = ox.widgets.toolBar.tabs;
    var sections = ox.widgets.toolBar.sections;
    var items = ox.widgets.toolBar.menuItems;
    var toolbar, tab, section;
    
    // fn
    var add = $p.add;
    
    // create toolbar instance
    toolbar = ox.widgets.toolBar.views[NAME] = new ox.gui.TabMenu(
        $p.getOptions({
            id: "toolbar-" + NAME,
            showSectionNames: false
        })
    );
    
    // new
    tab = tabs[NAME + "Create"] = new ox.gui.PanelMenu("toolbar-" + NAME + "-create",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+N for '&New'
        _("&New")).addTo(toolbar);
    // section
    section = sections.infostoreCreate = new ox.gui.PanelMenuSection(_("New"), "infostoreCreateSection").addTo(tab);
    // add items
    add(section, meta.create, NAME + "-create",
        ["mail", "calendar", "contact", "distributionlist", "task", "file"]
    );
    
    // edit
    tab = tabs[NAME + "Edit"] = new ox.gui.PanelMenu("toolbar-" + NAME + "-edit",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+E for '&Edit'
        _("&Edit")).addTo(toolbar);
    // section
    section = sections.infostoreCompose = new ox.gui.PanelMenuSection(_("Compose"), "infostoreComposeSection").addTo(tab);
    // add items
    add(section, meta[NAME], NAME + "-edit",
        ["compose"]
    );
    // section
    section = sections.infostoreEdit = new ox.gui.PanelMenuSection(_("Edit"), "infostoreEditSection").addTo(tab);
    // add items
    add(section, meta[NAME], NAME + "-edit",
        ["edit", "delete", "print", "lock", "unlock", "move"]
    );
    
    section = sections.infostoreSend = new ox.gui.PanelMenuSection(_("Send"), "infostoreSendSection").addTo(tab);
    // add items
    add(section, meta[NAME], NAME + "-send", ["as-attachment", "as-link"]);
    
    // section version
    section = sections.infostoreVersion = new ox.gui.PanelMenuSection(_("Version"), "infostoreVersionSection").addTo(tab);
    // add items
    add(section, meta[NAME], [NAME] + "-version",
            ["version-current", "version-delete"]
    );
    
    // version section visibile only in versions tab
    ox.api.event.register("OX_View_Changed", function(){
        toggleVersionSection();
        if (currentpath[0] === "infostore" && currentpath[2] !== "version") {
            ox.ToolBarController.processSelection("version",
                    false, [], true);
        }
    });
    
    // Bind to version selection
    ox.api.event.register("SubSelected", function (selection) {
        var sel = new Array(selection.length);
        for (var i = 0; i < sel.length; i++) {
            sel[i] = $.extend({}, selection[i], { folder_id: activefolder });
        }
        ox.ToolBarController.processSelection("version", false, sel, true);
    });
    
    // view
    tab = tabs[NAME + "View"] = new ox.gui.PanelMenu("toolbar-" + NAME + "-view",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+V for '&View'
        _("&View")).addTo(toolbar);
    // section
    section = sections.infostoreView = new ox.gui.PanelMenuSection(_("View"), "infostoreViewSection").addTo(tab);
    // add items
    add(section, meta[NAME], NAME + "-view",
        ["hsplit", "list"]
    );

    // Tagging (Flags & Categories)
    tab = tabs[NAME + "Tagging"] = new ox.gui.PanelMenu("toolbar-" + NAME + "-tag",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+F for '&Flags'
        _("&Flags")).addTo(toolbar);
    // section
    section = sections.infostoreFlags = new ox.gui.PanelMenuSection(_("Flags"), "infostoreFlagsSection").addTo(tab);
    // add items
    add(section, meta.flags, NAME + "-flag",
       ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    );
    
    // Add section search when embbedded mode is on
    if (corewindow.embedded) {
        ox.widgets.searchField.infostore = new ox.gui.SearchField("ox-topbar-search-infostore").
        addListener("widget:search", function(e) {
            triggerEvent("OX_New_Search", ox.api.ui.getActiveModule(), e.data.value);
        });
        
        tab = tabs.infostoreSearch = new ox.gui.PanelMenu("toolbar-infostore-search",
                _("&Search")).addTo(toolbar);
        // section
        section = sections.infostoreSearch = new ox.gui.PanelMenuSection(_("Search"), "infostoreSearchSection").addTo(tab);
        // add items
        section.add(ox.widgets.searchField.infostore);
    }
    
    /*
     * Add handler
     */
    
    // event hash
    var events = {
        "infostore-edit-compose": "OX_Before_Create_InfoStore",
        "infostore-edit-edit": "OX_InfoStore_Edit",
        "infostore-edit-delete": "OX_InfoStore_Delete",
        "infostore-edit-print": "OX_Print",
        "infostore-edit-move": "OX_InfoStore_Move",
        "infostore-edit-lock": "OX_InfoStore_Lock",
        "infostore-edit-unlock": "OX_InfoStore_Unlock",
        "infostore-send-as-attachment": "OX_InfoStore_Send_Attachment",
        "infostore-send-as-link": "OX_InfoStore_Send_Link",
        "infostore-version-version-current": "OX_InfoStore_Version_Current",
        "infostore-version-version-delete": "OX_InfoStore_Version_Delete"
    };
    
    // initial init
    ox.ToolBarController.processSelection("version", false, [], true);
    
    // add handler function (must return true when action taken)
    ox.ToolBarController.addHandler(function (id) {        
        // defined by event?
        if (events[id] !== undefined) {
            // trigger
            triggerEvent(events[id]);
            return true;
        }
        
        // individual handlers
        switch (id) {
        case "infostore-view-hsplit":
            menuswitchInfoStoreView('split')
            return true;
        case "infostore-view-list":
            menuswitchInfoStoreView('list');
            return true;
        }
    });
    
    // add to top-level element
    toolbar.addTo(ox.widgets.toolBar.viewControl);
    
    // "edit" tab is default
    ox.ToolBarController.setDefaultTab(toolbar, 1);
};