/**
 * 
 * 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 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, $, equals, register, triggerEvent, menuswitchMailView */

ox.gui.initToolBarCore = function () {
    /*
     * Add common handler
     */
    
    // event hash
    var events = {
        // create new element
        "create-mail": "OX_NEW_MAIL",
        "create-calendar": "OX_Before_Create_Calendar",
        "create-contact": "OX_Before_Create_Contact",
        "create-distributionlist": "OX_Before_Create_Distributionlist",
        "create-task": "OX_Before_Create_Task",
        "create-file": "OX_Before_Create_InfoStore"
    };
    
    ox.ToolBarController.addHandler(function (id) {
        
        // regex matches
        var m;
        
        // is create? (strip prefix first)
        m = id.match(/^\w+-(create-\w+)$/);
        if (m && m.length && events[m[1]] !== undefined) {
            // trigger event
            triggerEvent(events[m[1]]);
            return true;
        }
        
        // is flag/mark?
        m = id.match(/^\w+-flag-(\d+)$/);
        if (m && m.length) {
            // trigger event
            triggerEvent("OX_Add_Flag", m[1]);
            return true;
        }
    });
    
    /*
     * Add root DOM element (just a flying DIV right now)
     */
    var root = $("#toolbar_container")[0];
    
    /*
     * Add top-level view controller (containing all toolbars)
     */
    var control = ox.widgets.toolBar.viewControl = new ox.gui.ViewControl("toolbar-view-control").
        removeCSSClass("oxStretch").
        setParentDOMNode(root).
        addTo(ox.desktop);
    
    /*
     * Bind to UIController
     */
    ox.UIController.dispatcher.bind("modulechange", function (e) {
        // change toolbar to match current module
        var view = ox.widgets.toolBar.views[e.module];
        if (view !== undefined) {
            // change view
            control.showView(view.id);
            // jump to default tab
            ox.ToolBarController.showDefaultTab();
        }
    });
    
    /*
     * Bind to default selection
     */
    ox.api.event.register("Selected", function (selection) {
        // process selection
        ox.ToolBarController.processSelection("default", true, selection);
        // validate top-level control
        ox.widgets.toolBar.viewControl.validate();
    });
    
    // init
    ox.ToolBarController.processSelection("default", true, []);
};
