/**
 * 
 * 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) 2003-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Jan Finsel <jan.finsel@open-xchange.com>
 * 
 */

var menulastviews = new Object();
var lastCalendarTimeRanges = { detail: "overview" }, configparentfolder = -1;
var menudisableattachment = false, menucountunlockable = 0;
var menucounteditable = 0, menucountselected = 0;
var menucountsubselected = 0, menunestedmessage = false;
var menuisdraftfolder = false, menuselectedobjects = new Array();
var menuselectedfolders = new Object(), menuglobalzaehler=0;
var menumailfoldertreecopy = false, menucountlockable = 0;

function initContents(modules) {
    if (modules !== "core") {
        return;
    }
    register("Loaded", function () {
        menumailloaded();
        menucalendarloaded();
        menucontactloaded();
        menuinfostoreloaded();
        menuregisterMailContents();
        menuregisterCalendarContents();
        menuregisterContactContents();
        menuregisterTaskContents();
        if (configGetKey("modules.infostore.module")) {
            menuregisterInfoStoreContents();
        }
        register("OX_Configuration_Move_Folder", function () {
            // get folder first in order to get its module
            ox.api.folder.get({
                folder: configfolder,
                success: function (data) {
                    createMenuPopUpTree("menu_configuration_folder_folderpopup", 
                            data.module, function (data) {
                        jQuery("#menu_configuration_folder_folderpopup").hide();
                        ox.api.folder.get({
                            folder: configfolder,
                            success: function (folder) {
                                ox.api.folder.move(folder, data);
                            }
                        });
                    });
                    jQuery("#menu_configuration_folder_folderpopup").show();
                }
            });
        });
    });
}

function menumailloaded() {
    // create "Mark as" submenu
    var markas_submenu = new PopupMenu();
    var entries = {
            seen: _("Read"), unseen: _("Unread"),
            answer: _("Answered"), answered: _("Unanswered"),
            "delete": _("Deleted"), undelete: _("Undeleted")
    };
    (function fillItems(menu) {
        var items = {};
        for (var i in entries) {
            var item = items[i] = new MenuItem(entries[i], (function(flag) {
                return function() { triggerEvent("OX_Mail_Flag", flag); };
            })(i));
            menu.addItem(item);
        }
        menu.onShow = function() {
            var r = menucheckRight("READ");
            items.seen.setVisible(r);
            items.unseen.setVisible(r);
            var d = menucheckRight("DELETE");
            items["delete"].setVisible(d);
            items.undelete.setVisible(d);
            var w = menucheckRight("WRITE");
            items.answer.setVisible(w);
            items.answered.setVisible(w);
        };
    })(markas_submenu);
    
    var menu = globalContextMenus.mail = new ContextMenu();
    function one() { this.setEnabled(this.getContext().count == 1); }
    function many() { this.setEnabled(this.getContext().count > 0); }
    var items = [
    {
        text: _("Reply"), icon: "img/mail/reply",
        event: "OX_Mail_Reply", show: one
    }, {
        text: _("Reply all"), icon: "img/mail/reply_all",
        event: "OX_Mail_ReplyAll", show: one
    }, {
        text: _("Forward"), icon: "img/mail/forward",
        event: "OX_Mail_Forward", show: many
    }, {
        text: _("Delete"), icon: "img/menu/delete",
        event: "OX_Mail_Delete", show: many
    }, {
        text: _("Print"), icon: "img/menu/print",
        event: "OX_Print", show: many
    }, {
        //-----------------------
    }, {
        text: _("Mark as"), icon: "img/mail/mark_as",
        items: markas_submenu, show: many
    }, {
        //-----------------------
    }, {
        text: _("Save"), icon: "img/menu/save_as_link",
        event: "OX_Mail_SaveMail", show: one
    }, {
        text: _("Copy"), icon: "img/menu/copy_mail",
        event: "OX_Mail_Copy", show: many
    }, {
        text: _("Move"), icon: "img/menu/mail_move",
        event: "OX_Mail_Move", show: many
    }, {
        //-----------------------
    }, {
        text: _("Edit draft"), icon: "img/menu/edit_draft",
        icon_d: "img/dummy.gif", event: "OX_Mail_Edit_Draft",
        show: function() {
            this.setVisible(menuisdraftfolder);
            this.setEnabled(this.getContext().count == 1);
        }
    }, {
        text: _("Show source"), icon: "img/menu/view_emailsource",
        event: "OX_Mail_Show_Source", show: one
    }, {
        text: _("Spam"), icon: "img/mail/spam",
        event: "OX_Mail_Spam", show: function() { 
            this.setVisible(   this.getContext().count > 0
                            && configGetKey("mail.spambutton")
                            && checkSpamFolder("SPAM")
                            && getMailAccountIdByFolder(this.getContext().getSelected()[0].folder_id) == 0);
        }
    }, {
        text: _("No Spam"), icon: "img/menu/ham",
        icon_d: "img/menu/ham.gif", event: "OX_Mail_Ham",
        show: function() {
            this.setVisible(   menucountselected > 0
                            && configGetKey("mail.spambutton")
                            && checkSpamFolder("HAM")
                            && getMailAccountIdByFolder(this.getContext().getSelected()[0].folder_id) == 0);
        }
    }];
    for (var i in items) {
        (function(def) {
            if (def.text) {
                var item = new MenuItem(def.text,
                        def.event ? function() { triggerEvent(def.event); } :
                            def.items
                );
                item.setIcon(def.icon + ".gif", def.icon_d || def.icon + "_d.gif");
                item.onShow = def.show;
            } else {
                var item = new MenuSeparator();
            }
            menu.addItem(item);
        })(items[i]);
    }
}
function menuregisterMailContents() {
    register("OX_Mail_Move",menumailmoveclicked);
    register("OX_Mail_Copy",menumailcopyclicked);
}   

function menumailmoveclicked() {
    menumailfoldertreecopy=false;
    createMenuPopUpTree("menu_mail_move_foldertree","mail",doMailsFolder);
    document.getElementById("menu_mail_move_foldertree").style.display="";
} 

function menumailcopyclicked() {
    menumailfoldertreecopy=true;
    createMenuPopUpTree("menu_mail_move_foldertree","mail",doMailsFolder);  
    document.getElementById("menu_mail_move_foldertree").style.display="";
} 

function doMailsFolder(data) {
    var selectedfolderid = data.id;
    if(menumailfoldertreecopy) {
        triggerEvent("OX_Object_Copy",selectedfolderid);
    } else {
        triggerEvent("OX_Object_Move",selectedfolderid);
    }
    document.getElementById("menu_mail_move_foldertree").style.display="none";
}

function checkSpamFolder(type) {
    for(var i in menuselectedobjects) {
        var folder = menuselectedobjects[i].folder;
        if(!folder) folder= menuselectedobjects[i].folder_id;
        switch(type) {
            case "SPAM":
                if(folder == configGetKey("mail.folder.spam")) {
                    return false;
                }           
                break;
            case "HAM":
                if(folder != configGetKey("mail.folder.spam")) {
                    return false;
                }
                break;
            default:
                return false;
        }
    }
    return true;
}

/****************************************************************************************************/
/*** Calendar Function ******************************************************************************/
/****************************************************************************************************/
function menucalendarloaded() { 
    var contextData = [];
    var count = Value(), writable = Value(), deletable = Value(), isPrivate = Value();
    var confirmable = Value(), acceptDenyVisible = Value();
    
    function drawCatsList(cats_sub, cats) {
        // remove all sub nodes first
        cats_sub.removeAllItems();
        
        // delete menu
        var del = new MenuItem(_("Delete all Categories"),
                function() { triggerEvent('OX_Delete_All_Categories'); }
        );
        del.setEnabledF(function() { return cats.length > 0; });
        cats_sub.addItem(del);      
        
        // spacer
        cats_sub.addItem(new MenuSeparator());
        
        // category menu items (with color div)
        var categories = (ox.categories.list() || []); 
        var $l = (categories.length > 10 ? 10 : categories.length); 
        for (var i=0; i < $l; i++) {
            var item = new MenuItem(noI18n(categories[i].name),
                (function(category) {
                    return function() {
                        triggerEvent('OX_Add_Categories', [ category ]);
                    };
                })(categories[i].name));        
            cats_sub.addItem(item);
            
            // drawing color divs and append as new menu item
            var node = item.node;
            var text = node.firstChild;
            removeChildNodes(node);
            node.appendChild(newnode("div", 
                    { flt: "left", margin: "3px 5px 0 0" }, 
                    { className: "colorLabelCont bs ha colorLabel" + (categories[i].color || 0) }));
            node.appendChild(text);
        }
        
        // spacer
        cats_sub.addItem(new MenuSeparator());
        
        // all categories menu item (to open dialog)
        cats_sub.addItem(
                new MenuItem(_("All Categories..."),
                    function() { triggerEvent('OX_All_Categories'); }
                )
        );
    }
    
    var menu = globalContextMenus.calendar = new ContextMenu();   
    
    var edit = new MenuItem(_("Edit"),
        function() { triggerEvent('OX_Calendar_Edit'); });
    edit.setIcon("img/menu/edit.gif", "img/menu/edit_d.gif");
    edit.setEnabledF(function() { 
        return count() == 1 && writable() && !isPrivate(); 
    });
    menu.addItem(edit);

    var cats_s1 = new PopupMenu();
    cats_s1.onShow = function() {
        // getting selected apps
        var apps = contextData;     
        // create consolidated list of categories
        var cats = [];
        for (var i in apps) {
            if (apps[i].categories) {
                cats.push(apps[i].categories);
            }
        }
        drawCatsList(cats_s1, cats);
    };
    
    var cats = new MenuItem(_("Categories"),
            cats_s1); 
    cats.setIcon("img/mail/mark_as.gif", "img/mail/mark_as_d.gif");
    cats.setEnabledF(function() { return count() > 0 && !isPrivate(); });
    menu.addItem(cats);
    
    var del = new MenuItem(_("Delete"),
        function() { triggerEvent('OX_Calendar_Delete'); });
    del.setIcon("img/menu/delete.gif", "img/menu/delete_d.gif");
    del.setEnabledF(function() { return count() > 0 && deletable() && !isPrivate(); });
    menu.addItem(del);
    
    menu.addItem(new MenuSeparator());

    var confirm = new MenuItem(_("Change confirmation"), function() {
        var objects = new Array(contextData.length);
        for (var i = 0; i < objects.length; i++) {
            objects[i] = new AcceptDenyObject("calendar", contextData[i]);
        }
        (new AcceptDeny(true)).showConfirmation(objects);
    });
    confirm.setIcon("img/menu/global_confirmation_change.gif",
                    "img/menu/global_conf_change_d.gif");
    confirm.setEnabledF(function() {
        return count() > 0 && !acceptDenyVisible() && confirmable() && !isPrivate();
    });
    menu.addItem(confirm);

    menu.onShow = function() {
        acceptDenyVisible.set(AcceptDeny.visible);
        var objects = clone(this.getContext().getSelected());
        count.set(objects.length);
        if (!objects.length) return;
        for (var i = 0; i < objects.length; i++) {
            objects[i].module = "calendar";
            objects[i].folder_id = objects[i].folder;
            delete objects[i].folder;
        }
        writable.clear();
        deletable.clear();
        confirmable.clear();
        isPrivate.clear();
        var collection = { columns: [ "created_by", "users", "title", "location",
                                     "start_date", "end_date", "categories", "private_flag" ],
                           objects: objects };
        
        OXCache.newRequest(null, "calendar", collection, null, responseData);

        function responseData(data) { 
            contextData = data.objects; 
            ox.api.folder.get({
                folder: activefolder,
                success: function(response){
                    handleResponse(response, contextData);
                }
            });
        }
        function handleResponse(folder, contextData) {
            writable.set(menuhasRight(contextData, "WRITE"));
            deletable.set(menuhasRight(contextData, "DELETE"));
            if (!writable.value) {
                confirmable.set(false);
            }
            isPrivate.set(false);
            var shared = folder.created_by != configGetKey('identifier');
            var tmpPrivate = false;
            var me = folder.type == 3 ? folder.created_by
                                      : configGetKey("identifier");
            for (var i in contextData) {
                var users = contextData[i].users;
                if (shared == true && contextData[i].private_flag == true) {
                    isPrivate.set(true);
                }
                CheckUsers: {
                    for(var j = 0; j < users.length; j++) {
                        if (users[j].id == me) {
                            confirmable.set(true);
                            break CheckUsers;
                        }
                    }
                    confirmable.set(false);
                    return;
                }
            }            
        }
    };
    
    
    // Team view context menu
    var menu = globalContextMenus.teamview = new ContextMenu();
    
    // Edit
    var edit = new MenuItem(_("Edit"),
        function() { triggerEvent('OX_Calendar_Edit'); });
    edit.setIcon("img/menu/edit.gif", "img/menu/edit_d.gif");
    edit.setEnabledF(function() { return count() == 1; });
    menu.addItem(edit);
    
    var cats_s2 = new PopupMenu();
    cats_s2.onShow = function() {
        // getting selected apps
        var apps = clone(this.getContext().getSelectedItems());
        // create consolidated list of categories
        var cats = [];
        for (var i in apps) {
            if (apps[i].categories) {
                cats.push(apps[i].categories);
            }
        }
        drawCatsList(cats_s2, cats);
    };
    
    var cats = new MenuItem(_("Categories"),
            cats_s2); 
    cats.setIcon("img/mail/mark_as.gif", "img/mail/mark_as_d.gif");
    cats.setEnabledF(function() { return count() > 0; });
    menu.addItem(cats);
    
    // Delete
    var del = new MenuItem(_("Delete"),
        function() { triggerEvent('OX_Calendar_Delete'); });
    del.setIcon("img/menu/delete.gif", "img/menu/delete_d.gif");
    del.setEnabledF(function() { return count() > 0; });
    menu.addItem(del);
    
    menu.onShow = function() {
        // get number of selected appointments
        var c = this.getContext().numSelected();
        count.set(c);        
    };
}

function menuregisterCalendarContents() {
    register("OX_Calendar_Move", menucalendarmoveclicked);
}
function menucalendarmoveclicked() {
    createMenuPopUpTree("menu_calendar_move_foldertree","calendar", moveCalendarFolder);
    jQuery("#menu_calendar_move_foldertree").show();
} 
function moveCalendarFolder(data) {
    var selectedfolderid = data.id;
    triggerEvent("OX_Object_Move", selectedfolderid);
    jQuery("#menu_calendar_move_foldertree").hide();
}

/****************************************************************************************************/
/*** Task Function ******************************************************************************/
/****************************************************************************************************/
function menutasksloaded() {
    addOnClose($('menu_tasks_move_foldertree'), function () { 
        $('menu_tasks_move_foldertree').style.display = "none";
    });
}

function menuregisterTaskContents() {
    register("OX_Task_Move", menutaskmoveclicked);
}

function menutaskmoveclicked() {
    createMenuPopUpTree("menu_tasks_move_foldertree","tasks",moveTasksFolder);
    document.getElementById("menu_tasks_move_foldertree").style.display="";
} 

function moveTasksFolder(data) {
    var selectedfolderid = data.id;
    triggerEvent("OX_Object_Move",selectedfolderid);
    document.getElementById("menu_tasks_move_foldertree").style.display="none";
}

/****************************************************************************************************/
/*** Contact Function ******************************************************************************/
/****************************************************************************************************/
var menucontactfoldertreecopy=false;
function menucontactloaded() {
    var menu = globalContextMenus.contacts = new ContextMenu();
    var count = Value(), writable = Value(), deletable = Value();
    
    // Edit contact
    var edit = new MenuItem(_("Edit"),
        function() { triggerEvent('OX_Contact_Edit'); });
    edit.setIcon("img/menu/edit.gif", "img/menu/edit_d.gif");
    edit.setEnabledF(function() { return count() == 1 && writable(); });
    menu.addItem(edit);
    
    // Delete contact
    var del = new MenuItem(_("Delete"),
        function() { triggerEvent('OX_Contact_Delete'); });
    del.setIcon("img/menu/delete.gif", "img/menu/delete_d.gif");
    del.setEnabledF(function() { return count() > 0 && deletable(); });
    menu.addItem(del);
    
    // Use contact as template
    var template = new MenuItem(_("Use as template"),
        function() { triggerEvent('OX_Contact_Duplicate'); });
    template.setIcon("img/menu/duplicate_contacts.gif",
                     "img/menu/duplicate_contacts_d.gif");
    template.setEnabledF(function() { return count() == 1 && writable(); });
    menu.addItem(template);
    
    // Send contact as vCard
    var sendVCard = new MenuItem(_("Send as vCard"),
        function() { triggerEvent('OX_Contact_SendVCard'); });
    sendVCard.setIcon("img/mail/forward.gif", "img/mail/forward_d.gif");
    sendVCard.setEnabledF(function() { return count() > 0 });
    menu.addItem(sendVCard);

    // context menu - onShow handler
    menu.onShow = function() {
        var collection = { columns: ["created_by"],
                           objects: this.getContext().getSelected() };
        count.set(collection.objects.length);
        if (!count.value) return;
        OXCache.newRequest(null, "contacts", collection, null, responseData);
        function responseData(data) {
            writable.set(menuhasRight(data.objects, "WRITE"));
            deletable.set(menuhasRight(data.objects, "DELETE"));
        }
    };
}

function menuregisterContactContents() {
    register("OX_Contact_Move",menucontactmoveclicked);
    register("OX_Contact_Copy",menucontactcopyclicked);
}
function menucontactmoveclicked() {
    createMenuPopUpTree("menu_contacts_move_foldertree","contacts",doContactsFolder);
    document.getElementById("menu_contacts_move_foldertree").style.display="";
    menucontactfoldertreecopy=false;
} 

function menucontactcopyclicked() {
    createMenuPopUpTree("menu_contacts_move_foldertree","contacts",doContactsFolder);
    document.getElementById("menu_contacts_move_foldertree").style.display="";
    menucontactfoldertreecopy=true;
} 

function doContactsFolder(data) {
    var selectedfolderid = data.id;
    if (menucontactfoldertreecopy) {
        triggerEvent("OX_Object_Copy",selectedfolderid);
    } else {
        triggerEvent("OX_Object_Move",selectedfolderid);
    }
    document.getElementById("menu_contacts_move_foldertree").style.display="none";
}

/****************************************************************************************************/
/*** InfoStore Function ******************************************************************************/
/****************************************************************************************************/

function menuinfostoreloaded() {
    var menu = globalContextMenus.infostore = new ContextMenu();
    var contextData = [];
    var count = Value(), readable = Value(), writable = Value();
    var editable = Value(), deletable = Value(), lockable = Value();
    var unlockable = Value(), hasFile = Value();;
    
    var edit = new MenuItem(_("Edit"),
        function() { triggerEvent('OX_InfoStore_Edit'); });
    edit.setIcon("img/menu/edit.gif", "img/menu/edit_d.gif");
    edit.setEnabledF( function() {
        return count() == 1 && writable() && editable();
    });
    menu.addItem(edit);
    
    var del = new MenuItem(_("Delete"),
        function() { triggerEvent('OX_InfoStore_Delete'); });
    del.setIcon("img/menu/delete.gif", "img/menu/delete_d.gif");
    del.setEnabledF(function() {
        return count() > 0 && lockable() && deletable();
    }); 
    menu.addItem(del);
    
    menu.addItem(new MenuSeparator());
    
    var lock = new MenuItem(_("Lock"),
        function() { triggerEvent('OX_InfoStore_Lock'); });
    lock.setIcon("img/menu/sperren.gif", "img/menu/sperren_d.gif");
    lock.setEnabledF(function() {
        return count() > 0 && writable() && lockable();
    });
    menu.addItem(lock);
    
    var unlock = new MenuItem(_("Unlock"),
        function() { triggerEvent('OX_InfoStore_Unlock'); });
    unlock.setIcon("img/menu/entsperren.gif", "img/menu/entsperren_d.gif");
    unlock.setEnabledF(function() {
        return count() > 0 && writable() && unlockable();
    });
    menu.addItem(unlock);
    
    menu.addItem(new MenuSeparator());
    
    var attach = new MenuItem(_("Send as attachment"),
        function() { triggerEvent('OX_InfoStore_Send_Attachment'); });
    attach.setIcon("img/menu/alsanlagesenden.gif",
                   "img/menu/alsanlagesenden_d.gif");
    attach.setEnabledF(function() { return count() > 0 && readable(); });
    menu.addItem(attach);
    
    var link = new MenuItem(_("Send as link"),
        function() { triggerEvent('OX_InfoStore_Send_Link'); });
    link.setIcon("img/menu/save_as_link.gif", "img/menu/save_as_link_d.gif");
    link.setEnabledF(function() { return count() > 0 && readable() && ("infostore_sendLink" in window);  });
    menu.addItem(link);
    
    var open = new MenuItem(_("Open"), function() {
        triggerEvent('OX_InfoStore_Open_Attachment', contextData);
    });
    open.setIcon("img/mail/open_ISattachment.gif",
                 "img/mail/open_ISattachment_d.gif");
    open.setEnabledF(function() { return count() >= 1 && hasFile(); });
    menu.addItem(open);
    
    var save = new MenuItem(_("Save"), function() {
        triggerEvent("OX_InfoStore_Save_Attachment", contextData);
    });
    save.setIcon("img/menu/attachment_save.gif",
                 "img/menu/attachment_save_d.gif");
    save.setEnabledF(function() { return count() >= 1 && hasFile(); });
    menu.addItem(save);
    
    menu.onShow = function() {
        var collection = {
            columns: ["created_by", "modified_by", "locked_until", "file_size",
                      "filename"],
            objects: this.getContext().getSelected()
        };
        count.set(collection.objects.length);
        if (!count.value) return;
        readable.clear();
        writable.clear();
        editable.clear();
        deletable.clear();
        lockable.clear();
        unlockable.clear();
        hasFile.clear();
        OXCache.newRequest(null, "infostore", collection, null, responseData);
        function responseData(data) {
            contextData = data.objects;
            var l = true, ul = true, e = true;
            var me = configGetKey("identifier");
            for (var i in contextData) {
                var item = contextData[i];
                if (!item.locked_until) ul = false; else {
                    l = false;
                    if (item.modified_by != me) {
                        e = false;
                        if (item.created_by != me) ul = false;
                    }
                }
            }
            lockable.set(l);
            unlockable.set(ul);
            editable.set(e);
            readable.set(menuhasRight(contextData, "READ"));
            writable.set(menuhasRight(contextData, "WRITE"));
            deletable.set(menuhasRight(contextData, "DELETE"));
            hasFile.set(readable.value && hasAttachment(contextData));
        }
    };

    function hasAttachment(myobjects) {
        for(var i in myobjects) {
            if(!(myobjects[i]["file_size"]>0)) {
                return false;
            }
        }
        return true;
    };
}
function menuregisterInfoStoreContents() {
    register("OX_InfoStore_Move",menuinfostoremoveclicked);
    register("OX_Search_InfoStore",onmenusearchInfoStore);
}

function onmenusearchInfoStore() {
    var mysearchparam=document.getElementById("menu_search_infostore_searchfield").value;
    var mysearch=new Object();
    mysearch["pattern"]=mysearchparam;
    triggerEvent("OX_InfoStore_Search",mysearch);
}

function menuinfostoremoveclicked() {
    register("OX_InfoStore_Move",menuinfostoremoveclicked);
    createMenuPopUpTree("menu_infostore_move_foldertree","infostore",moveInfoStoreFolder);
    document.getElementById("menu_infostore_move_foldertree").style.display="";
} 

function moveInfoStoreFolder(data) {
    var selectedfolderid = data.id;
    triggerEvent("OX_Object_Move",selectedfolderid);
    document.getElementById("menu_infostore_move_foldertree").style.display="none";
}

function menucheckRight(right) {
    return menuhasRight(menuselectedobjects,right); 
}
function menuhasRightandLoad(selectedobjects,right,cbtrue,cbfalse) {
    var folders = {};
    for(var i in selectedobjects) {
        var folder = selectedobjects[i];
        var id = folder.folder || folder.folder_id;
        folders[id] = true;
    }
    var folderList = [];
    for (var i in folders) folderList.push(i);
    ox.api.folder.getMultiple({
        list: folderList,
        success: function (data) {
            if (menuhasRight(selectedobjects, right, data)) {
                if(cbtrue) cbtrue();
            } else {
                if(cbfalse) cbfalse();
            }
        }
    });
}

function menuhasRight(selectedobjects,right,resp) {
    right = { READ: 7, WRITE: 14, DELETE: 21, ADMIN: 28, USER: 29 }[right];
    if (!right) return false;
    function getFolder(folder) {
        return menuselectedfolders[folder] || resp && resp[folder];
    }
    var me = configGetKey("identifier");
    var rights = {};
    for (var i in selectedobjects) {
        var o = selectedobjects[i];
        var fid = o.folder || o.folder_id;
        if (!rights[fid]) {
            var folder = getFolder(fid);
            if (!folder) return false;
            switch (rights[fid] = computePerm(folder.own_rights, right)) {
                case 0:
                    return false;
                case 1:
                    if (right >= 28) rights[fid] = 2;
            }
        }
        if (rights[fid] == 1 && o.created_by != me) return false;
    }
    return true;    
}

function createMenuPopUpTree(elementid,moduletype,executeFunction) {
    ox.api.ui.selectFolder({
        type: moduletype,
        id: "select-folder-popup-" + moduletype,
        callback: executeFunction,
        node: $(elementid+"_content")
    });
}

function showErrorinPopup() {
	var d = $("error_popup_messages");
	removeChildNodes(d);
	
	// loop over errors
	var hasErrors = false;
	var history = ox.UINotifier.history, i = 0, $l = history.length, item, newnode, message;
	for (; i < $l; i++) {
		hasErrors = true;
		item = history[i];
		newnode = $("error_messages_template").cloneNode(true);
		newnode.id = "";
		message = item.data !== undefined ? formatError(item.data) : item.text;
		newnode.getElementsByTagName("td")[0].firstChild.data = formatDate(item.time, "datetime") + ": " + message;
		d.appendChild(newnode);
		newnode.style.display = "";
	}
	
	if (!hasErrors) {
		var newnode = $("error_messages_template").cloneNode(true);
		newnode.id = "";
		newnode.getElementsByTagName("td")[0].firstChild.data = _("No error occured");
		d.appendChild(newnode);
		newnode.style.display = "";
	}
	ErrorPopup.openWindow(600, 450);
}

function newServerError(args, level) {
	if (args.error) {
		var sizes = {
			"MSG-0028": [0, 2], "MSG-0029": [0], "NON-0005": [0, 1],
			"AJP-0006": [0], "FLS-0003": [0, 1, 2], "CON-0101": [1, 2],
			"AJP-0020": [0, 1]
		}[args.code];
		if (sizes) {
			for (var i = 0; i < sizes.length; i++) {
				args.error_params[sizes[i]] = bytesToString(args.error_params[sizes[i]]);
			}
		}
		triggerEvent("OX_New_Error", (level || 4), formatError(args), clone(args));
	}
}

function loadDefaultModules() {
    var modules = ox.api.ui.listModules();
    for (var i in modules) {
        var configPath = "gui." + modules[i].name + ".view";
        if(!modules[i].disable && configContainsKey(configPath)) {
            var defaults = configGetKey(configPath);
            if (modules[i].name == "calendar") {
                defaults = configGetKey("gui.calendar.views");
                if (!configGetKey("modules.calendar.calendar_teamview") && 
                        defaults.view == "team") {
                    defaults.view = "calendar";
                    configSetKey("gui.calendar.views.view", "calendar");
                }
                menulastviews.calendar = getDefaultCalendarView();
                lastCalendarTimeRanges.calendar = defaults.calendar;
                lastCalendarTimeRanges.team = defaults.team;
                lastCalendarTimeRanges.list = defaults.list;
            } else {
                menulastviews[modules[i].name] = configGetKey(configPath);
            }
        } else {
            if (modules[i].name== "configuration") {
                menulastviews[modules[i].name] = "configuration/settings";
            } else {
                menulastviews[modules[i].name] = modules[i].name;
            }
        }
    }
}

function switchtoView(newview, param) {
    var elements = newview.split("/");
    var newmodule= elements[0];
    
    // continuation
    var cont = function () {
        if (isDefaultableView(newview)) {
            menulastviews[newmodule] = newview;
            if (newmodule === "calendar" && elements[1] !== "detail") {
                lastCalendarTimeRanges[elements[1]] = elements[2];
            }
        }
        changeView(newview, param);
        triggerEvent("OX_Switched");
    };
    
    // change module? (check for UIController since we might be in nested windows)
    // special case: configuration/folder does not change to configuration
    var isFolderConfig = /^configuration\/folder/.test(newview);
    if (ox.UIController && !isFolderConfig && newmodule !== ox.UIController.getModule()) {
        // set module
        ox.UIController.setModule({
            module: newmodule,
            success: cont
        });
    } else {
        cont();
    }
}

function menufollowLink(mymodule,object) {
    if (mymodule == "task") { 
        mymodule = "tasks";
    } 
    
    var view = mymodule + "/detail/overview";
    activefolder = object.folder;
    if (!object.folder_id && object.folder) {
        object.folder_id = object.folder;
    }
    if (!object.module) {
        object.module = mymodule;
    }
    menucountselected = 1;
    menucountsubselected = 0;
    var oArray = new Array();
    oArray.push(object);
    switch(mymodule) {
        case "infostore":
            view = menulastviews[mymodule] || mymodule+"/split/overview";
            if (object.id) {
                view = mymodule+"/split/overview";
                object["directLink"] = true;
                oLastSelectedInfoObject = new Array();
                oLastSelectedInfoObject[0] = object;
            }       
            break;
        case "contacts":            
            if (object.id) {
                object["directLink"] = true;
                contactDetailId = object;
            } else {
                view = menulastviews[mymodule] || configGetKey("gui.contacts.view");
            }
            break;
        case "calendar":
            if (object.id) {
                object["directLink"] = true;
                selectedAppointment = object;
            } else {
                view = getLastCalendarView();
            }
            break;
        case "tasks":
            view = menulastviews[mymodule] || configGetKey("gui.tasks.view");
            if (object.id) {
                view = mymodule+"/split/overview";
                object["directLink"] = true;
                activeTaskId = new Array();
                activeTaskId[0]=object;
            }   
            break;
        case "mail":
            view = menulastviews[mymodule] || configGetKey("gui.mail.view");
            if (object.id) {
                if (view.match(/mail\/list/gi)) view = mymodule + "/hsplit/unthreaded";
                object["directLink"]=true;
                mail_lastSelectedId=object;
            }
    }
    var folderChanged = (activefolder == object.folder);
    // use new UI controller
    ox.UIController.setFolder({
        folder: object.folder,
        module: "default",
        view: view,
        force: "folder",
        success: function () {
            triggerEvent("Selected", oArray);
        }
    });
}

function folderUsersUpsell() {
    if (configGetKey("modules.folder.read_create_shared_folders")) return;
    ox.api.folder.get({
        folder: configparentfolder != -1 ? configparentfolder : configfolder,
        success: function (folder) {
            var haveadminrights = configparentfolder == -1
                ? folder.own_rights & (1 << 28) // admin flag
                : folder.own_rights & 127 >= 4; // folder permissions >= create subfolders
            var haveadminrights2 = folder.type == 5 &&
                configGetKey("modules.folder.public_folders");
            if (haveadminrights && !haveadminrights2) {
                triggerEvent("Feature_Not_Available", "modules/folders/users");
            }
        }
    });
}

function menuswitchConfigurationFolderView(param) {
    var newpath = currentpath2.slice(0);
    newpath[2] = param;
    newpath.length = 3;
    switchtoView(newpath.join("/"));
}

/**
 * Shows or hides a menu element in the specified view.
 * @param {String} name The name of the view as used for registerView.
 * @param {String} id The ID of the DOM node which will be shown in the view.
 * @param {Boolean} hide If true, a previously shown element will be hidden.
 */
function changeDisplay(name, id, hide) {
    var change = changeDisplay.changes[name];
    if (change) change = change[id];
    if (hide) {
        if (change) {
            delete changeDisplay.changes[name][id];
        } else {
            console.error("Invalid changeDisplay", name, id);
        }
    } else {
        if (change) {
        } else {
            var views = ox.widgets.toolBar.views;
            if (name in views) {
                MenuNodes.contexts[id].node.addTo(views[name].children[0]);
            } else {
                var changes = changeDisplay.changes[name];
                if (!changes) changes = changeDisplay.changes[name] = {};
                changes[id] = true;
            }
        }
    }
}
changeDisplay.changes = {};
changeDisplay.update = function(name) {
    if (name in changeDisplay.changes) {
        var tab = ox.widgets.toolBar.views[name].children[0];
        for (var id in changeDisplay.changes[name]) {
            MenuNodes.contexts[id].node.addTo(tab);
        }
        delete changeDisplay.changes[name];
    }
};

function menuswitchMailView(param) {
    var newpath = currentpath2.slice(0);
    newpath[1] = param;
    switch (param)  {
        case "list":
        case "vsplit":
        case "hsplit":
            if (newpath[2]) {
                if (newpath[2] != "unthreaded" && newpath[2] != "threaded") {
                    newpath.length = 3;
                    newpath[2] = "unthreaded";
                    break;
                }
            } else {
                newpath[2] = "unthreaded";
            }
            break;
    }
    switchtoView(newpath.join("/"));
}

function menuswitchCalendarView(param) {
    var range = lastCalendarTimeRanges[param];
    if (param != "detail" && currentpath2[1] != "detail" && 
            configGetKey("gui.calendar.views.shared")) {
        range = currentpath2[2];
    }
    switchtoView("calendar/" + param + "/" + range);
}
function menuswitchCalendarTimerange(param) {
    var newpath = currentpath2.slice(0);
    newpath[2] = param;
    if (newpath[1] == "detail") {
        newpath[1] = "calendar";
        if (menulastviews["calendar"] !== undefined) {
            newpath[1] = menulastviews["calendar"].split("/")[1];
        }
    }
    newpath.length = 3;
    switchtoView(newpath.join("/"));
}

function menuswitchCalendarDetail(param) {
    var newpath = currentpath2.slice(0);
    newpath[2] = param;
    newpath.length = 3;
    switchtoView(newpath.join("/"));
}

function menuswitchContactView(param) {
    var newpath = currentpath2.slice(0);
    newpath[1] = param;
    switch (param)  {
        case "phonelist":
        case "cards":
            newpath.length = 2;
            break;
        case "detail":
            newpath[2] = "overview";
            newpath.length = 3;
            break;
    }
    switchtoView(newpath.join("/"));
}

function menuswitchContactDetail(param) {
    var newpath = currentpath2.slice(0);
    newpath[2] = param;
    newpath.length = 3;
    switchtoView(newpath.join("/"));
}

function menuswitchContactNew(param) {
    var newpath = currentpath2.slice(0);
    newpath[1] = param;
    newpath.length = 2;
    switchtoView(newpath.join("/"));
}

function menuswitchInfoStoreView(param) {
    var newpath = currentpath2.slice(0);
    newpath[1] = param;
    switch (param)  {
        case "list":
        case "split":
            newpath.length = 2;
            break;
        case "detail":
            newpath[2] = "overview";
            newpath.length = 3;
            break;
    }
    switchtoView(newpath.join("/"));
}
function menuswitchInfoStoreDetail(param) {
    var newpath = currentpath2.slice(0);
    newpath[2] = param;
    newpath.length = 3;
    switchtoView(newpath.join("/"));
}

function menuswitchTaskView(param) {
    var newpath = currentpath2.slice(0);
    newpath[1] = param;   
    switch (param)  {
    case "list":
        case "split":
            newpath.length = 2;
            break;
        case "detail":
            newpath[2] = "overview";
            newpath.length = 3;
            break;
    }
    switchtoView(newpath.join("/"));
}
function menuswitchTaskDetail(param) {
    var newpath = currentpath2.slice(0);
    newpath[2] = param;
    newpath.length = 3;
    switchtoView(newpath.join("/"));
}

function menuswitchTaskNew(param) {
    var newpath = currentpath2.slice(0);
    newpath[1] = param;
    newpath.length = 2;
    switchtoView(newpath.join("/"));
}

register("OX_Configuration_Set_Empty", loadDefaultModules);
register("OX_Switch_View", switchtoView);
register("OX_Direct_Linking", function(modulename, object) {
    menufollowLink(modulename,object);
});

register("OX_Selected_Nested",function (nestedbool) {
    menunestedmessage = nestedbool;
});

register("OX_Selected_Draft",function (draftbool) {
    menuisdraftfolder = draftbool;
});

register("Selected",function (selected) {
    if(!equals(menuselectedobjects,selected)) {
        menucountselected = selected.length;
        menuselectedobjects = selected;
        var ids = {};
        for (var i = 0; i < menuselectedobjects.length; i++) {
            var object = menuselectedobjects[i];
            ids[object.folder || object.folder_id] = true;
        }
        var idList = [];
        for (var i in ids) idList.push(i);
        ox.api.folder.getMultiple({
            list: idList,
            success: function (folders) {
                menuselectedfolders = folders;
                triggerEvent("OX_SELECTED_ITEMS_CHANGED", menucountselected);
                triggerEvent("OX_SELECTION_CHANGED", menucountselected);
            }
        });
    }
});

register("SubSelected", function(selected,disable) {
    menucountsubselected = selected;
    if (disable) { 
        menudisableattachment = true; 
    } else { 
        menudisableattachment = false; 
    }
});

register("OX_Selected_Member", function(selected) {
    triggerEvent("SubSelected", selected.length);
});

register("OX_Lockable",function(lock, unlock, editlock) {
    menucountlockable = lock;
    menucountunlockable = unlock;
    menucounteditable = editlock;
});

function resizeToolbar() {
    try {
        if (ox.ToolBarController) {
            setTimeout(function() {
                ox.ToolBarController.initialResize();
            }, 0);
        }
   } catch (e) { }
}

register("OX_menu_Change_Height", resizeToolbar);

fileloaded();