/**
 * 
 * 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 Andreas Mayer <andreas.mayer@open-xchange.com>
 * 
 */

registerView("configuration/folder",
        function() { 
            showNode("folder_props");  
            $('folder_props').style.display = "block";
            $('folder_tree').style.display = "block";
        },
        function() {    
          register("OX_SAVE_OBJECT",cf_saveConfiguration);
          register("OX_Cancel_Object",cf_cancelConfiguration);      
          register("OX_Configuration_Delete_Folder",deleteFolderConfig);            
          
        },
        function() {
            unLoadFolderProps();
             unregister("OX_SAVE_OBJECT",cf_saveConfiguration);
            unregister("OX_Cancel_Object",cf_cancelConfiguration);
             unregister("OX_Configuration_Delete_Folder",deleteFolderConfig);            
            
        },
        function() { 
            hideNode("folder_props");  
            $('folder_props').style.display = 'none'; 
            
            // hack to disable origin folder tree if we stay at the config
            if (currentpath2.join("/").match(/^configuration/)) {
                $("config_folder_tree").style.display="block";
                $("configComplete").style.display = "block";
                $("folder_tree").style.display = "none";
            }
        },
        function() { }
    );

registerView("configuration/folder/overview",
        function() {
            $("tab_props1").style.display="block";
            $("panel_props1").className="tabPanelFirstHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";

            // toolbar
            if (!configToolbars.folderOverview) {
                configToolbars.folderOverview =
                    temporary.configuration.newToolbar(
                        _("Folder"), [
                            temporary.configuration.saveButton,
                            {
                                title: _("Folder"),
                                id: "folder",
                                buttons: [{
                                    title: _("Move"),
                                    id: "move",
                                    icons: ["img/menu/move_folder.gif",
                                            "img/menu/userrights_d.gif"],
                                    event: "OX_Configuration_Move_Folder"
                                }, {
                                    title: _("Delete"),
                                    id: "delete",
                                    icons: ["img/menu/delete_folder.gif",
                                            "img/menu/delete_folder_d.gif"],
                                    event: "OX_Configuration_Delete_Folder"
                                }]
                            }
                        ], "folder");
            }
            temporary.configuration.showToolbar(configToolbars.folderOverview);
        },
        function() { },
        null,
        function() {
            $("tab_props1").style.isplay="none";
            $("panel_props1").className="tabPanelFirst tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";
        },
        function() { }
    );

function cf_saveConfiguration() {
    triggerEvent("OX_Save_Configuration",false,false,null,null);
}

var oPermissionsLiveGrid = null;
var permStorage;

registerView(
    "configuration/folder/rights",
    function () {
        
        $("tab_props2").style.display="block";
        $("panel_props2").className="tabPanelHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";
        
        listUserMappingArray = [];

        temporary.configuration.showToolbar(configToolbars.folderPermissions);
        
        //Create Live Grid Here
        if (oPermissionsLiveGrid == null) {            
            oPermissionsLiveGrid = new LiveGrid([ {
                index: 1,            
                text: "",
                i18n: true,
                width: "16px",
                style: {padding: 0},
                //using in infostore defined functions here
                set: function  (div, text) {
                    var sImgStr = (text.groupflag)?getFullImgSrc("img/calendar/group.gif"):getFullImgSrc("img/calendar/user.gif");
                    var sAlt = (text.groupflag)?"Group":"User";
                    if(div.firstChild.src)
                        div.firstChild.src = sImgStr;
                    else{
                        removeChildNodes(div);
                        div.appendChild(newnode("img", 0, {src:sImgStr, alt: sAlt}));
                    }
                },                
                clear: LiveGrid.makeClear("...")
            }, {
                index: 1,            
                text: "User", /*i18n*/
                i18n: true,
                //using in infostore defined functions here
                set: function  (div, text) {
                    function cb_fetchUserFromCache(nId){
                        return function (arg)                        
                        {
                            if (div.firstChild)
                                div.firstChild.data = arg[nId].display_name;
                            else
                                div.appendChild(document.createTextNode(arg[nId].display_name));
                        };
                    }
                    if(text.groupflag)
                    {
                        internalCache.getGroups([parseInt(text.id)],cb_fetchUserFromCache(parseInt(text.id)));        
                    }
                    else
                    {
                        internalCache.getUsers([parseInt(text.id)],cb_fetchUserFromCache(parseInt(text.id)));        
                    }
                },                
                clear: LiveGrid.makeClear("...")
            }, {
                index: 2,                
                text: "Folder admin", /*i18n*/
                i18n: true,                
                width: "7em",
                set: function  (div, text){
                    removeChildNodes(div);
                    var sDisplayString =  (text == 1)?_("Yes"):_("No");            
                    div.appendChild(document.createTextNode(sDisplayString));        
                },            
                clear: LiveGrid.makeClear("...")
            }, {
                index: 3,    
                text: "Admin", /*i18n*/
                i18n: true,                
                width: "12em",
                set: function  (div, text){
                    removeChildNodes(div);
                    var sDisplayString = expectI18n(text);
                    div.appendChild(document.createTextNode(sDisplayString));    
                },
                clear: LiveGrid.makeClear("...")
            }, {
                index: 4,    
                text: "Read objects", /*i18n*/
                i18n: true,                
                width: "9em",
                set: function  (div, text){
                removeChildNodes(div);
                var sDisplayString = expectI18n(text);
                div.appendChild(document.createTextNode(sDisplayString));    
                },
                clear: LiveGrid.makeClear("...")
            }, {
                index: 5,                    
                text: "Modify objects", /*i18n*/
                i18n: true,                
                width: "9em",
                set: function  (div, text){
                removeChildNodes(div);
                var sDisplayString = expectI18n(text);
                div.appendChild(document.createTextNode(sDisplayString));    
                },
                clear: LiveGrid.makeClear("...")
            }, {
                index: 6,                    
                text: "Delete objects", /*i18n*/
                i18n: true,                
                width: "9em",
                set: function  (div, text){
                removeChildNodes(div);
                var sDisplayString = expectI18n(text);
                div.appendChild(document.createTextNode(sDisplayString));    
                },
                clear: LiveGrid.makeClear("...")                
            }], new Selection());
            
            oPermissionsLiveGrid.emptylivegridtext = "";
            oPermissionsLiveGrid.events.register("Selected", fireSelected);
            $("userRightsHeadContainer").appendChild(oPermissionsLiveGrid.getHeader());
            oPermissionsLiveGrid.getTable($("userRightsTableContainer"));        
            permGridEnable(true);
            fireSelected(0);
        } else {
            permGridEnable(false);                
        }
        var haveadminrights, privatefolder, lastEntity;
        function fireSelected(count) {
            editEntity = count != 1 ? '' :
                oPermissionsLiveGrid.selection.getSelected()[0];
            if (haveadminrights === undefined) {
                ox.api.folder.get({
                    folder: configfolder,
                    success: function (oFolder) {
                        haveadminrights = configparentfolder == -1 &&
                            (oFolder.own_rights & (1 << 28)); // admin flag
                        privatefolder = configfolder == 1 ||
                            oFolder.type == 1; 
                        handleSelection(count);
                    }
                });
            } else {
                handleSelection(count);
            }
        }
        function handleSelection (count) {
            var enabled = Boolean(count == 1 && haveadminrights);
            var bits = enabled ? aGlobalPermissions[editEntity].bitmask : 0;
            // update "remove button"
            ox.widgets.toolBar.menuItems["permissions-save-remove"].setEnabled(count > 0);
            // get sections
            var folders = ox.widgets.toolBar.tabs.permissionsForFolders.getChildren();
            var objects = ox.widgets.toolBar.tabs.permissionsForObjects.getChildren();
            // update section "admin"
            updateSection(folders[0], enabled && !privatefolder, (bits >> 28) & 1, [1, 0]); // folder admin
            // update section "folder permissions"
            updateSection(folders[1], enabled, bits, [0, 1, 2, 4, 64]); // admin
            // update section "read permissions"
            updateSection(objects[0], enabled, bits >> 7, [0, 1, 2, 64]); // read
            // update section "modify permissions"
            updateSection(objects[1], enabled, bits >> 14, [0, 1, 2, 64]); // write
            // update section "delete permissions"
            updateSection(objects[2], enabled, bits >> 21, [0, 1, 2, 64]); // delete
            // validate
            configToolbars.folderPermissions.validate();
            // show default tab
            if (editEntity !== lastEntity) {
                configToolbars.folderPermissions.setPosition(2);
                lastEntity = editEntity;
            }
        }
        function updateSection (section, enabled, value, values) {
            value &= 127;
            var items = section.getChildren();
            for (var i = 0; i < items.length; i++) {
                items[i].setEnabled(enabled);
                items[i].setChecked(enabled && value == values[i]);
            }
        }
    },
    function() {
        //TODO set Private flag and admin flag      
    },
    function() {
        //TODO set Private flag and admin flag  
        triggerEvent('Selected',0);
    },
    function() {
        oPermissionsLiveGrid.disable();
        $("tab_props2").style.display="none";
        $("panel_props2").className="tabPanel tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";
    },
    function() { }
);

function permGridEnable(bInitialEnabl) {
    if(permStorage != null) {
        oPermissionsLiveGrid.enable(permStorage);
        return;
    }
    var aData = new Array();
    for (var indx in  aViewObjects) {
        var aSubData = new Array();
        var oEachObj = aViewObjects[indx];
        aSubData.push(oEachObj.entity + '_' + ((oEachObj.groupflag)?1:0));
        aSubData.push({id:oEachObj.entity,groupflag:oEachObj.groupflag});        
        aSubData.push(oEachObj.admin);
        aSubData.push(oEachObj.fr);
        aSubData.push(oEachObj.rr);
        aSubData.push(oEachObj.wr);        
        aSubData.push(oEachObj.dr);                
        aData.push(aSubData);
    }
    updateGrid(aData);
}

function updateGrid(aData) {
    permStorage = new Storage(0, [],null,null,null,null, 
       function (x) {
            return x[0];
       });    
    permStorage.append(aData);    
    oPermissionsLiveGrid.enable(permStorage);    
}

function avoidSubmitOnEnter(event) {
    registerFolderChange('title');
    if(event && event.keyCode == 13)
    {
        return false;
    }
}

function cf_cancelConfiguration() {
    configuration_changed_fields["folder"] = false;
}

register("OX_Configuration_Switch_Folder_View", function(param) { menuswitchConfigurationFolderView(param); });

var fdpropsTabsList = new Array('tab_props1','tab_props2');
var fdpropsPanelsList = new Array('panel_props1','panel_props2', 'panel_props3');
var fdpropsEventList = new Array( ['OX_Configuration_Switch_Folder_View','overview'],
                                      ['OX_Configuration_Switch_Folder_View','rights']
                                );
var bNew ;
var bParticipantsLoaded = false;
var bTableCreated = false;
var bValuesInit = false;
var bValuesLoaded = false;
var editEntity = '';

/////////////////////////////////////////////
// search and add users    
var participantObjects;
var selectedParticipants = new Array();
var oPartDialog = null;

function openAddUserDiv(oFolder) {    
    var bDisableGroup = true;
    if(oFolder.module == "mail")
        bDisableGroup = -1;
    if (!oPartDialog) {
        oPartDialog = new ParticipantsSmall(null,addToSelectedUser,true,true,false,false,"Select Users", /*i18n*/
                    null,true,false,true);
    }
    oPartDialog.openAddParticipantsWindow();
}    

function participantObj(objFromServer) {
    this.id = objFromServer.id;
    this.display_name = objFromServer.display_name;
    this.type = objFromServer.type;
    this.email = objFromServer.email;
}

var aChangedAttributes = new Object();
function registerFolderChange(sAttribute) {
    aChangedAttributes[sAttribute] = true;
    configuration_changed_fields["folder"]=true;    
}

function addToSelectedUser(arg) {
    commitAddUser(arg);
    registerFolderChange("user");
}

function commitAddUser(selectedParticipants) {
    var aPermissionArrayForeign = new Array();
    var aPermissionArraySelf = new Array();    
        
    for (var nIndex = 0;nIndex<selectedParticipants.length;nIndex++) {
        if(selectedParticipants[nIndex].type == 2) {
            var bGroupFlag = true;        
        } else {
            var bGroupFlag = false;
        }
        if (selectedParticipants[nIndex].id == configGetKey("identifier")) {
                    aPermissionArraySelf[0] = {group:false,bits:Math.pow(2,6)+Math.pow(2,13)+
                                            Math.pow(2,20) + Math.pow(2,27) + Math.pow(2,28),                    
                                           entity:configGetKey("identifier")};
        } else {
            aPermissionArrayForeign.push({group:bGroupFlag,bits:Math.pow(2,0)+Math.pow(2,8)+
                            Math.pow(2,15) + Math.pow(2,22),
                                            entity:selectedParticipants[nIndex].id});            
        }
    }
    var aPermissionArray = aPermissionArraySelf.concat(aPermissionArrayForeign);
    selectedParticipants = new Array();
    var aViewObjects = permissionsToViewObjects(aPermissionArray);
    var aData = new Array();
    for (var indx in  aViewObjects) {
        var aSubData = new Array();
        var oEachObj = aViewObjects[indx];
        aSubData.push(oEachObj.entity + '_' + ((oEachObj.groupflag)?1:0));
        aSubData.push({id:oEachObj.entity,groupflag:oEachObj.groupflag});        
        aSubData.push(oEachObj.admin);
        aSubData.push(oEachObj.fr);
        aSubData.push(oEachObj.rr);
        aSubData.push(oEachObj.wr);        
        aSubData.push(oEachObj.dr);                
        aData.push(aSubData);
    }
    //avoid duplicated entries here
    var aFinalArr = new Array();
    for (var indxUser=0;indxUser<aData.length;indxUser++) {        
        if(permStorage.data.data[aData[indxUser][0]] == undefined) {
            aFinalArr.push(aData[indxUser]);
        }
    }
    permStorage.append(aFinalArr);
    oPermissionsLiveGrid.enable(permStorage);    

}

function removeFolderUser() {        
    registerFolderChange("user");
    var aIdToDel = oPermissionsLiveGrid.selection.getSelected();    
    oPermissionsLiveGrid.deleteIDs(aIdToDel);                
    //fixed bug #10380
    oPermissionsLiveGrid.selection.reset();        
    oPermissionsLiveGrid.focus=undefined;
    oPermissionsLiveGrid.updateStyles();
    for (var indx=0;indx<aIdToDel.length;indx++) {
        delete aGlobalPermissions[aIdToDel[indx]];
    }
}

function unLoadFolderProps() {
    editEntity = '';
    unregister("OX_Configuration_Remove_User",removeFolderUser);            
    unregister("OX_Configuration_Add_User",openAddUserDiv);                    
    $('inFolderName').value = '';
    configuration_changed_fields["folder"] = false;
    bParticipantsLoaded = false;
    aChangedAttributes = new Object();
    bTableCreated = false;
    bValuesInit = false;
    bValuesLoaded = false;
    bconfigFolderUserChanges = false;
    aGlobalPermissions = new Object();
    $('checkBoxSubscr').checked = false;
    $('checkBoxSubscr').disabled = false;        
    $('checkBoxSubscrDiv').style.display = "none";
}
    
function getFolderNameTranslated(folderObject) {
    var ids = configGetKey("folder");
    var replacedname = folderObject.title;
    switch (String(folderObject.id)) {
        case String(ids.tasks):
            replacedname = _("Tasks"); /*i18n*/
            break;
        case String(ids.calendar):
            replacedname = _("Calendar"); /*i18n*/
            break;
        case String(ids.contacts):
            replacedname = _("Contacts"); /*i18n*/
            break;
    }
    return replacedname;
}

var aViewObjects;
function loadFolderProps(bPermPropagation,bDisableScrollTo) {
    register("OX_Configuration_Remove_User",removeFolderUser);
    register("OX_Configuration_Add_User",openAddUserDiv);                
    permStorage = null;
    bNew = (configparentfolder != -1);
    if(!bParticipantsLoaded) {
        if(!bNew) {
            // get folder
            ox.api.folder.get({
                folder: configfolder,
                success: function (OXFolder) {
                    if (oPermissionsLiveGrid && oPermissionsLiveGrid.selection) {
                        oPermissionsLiveGrid.selection.reset(); // bugfix #9991
                        triggerEvent("SubSelected",[]);
                    }
                    var replacedname = getFolderNameTranslated(OXFolder);
                    setPropsHeadLine(replacedname, false);
                    var aPermissionArray = OXFolder.permissions;
                    var sModule = OXFolder.module;
                    var sIdParam = OXFolder.id;                                        
                    var oOwnRights = OXFolder.own_rights;
                    if (!bValuesInit) {        
                        $('inFolderName').value = replacedname;
                    }
                    configuration_changed_fields["folder"] = false;
                    bValuesInit = true;    
                    loadTabs(sModule,oOwnRights,sIdParam);
                    aViewObjects = permissionsToViewObjects(aPermissionArray);    
                    //check acls enabled here
                    if((sModule == "mail" || String(sIdParam).match(/^default(\d+)?/))     //check capabilities here
                                             && !(OXFolder.capabilities & Math.pow(2,0))) 
                     {
                        $("panel_props2").style.display = "none";
                     }
                     else
                     {
                         $("panel_props2").style.display = "block";
                     }
                    if(sModule == "mail"     //check capabilities here
                                             && (OXFolder.capabilities & Math.pow(2,8))) 
                    {
                        $('checkBoxSubscrDiv').style.display = "";            
                        $('checkBoxSubscr').checked = (OXFolder.subscribed);
                        if(OXFolder.id == "default.INBOX")
                        {
                            $('checkBoxSubscr').disabled = true;                            
                        }
                    }
                }
            });
        } else {
            if (oPermissionsLiveGrid && oPermissionsLiveGrid.selection) {
                    oPermissionsLiveGrid.selection.reset(); // bugfix #9991
                    triggerEvent("SubSelected",[]);
            }
            // get folder
            ox.api.folder.get({
                folder: configparentfolder,
                success: function (OXFolder) {
    
                    setPropsHeadLine(getFolderNameTranslated(OXFolder),true);                    
    
                    var sModule = OXFolder.module;
                    
                    if((sModule == "mail" || String(OXFolder.id).match(/^default(\d+)?/))     //check capabilities here
                                             && !(OXFolder.capabilities & Math.pow(2,0))) 
                     {
                        $("panel_props2").style.display = "none";
                     }                                        
                     else
                     {
                         $("panel_props2").style.display = "block";
                     }
                         
                    if(!bValuesInit)
                    {
                        $('inFolderName').value = '';
                        configuration_changed_fields["folder"] = false;
                    }
                    bValuesInit = true;        
                    
                    var aPermissionArray = getNewFolderPerms(OXFolder,bPermPropagation);    
                    
                    var aViewObjects = permissionsToViewObjects(aPermissionArray);                    
                    var oOwnRights = aPermissionArray[0];                        
                    loadTabs(sModule,oOwnRights);
                    if(sModule == "mail")
                    {
                        $('checkBoxSubscrDiv').style.display = "";
                        $('checkBoxSubscr').checked = true;
                        $('checkBoxSubscr').disabled = true;
                    }
                }
            });
        }
    }
    triggerEvent("OX_Config_Folder_Changed");
}

function getNewFolderPerms(OXFolder, bPermPropagation) {
    var aPermissionArray = new Array();                    
    //shared folder permissions
    if (OXFolder.type == 3 && OXFolder.created_by != null 
           && OXFolder.created_by != configGetKey("identifier")) {
        aPermissionArray[0] = {group:false,bits:Math.pow(2,6)+Math.pow(2,13)+
                                Math.pow(2,20) + Math.pow(2,27) + Math.pow(2,28),                                                                    
                               entity:OXFolder.created_by};                        
        aPermissionArray[1] = {group:false,bits:Math.pow(2,0)+Math.pow(2,8)+
            Math.pow(2,15) + Math.pow(2,22),
                            entity:configGetKey("identifier")};
    } else {
        aPermissionArray[0] = {group:false,bits:Math.pow(2,6)+Math.pow(2,13)+
                                Math.pow(2,20) + Math.pow(2,27) + Math.pow(2,28),                    
                               entity:configGetKey("identifier")};
    }
    if (bPermPropagation) {
        var aPermissionArray = new Array();
        switch(OXFolder.id) {
            case 1: case 2: case 10:                            
                aPermissionArray = aPermissionArray.concat(OXFolder.permissions);                            
                aPermissionArray.push({group:false,bits:Math.pow(2,6)+Math.pow(2,13)+
                                    Math.pow(2,20) + Math.pow(2,27) + Math.pow(2,28),                    
                                   entity:configGetKey("identifier")});                                               
                break;
            default:
                aPermissionArray = OXFolder.permissions;
                break;
        }        
    }    
    return aPermissionArray;
}

function setPropsHeadLine(stitle, bNewFolderDia){
    removeChildNodes($("folder_prop_headline"));
    if(bNewFolderDia) {
        var oTextNodeDOM = new I18nNode(_("Folder Properties"));
        $("folder_prop_headline").appendChild(oTextNodeDOM.node);
    } else {
        //#. %s is the folder name.
        //#, c-format
        var oTextNodeDOM = new I18nNode(format(_("Folder Properties: %s"),
                                               stitle));
        $("folder_prop_headline").appendChild(oTextNodeDOM.node);
    }
}

function fn_ln2(val) {
    return Math.log(val)/Math.log(2);
}

function changeRights(sType,sRight) {
    registerFolderChange("user");
    var bits = 0;

    if(!aGlobalPermissions[editEntity])
        return;

    switch(sType) {
        case 'FOLDER':
                bits =     Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][1].bit)) + 7) + 
                            Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][2].bit)) + 14)  + 
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][3].bit)) + 21);
                        bits += (aGlobalPermissions[editEntity]['obj'][4]==0)?0:Math.pow(2,28);
                        bits += (sRight==0)?0:Math.pow(2,fn_ln2(parseInt(sRight)) + 0);
                        aGlobalPermissions[editEntity]['obj'][0].bit = parseInt(sRight);
                        aGlobalPermissions[editEntity]['obj'][0].string = ox.api.folder.derive("permissions", bits, 0).string;
                        break;
        case 'READ':
                bits =     Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][0].bit)) + 0) + 
                            Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][2].bit)) + 14)  + 
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][3].bit)) + 21);
                        bits += (aGlobalPermissions[editEntity]['obj'][4]==0)?0:Math.pow(2,28);
                        bits += (sRight==0)?0:Math.pow(2,fn_ln2(parseInt(sRight)) + 7);
                        aGlobalPermissions[editEntity]['obj'][1].bit = parseInt(sRight);
                        aGlobalPermissions[editEntity]['obj'][1].string = ox.api.folder.derive("permissions", bits, 7).string;    
                        break;
        case 'WRITE':
                bits =     Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][0].bit)) + 0) + 
                            Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][1].bit)) + 7)  + 
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][3].bit)) + 21);
                        bits += (aGlobalPermissions[editEntity]['obj'][4]==0)?0:Math.pow(2,28);                                                        
                        bits += (sRight==0)?0:Math.pow(2,fn_ln2(parseInt(sRight)) + 14);
                        aGlobalPermissions[editEntity]['obj'][2].bit = parseInt(sRight);
                        aGlobalPermissions[editEntity]['obj'][2].string = ox.api.folder.derive("permissions", bits, 14).string;
                        break;
        case 'DELETE':
                bits =     Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][0].bit)) + 0) + 
                            Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][1].bit)) + 7)  + 
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][2].bit)) + 14);
                        bits += (aGlobalPermissions[editEntity]['obj'][4]==0)?0:Math.pow(2,28);                    
                        bits += (sRight==0)?0:Math.pow(2,fn_ln2(parseInt(sRight)) + 21);
                        aGlobalPermissions[editEntity]['obj'][3].bit = parseInt(sRight);
                        aGlobalPermissions[editEntity]['obj'][3].string = ox.api.folder.derive("permissions", bits, 21).string;
                        break;
        case 'ADMIN':    bits =     Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][0].bit)) + 0) + 
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][1].bit)) + 7)  + 
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][2].bit)) + 14) +
                                Math.pow(2,fn_ln2(parseInt(aGlobalPermissions[editEntity]['obj'][3].bit)) + 21) ;
                        bits += (sRight==0)?0:Math.pow(2,28);                    
                        aGlobalPermissions[editEntity]['obj'][4] = parseInt(sRight);                                    
                        break;
        default:        bits;                
    }
    aGlobalPermissions[editEntity]['bitmask'] = bits;
    var oPermissions = aGlobalPermissions[editEntity]['obj'];    
    var aaA = new Array();    
    aaA.push([editEntity,{id:editEntity.entity,groupflag:editEntity.groupflag},
                                oPermissions[4],
                                    oPermissions[0].string,oPermissions[1].string,
                                                            oPermissions[2].string,oPermissions[3].string]);
    function cb_loc_updt (){
        return function (indx,data)
        {
            data[2] = oPermissions[4];
            data[3] = oPermissions[0].string;
            data[4] = oPermissions[1].string;
            data[5] = oPermissions[2].string;                        
            data[6] = oPermissions[3].string;    
            return data;                                
        };
    }
    oPermissionsLiveGrid.storage.localUpdate([editEntity],cb_loc_updt());
    oPermissionsLiveGrid.events.trigger("Selected",
        oPermissionsLiveGrid.selection.count);
    return bits;
}

var aGlobalPermissions = new Object();
function permissionsToViewObjects(aPermissionArray) {    
    var aViewObjects = new Array();
    if (!aPermissionArray) {
        return aViewObjects;
    }
    for (nEntity=0;nEntity < aPermissionArray.length;nEntity++) {
        var aEntityPermissions = aPermissionArray[nEntity];        
        var nBits = aEntityPermissions.bits;

        aViewObjects[nEntity] = new Object();
        aViewObjects[nEntity]['entity'] = aEntityPermissions.entity;                
        aViewObjects[nEntity]['groupflag'] = aEntityPermissions.group;                        
        
        oPerm = new Array();
        
        oPerm[0] = ox.api.folder.derive("permissions", nBits, 0);
        oPerm[1] = ox.api.folder.derive("permissions", nBits, 7);
        oPerm[2] = ox.api.folder.derive("permissions", nBits, 14);
        oPerm[3] = ox.api.folder.derive("permissions", nBits, 21);
        oPerm[4] = (nBits & Math.pow(2,28))?1:0;    
        
        aViewObjects[nEntity]['fr'] = oPerm[0].string;
        aViewObjects[nEntity]['rr'] = oPerm[1].string;
        aViewObjects[nEntity]['wr'] = oPerm[2].string;                                
        aViewObjects[nEntity]['dr'] = oPerm[3].string;                                                
        aViewObjects[nEntity]['admin'] = oPerm[4];
        
        var sKey = aEntityPermissions.entity + '_' + ((aEntityPermissions.group)?1:0);
        aGlobalPermissions[sKey] = new Object();
        aGlobalPermissions[sKey]['obj'] = oPerm;
        aGlobalPermissions[sKey]['bitmask'] = nBits;
        aGlobalPermissions[sKey]['groupflag'] = aEntityPermissions.group;
    }
    return aViewObjects;
}

function getDisplayName(bGroupFlag,nEntity,DOMDiv) {
    var arr = new Array();
    arr[0] = nEntity;
    var newValue = nEntity;
    function fnSetUserColumn(arg) {
        if(DOMDiv && arg[newValue]) {
            var oTextNode = document.createTextNode(arg[newValue].display_name);
            DOMDiv.appendChild(oTextNode);
        } else {
            var oTextNode = document.createTextNode('');
            DOMDiv.appendChild(oTextNode);
        }
    }
    if (bGroupFlag) {
        internalCache.getGroups(arr,fnSetUserColumn);
    } else {        
        internalCache.getUsers(arr,fnSetUserColumn);
    }        
}

function saveFolder(fn_opt) {
    var oFolderNEW = getFolderFromForm();

    ox.api.folder.get({ folder: configfolder, success: function (oFolder) {
	        function success(arg) {
	            //the folder id must be reseted after mail folder update
	            activefolder = (oFolder.module=="mail")?arg.data:configfolder;    
	            configfolder = activefolder;                        
	            triggerEvent("OX_New_Info",4,_("Your settings have been saved"));
	            
	            // workaround for foldertree updates after permission changes to display
	            // shared icons on folders
                ox.api.cache.folder0.clear();
                ox.api.cache.folder1.clear();
                ox.api.cache.folderFlat.clear();
                              
	            if(fn_opt)
	                fn_opt();
	        }
	        function error() {
	            disableNodeActions = false;
	            if(fn_opt)
	                fn_opt();
	        }            
	        //check Folder default
	        var oFolderdefault = configGetKey("folder");
	        var isDefaultfolder = false;
	        for(var itemF in oFolderdefault) {
	            if(changedFolderId == oFolderdefault[itemF])
	                isDefaultfolder    = true;
	        }
	        if (isDefaultfolder || !aChangedAttributes["title"]) {
	            delete oFolderNEW["title"];
	        }
	        if (!aChangedAttributes["user"]) {
	            delete oFolderNEW["permissions"];                
	        }
	        if (oFolder != undefined) {
	            ox.api.folder.update({
	                folder: configfolder,
	                data: oFolderNEW,
	                success: success,
	                error: error
	            });
	        }
	    } 
    });     
}

function getFolderFromForm() {
    var sName = document.forms.folderMainProps.inFolderName.value;
    var bSubscribed = document.forms.folderMainProps.checkBoxSubscr.checked;    
    var sType = "";
    if(!comboboxProps) return;
    changedFolderId = configfolder;        
    var sIDOpt  = comboboxProps.getKey();
    sType = sIDOpt.split("_")[1];
    
    var nPerNum = 0;
    var aPermissionArray = new Array();    
    for (sEnt in aGlobalPermissions) {
        var oPermission = new Object();
        oPermission['bits'] = parseInt(aGlobalPermissions[sEnt].bitmask);
        oPermission['entity'] = sEnt.split("_")[0]; //UserId
        oPermission['rights'] = '';
        oPermission['group'] = (sEnt.split("_")[1] == "0")?false:true;
        aPermissionArray[nPerNum] = oPermission;
        nPerNum++;
    }
    var oFolder  = new Object();
    oFolder['title'] = sName;
    oFolder['module'] = sType;    
    oFolder['permissions'] = aPermissionArray;    
    oFolder['subscribed'] = (bSubscribed)?1:0;        
    return oFolder;
}    

function loadTabs(sModule,oOwnRights,sIdParam){
    setTabLists(fdpropsTabsList, fdpropsPanelsList,fdpropsEventList);    
    if(!bValuesLoaded)
        loadValues(sModule,oOwnRights);    
    bValuesLoaded = true;
}

var comboboxProps = null;
function loadValues(sModule,oOwnRights) {
    // get folder
    var id = (bNew) ? configparentfolder : configfolder;
    ox.api.folder.get({
        folder: id, 
        success: function (folder) {
            var sMod = folder.module;
            var sId = folder.id;    
            var selectedItem = 'm_'+sMod;
            var inputNameField = $('inFolderName');
            var bPermFolderBit = ox.api.folder.derive("permissions", folder, 0).bit;
            if(!ox.api.folder.can("rename", folder) && !bNew) {
                inputNameField.disabled = true;
                inputNameField.className = "background-color-default border-color-design";
            } else {                    
                inputNameField.disabled = false;
                inputNameField.className = "";
            }
            if(bNew && sId != 'default' && sMod != 'infostore' && sMod != 'mail') {        
                if(selectedItem == 'm_system')
                    selectedItem = 'm_calendar';
                comboboxProps = new ComboBox3(window, "SelTypeFolder", "190px", 0, true, "OX_Folder_ModuleComboChanged", null);
                if(configGetKey("modules.calendar.module"))
                    comboboxProps.addElement(_("Calendar"),"m_calendar");    
                if(configGetKey("modules.contacts.module"))    
                    comboboxProps.addElement(_("Contacts"),"m_contacts");                
                if(configGetKey("modules.tasks.module"))
                    comboboxProps.addElement(_("Tasks"),"m_tasks");
                comboboxProps.getDomNode();    
            } else { 
                comboboxProps = new ComboBox3(window, "SelTypeFolder", "190px", 0, true, "OX_Folder_ModuleComboChanged", null);
                comboboxProps.addElement(_("Calendar"),"m_calendar");        
                comboboxProps.addElement(_("Contacts"),"m_contacts");        
                comboboxProps.addElement(_("Tasks"),"m_tasks");                
                comboboxProps.addElement(_("E-Mail"),"m_mail");                        
                comboboxProps.addElement(_("InfoStore"),"m_infostore");                                
                comboboxProps.getDomNode();
                comboboxProps.disable();
                if(sId == 'default')
                    selectedItem = 'm_mail';
            }
            comboboxProps.setKey(selectedItem);
        }
   });
}

fileloaded();    