/**
 * 
 * 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.initToolBarTasks = function ($p) {
    
    /*
     * Meta data
     */
    var meta = $.extend(ox.widgets.toolBar.meta, {
        /*
         * Tasks
         */
        tasks: {
            "compose": {
                title: _("New task"),
                icons: ["mod_tasks.png"],
                big: true
            },
            "edit": {
                title: _("Edit"),
                icons: ["edit.png"],
                big: true,
                requires: ["one", "modify"]
            },
            "delete": {
                title: _("Delete"),
                icons: ["delete.png"],
                big: true,
                requires: ["some", "delete"]
            },
            "print": {
                title: _("Print"),
                icons: ["print.png"],
                big: true,
                requires: ["some"]
            },
            "change": {
                title: _("Confirmation"),
                icons: ["confirmation_change.png"],
                big: true,
                requires: function (ability, selection) {
                    // one?
                    if (ability.one && !AcceptDeny.visible) {
                        // get task
                        var task = selection[0];
                        // has users
                        if (ox.util.isArray(task.users)) {
                            // get current user
                            var myself = ox.api.config.get("identifier");
                            // loop over users and check if current user is listed
                            var i = 0, users = task.users, $l = users.length;
                            for (; i < $l; i++) {
                                if (users[i].id === myself) {
                                    return true;
                                }
                            }
                        }
                        // has no users or current user is not listed
                        return false;
                    } else {
                        // none, multiple, etc. or AcceptDeny dialog active
                        return false;
                    }
                }
            },
            "move": {
                title: _("Move"),
                icons: ["task_move.png"],
                requires: ["some", "delete"]
            },
            "mark-as-done": {
                title: _("Mark as Done"),
                icons: ["dummy.gif"],
                requires: ["some", "modify"]
            },
            "use-as-template": {
                title: _("Use as template"),
                icons: ["task_copy.png"],
                requires: ["one"]
            },
            /*Attachments*/
            "attachment-open": {
                title: _("Open attachment"),
                icons: ["attachment_open.png"],
                selection: "attachments",
                requires: function(ability) {
                    return ability.one;
                }
            },
            "attachment-save": {
                title: _("Save as"),
                icons: ["send_as_attachment.png"],
                selection: "attachments",
                requires: function(ability) {
                    return ability.one;
                }
            },
            "attachment-save-infostore": {
                title: _("Save in InfoStore"),
                icons: ["save.png"],
                selection: "attachments",
                requires: function(ability) {
                    return ability.one;
                },
                mousedown: function (options, e) {
                    if (ox.api.config.get("modules.infostore.module") == false) {
                        corewindow.triggerEvent("Feature_Not_Available", 
                                "modules/tasks/save_to_infostore", window);
                    }
                }
            },
            // 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 toggleAttachmentSection = function () {
        if (currentpath[0] === "tasks") {
            // get parent tab
            var tab = ox.widgets.toolBar.tabs.tasksEdit;
            var section = tab.children[2];
            var visible = section.isVisible();
            // in attachment tab?
            if (currentpath[2] === "attachment") {
                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.tasks = new ox.gui.TabMenu(
        $p.getOptions({
            id: "toolbar-tasks",
            showSectionNames: false
        })
    );
    
    // new
    tab = tabs.tasksCreate = new ox.gui.PanelMenu("toolbar-tasks-create",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+N for '&New'
        _("&New")).addTo(toolbar);
    // section
    section = sections.tasksCreate = new ox.gui.PanelMenuSection(_("New"), "tasksCreateSection").addTo(tab);
    // add items
    add(section, meta.create, "tasks-create",
        ["mail", "calendar", "contact", "distributionlist", "task", "file"]
    );
    
    // edit
    tab = tabs.tasksEdit = new ox.gui.PanelMenu("toolbar-tasks-edit",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+E for '&Edit'
        _("&Edit")).addTo(toolbar);
    // section
    section = sections.tasksCompose = new ox.gui.PanelMenuSection(_("Compose"), "tasksComposeSection").addTo(tab);
    // add items
    add(section, meta.tasks, "tasks-edit",
        ["compose"]
    );
    // section
    section = sections.tasksEdit = new ox.gui.PanelMenuSection(_("Edit"), "tasksEditSection").addTo(tab);
    // add items
    add(section, meta.tasks, "tasks-edit",
        ["edit", "delete", "print", "change", "move", "mark-as-done", "use-as-template"]
    );
    
    // section attachments
    section = section.tasksAttachment = new ox.gui.PanelMenuSection(_("Attachments"), "tasksAttachmentSection").addTo(tab);
    // add items
    add(section, meta.tasks, "tasks-edit",
            ["attachment-open", "attachment-save", "attachment-save-infostore"]
    );
    
    // view
    tab = tabs.tasksView = new ox.gui.PanelMenu("toolbar-tasks-view",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+V for '&View'
        _("&View")).addTo(toolbar);
    // section
    section = sections.tasksView = new ox.gui.PanelMenuSection(_("View"), "tasksViewSection").addTo(tab);
    // add items
    add(section, meta.tasks, "tasks-view",
        ["hsplit", "list"]
    );
    
    // Tagging (Flags & Categories)
    tab = tabs.tasksTagging = new ox.gui.PanelMenu("toolbar-tasks-tag",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+F for '&Flags'
        _("&Flags")).addTo(toolbar);
    // section
    section = sections.tasksFlags = new ox.gui.PanelMenuSection(_("Flags"), "tasksFlagsSection").addTo(tab);
    // add items
    add(section, meta.flags, "tasks-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.tasks = new ox.gui.SearchField("ox-topbar-search-tasks").
        addListener("widget:search", function(e) {
            triggerEvent("OX_New_Search", ox.api.ui.getActiveModule(), e.data.value);
        });
        
        tab = tabs.tasksSearch = new ox.gui.PanelMenu("toolbar-tasks-search",
                _("&Search")).addTo(toolbar);
        // section
        section = sections.tasksSearch = new ox.gui.PanelMenuSection(_("Search"), "tasksSearchSection").addTo(tab);
        // add items
        section.add(ox.widgets.searchField.tasks);
    }
    
    // attachments section visibile only in attachments tab
    ox.api.event.register("OX_View_Changed", function(){
        toggleAttachmentSection();
        if (currentpath[0] === "tasks" && currentpath[2] !== "attachment") {
            ox.ToolBarController.processSelection("attachments",
                    false, [], true);
        }
    });
    
    /*
     * Add handler
     */
    
    // event hash
    var events = {
        "tasks-edit-compose": "OX_Before_Create_Task",
        "tasks-edit-edit": "OX_Task_Edit",
        "tasks-edit-delete": "OX_Task_Delete",
        "tasks-edit-print": "OX_Print",
        "tasks-edit-change": "OX_Confirmation_Change",
        "tasks-edit-move": "OX_Task_Move",
        "tasks-edit-mark-as-done": "OX_Task_MarkAsDone",
        "tasks-edit-use-as-template": "OX_Task_Duplicate",
        "tasks-edit-attachment-save" : "OX_Attachment_Save",
        "tasks-edit-attachment-save-infostore" : "OX_Attachment_SaveInfoStore"
    };
    
    // 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 "tasks-view-hsplit":
            menuswitchTaskView('split')
            return true;
        case "tasks-view-list":
            menuswitchTaskView('list');
            return true;
            
        case "tasks-edit-attachment-open":
            triggerEvent(menunestedmessage ? "OX_Attachment_Open_Nested" : "OX_Attachment_Open");
            return true;
        }
    });
    
    
    // add to top-level element
    toolbar.addTo(ox.widgets.toolBar.viewControl);

    // initial init
    ox.ToolBarController.processSelection("attachments",false, [], true);
    
    // "edit" tab is default
    ox.ToolBarController.setDefaultTab(toolbar, 1);
};