/**
 * 
 * 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.initToolBarMail = function ($p) {
    
    /*
     * Meta data
     */
    var meta = $.extend(ox.widgets.toolBar.meta, {
        /*
         * Mail
         */
        mail: {
            "compose": {
                title: _("New E-Mail"),
                icons: ["mail_write.png"],
                big: true,
                visible: function () {
                    // competes with "edit draft" (could show both if support for 1024x768 is stopped
                    return ox.UIController.getFolder() !== ox.api.config.get("mail.folder.drafts");
                }
            },
            "quick-read": {
                title: _("Mark as read"),
                icons: ["mark_as_done.png"],
                big: true,
                requires: ["multiple", "modify"],
                visible: function (ability) {
                    return ability.multiple;
                }
            },
            "reply": {
                title: _("Reply"),
                icons: ["reply.png"],
                big: true,
                requires: ["one"],
                visible: function (ability) {
                    return !ability.multiple;
                }
            },
            "reply-all": {
                title: _("Reply all"),
                icons: ["reply_all.png"],
                big: true,
                requires: ["one"],
                visible: function (ability) {
                    return !ability.multiple;
                }
            },
            "forward": {
                title: _("Forward"),
                icons: ["forward.png"],
                big: true,
                requires: ["some"]
            },
            "delete": {
                title: _("Delete"),
                icons: ["delete.png"],
                big: true,
                requires: ["some", "delete"]
            },
            "edit": {
                title: _("Edit draft"),
                icons: ["draft.png"],
                big: true,
                requires: function (ability) {
                    // current folder is drafts folder?
                    return ox.UIController.getFolder() === ox.api.config.get("mail.folder.drafts");
                },
                visible: function () {
                    // current folder is drafts folder?
                    return ox.UIController.getFolder() === ox.api.config.get("mail.folder.drafts");
                }
            },
            "copy": {
                title: _("Copy"),
                icons: ["mail_copy.png"],
                requires: ["some"]
            },
            "move": {
                title: _("Move"),
                icons: ["mail_move.png"],
                requires: ["some", "delete"]
            },
            "save": {
                title: _("Save"),
                icons: ["send_as_link.png"],
                requires: ["one"]
            },
            "view-source": {
                title: _("Show source"),
                icons: ["mail_source.png"],
                requires: ["one"]
            },
            
            "print": {
                title: _("Print"),
                icons: ["print.png"],
                requires: ["some"]
            },
            "mark-as": {
                title: _("Mark as"),
                icons: ["mark_as.png"],
                requires: ["some"]
            },
            "mark-as-read": {
                title: _("Read"),
                requires: ["some", "modify"]
            },
            "mark-as-unread": {
                title: _("Unread"),
                requires: ["some", "modify"]
            },
            "mark-as-answered": {
                title: _("Answered"),
                requires: ["some", "modify"]
            },
            "mark-as-unanswered": {
                title: _("Unanswered"),
                requires: ["some", "modify"]
            },
            "mark-as-deleted": {
                title: _("Deleted"),
                requires: ["some", "modify"]
            },
            "mark-as-undeleted": {
                title: _("Undeleted"),
                requires: ["some", "modify"]
            },
            /*Attachments*/
            "attachment-open": {
                title: _("Open attachment"),
                icons: ["attachment_open.png"],
                selection: "mail-attachment",
                requires: ["one"]
            },
            "attachment-save": {
                title: _("Save as"),
                icons: ["send_as_attachment.png"],
                selection: "mail-attachment",
                requires: ["one"]
            },
            "attachment-save-infostore": {
                title: _("Save in InfoStore"),
                icons: ["save.png"],
                selection: "mail-attachment",
                requires: ["one", "infostore"],
                mousedown: function(options, e) {
                    if (ox.api.config.get("modules.infostore.module") == false) {
                        corewindow.triggerEvent("Feature_Not_Available", 
                                "modules/mail/save_to_infostore", window);
                    }
                }
            }
        }
    });
    
    // SPAM buttons
    (function () {
        
        // get some config parameter
        var spamButton = ox.api.config.get("mail.spambutton", false);
        var spamFolder = ox.api.config.get("mail.folder.spam");
        
        meta.mail.spam = {
            title: _("Spam"),
            icons: ["spam.png"],
            requires: function (ability, selection) {
                var folder = ox.UIController.getFolder();
                var accountId = ox.api.folder.derive("accountId", folder);
                return ability.some && spamButton === true && accountId === 0 && folder !== spamFolder;
            },
            visible: function (ability, selection) {
                var folder = ox.UIController.getFolder();
                var accountId = ox.api.folder.derive("accountId", folder);
                return spamButton === true && accountId === 0 && folder !== spamFolder;
            }
        };
        
        meta.mail.ham = {
            title: _("No Spam"),
            icons: ["ham.png"],
            requires: function (ability, selection) {
                var folder = ox.UIController.getFolder();
                var accountId = ox.api.folder.derive("accountId", folder);
                return ability.some && spamButton === true && accountId === 0 && folder === spamFolder;
            },
            visible: function (ability, selection) {
                return spamButton === true && ox.UIController.getFolder() === spamFolder;
            }
        };
        
    }());
    
    
    // toggles attachment section
    var toggleAttachmentSection = function (visible) {
        if (currentpath[0] === "mail") {
            // get parent tab
            var tab = ox.widgets.toolBar.tabs.mailEdit;
            var section = tab.children[2];
            if (section.isVisible() != visible) {
                section.setVisible(visible);
                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.mail = new ox.gui.TabMenu(
        $p.getOptions({
            id: "toolbar-mail",
            showSectionNames: false
        })
    );
    
    // new
    tab = tabs.mailCreate = new ox.gui.PanelMenu("toolbar-mail-create",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+N for '&New'
        _("&New")).addTo(toolbar);
    // section
    section = sections.mailCreate = new ox.gui.PanelMenuSection(_("New"), "mailCreateSection").addTo(tab);
    // add items
    add(section, meta.create, "mail-create",
        ["mail", "calendar", "contact", "distributionlist", "task", "file"]
    );
    
    // Bind to attachment selection
    ox.api.event.register("SubSelected", function (selection) {
        ox.ToolBarController.processSelection("mail-attachment", false, selection, true);
        //toggleAttachmentSection(selection.length != 0);
    });
    
    // edit
    tab = tabs.mailEdit = new ox.gui.PanelMenu("toolbar-mail-edit",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+E for '&Edit'
        _("&Edit")).addTo(toolbar);
    // section compose
    section = sections.mailCompose = new ox.gui.PanelMenuSection(_("Compose"), "mailComposeSection").addTo(tab);
    // add items
    add(section, meta.mail, "mail-compose", ["compose", "edit"]);
    // section
    section = sections.mailEdit = new ox.gui.PanelMenuSection(_("Edit"), "mailEditSection").addTo(tab);
    // add items
    add(section, meta.mail, "mail-edit",
        ["quick-read", "reply", "reply-all", "forward", "delete",
         "print", "mark-as",
         "copy", "move",
         "save", "spam", "ham"
        ]
    );
    // add to "mark as"
    add(items["mail-edit-mark-as"], meta.mail, "mail-edit",
        ["mark-as-read", "mark-as-unread",
         "mark-as-answered", "mark-as-unanswered",
         "mark-as-deleted", "mark-as-undeleted"
        ]
    );
        
    
    // attachment (tab for 1024x768 support)
    tab = tabs.mailAttachment = new ox.gui.PanelMenu("toolbar-mail-attachment",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+V for '&View'
        _("&Attachment")).addTo(toolbar);
    section = sections.mailAttachment = new ox.gui.PanelMenuSection(_("Attachment"), "mailAttachmentSection").addTo(tab);
    // add items
    add(section, meta.mail, "mail-attachment",
        [ "attachment-open", "attachment-save", "attachment-save-infostore" ]
    );
    
    // views
    tab = tabs.mailView = new ox.gui.PanelMenu("toolbar-mail-view",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+V for '&View'
        _("&View")).addTo(toolbar);
    // section
    section = sections.mailView = new ox.gui.PanelMenuSection(_("View"), "mailViewSection").addTo(tab);
    // add items
    add(section, meta.view, "mail-view",
        ["vsplit", "hsplit", "list"]
    );

    // Tagging (Flags & Categories)
    tab = tabs.mailTagging = new ox.gui.PanelMenu("toolbar-mail-tag",
        //#. '&' before a letter indicates a shortcut, i.e. Alt+F for '&Flags'
        _("&Flags")).addTo(toolbar);
    // section
    section = sections.mailFlags = new ox.gui.PanelMenuSection(_("Flags"), "mailFlagsSection").addTo(tab);
    // add items
    add(section, meta.flags, "mail-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.mail = new ox.gui.SearchField("ox-topbar-search-mail").
        addListener("widget:search", function(e) {
            triggerEvent("OX_New_Search", ox.api.ui.getActiveModule(), e.data.value);
        });
        
        tab = tabs.mailSearch = new ox.gui.PanelMenu("toolbar-mail-search",
                _("&Search")).addTo(toolbar);
        // section
        section = sections.mailSearch = new ox.gui.PanelMenuSection(_("Search"), "mailSearchSection").addTo(tab);
        // add items
        section.add(ox.widgets.searchField.mail);
    }
    
    
    /*
     * Add handler
     */
    
    // event hash
    var events = {
        // edit mail
        "mail-compose-compose": "OX_NEW_MAIL",
        "mail-compose-edit": "OX_Mail_Edit_Draft",
        "mail-edit-reply": "OX_Mail_Reply",
        "mail-edit-reply-all": "OX_Mail_ReplyAll",
        "mail-edit-forward": "OX_Mail_Forward",
        "mail-edit-delete": "OX_Mail_Delete",
        "mail-edit-copy": "OX_Mail_Copy",
        "mail-edit-move": "OX_Mail_Move",
        "mail-edit-save": "OX_Mail_SaveMail",
        "mail-edit-view-source": "OX_Mail_Show_Source",
        "mail-edit-print": "OX_Print",
        "mail-edit-spam": "OX_Mail_Spam",
        "mail-edit-ham": "OX_Mail_Ham",
        "mail-attachment-attachment-save": "OX_Attachment_Save",
        "mail-attachment-attachment-save-infostore": "OX_Attachment_SaveInfoStore"
    };
    
    // mapping of mail flags
    var mailFlags = {
        "read": "seen", 
        "unread": "unseen",
        "answered": "answer", 
        "unanswered": "answered",
        "deleted": "delete", 
        "undeleted": "undelete"
    };
    
    // add handler function (must return true when action taken)
    ox.ToolBarController.addHandler(function (id) {
        
        // regex matches
        var m;
        
        // defined by event?
        if (events[id] !== undefined) {
            // trigger
            triggerEvent(events[id]);
            return true;
        }
        
        // is mail mark?
        m = id.match(/^(mail-edit-quick|mail-edit-mark-as)-(\w+)$/);
        if (m && m.length) {
            // trigger event
            triggerEvent("OX_Mail_Flag", mailFlags[m[2]]);
            return true;
        }
        
        // individual handlers
        switch (id) {
        case "mail-view-vsplit":
            menuswitchMailView('vsplit');
            return true;
        case "mail-view-hsplit":
            menuswitchMailView('hsplit');
            return true;
        case "mail-view-list":
            menuswitchMailView('list');
            return true;
        case "mail-attachment-attachment-open":
            triggerEvent(menunestedmessage ? "OX_Attachment_Open_Nested" : "OX_Attachment_Open");
            return true;
        }
    });
    
    // add to top-level element
    toolbar.addTo(ox.widgets.toolBar.viewControl);
    
    // "edit" tab is default
    ox.ToolBarController.setDefaultTab(toolbar, 1);
};