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

function computePerm(nBits, nOffset) {
    return (nBits >> nOffset) & (nOffset >= 28 ? 1 : 127);
}

function FolderPath (module) {
    this.module = module;
    this.folderId = null;
    this.nodeId = null;
    this.className = "linkstyle-headline";
    this.classNameD = "font-style-low";
    this.events = new Array();
    this.cb = function(module, folderId) {
            return function() {
                ox.api.ui.setModule(module, null, folderId);
            };
        };
    this._cancelDraw=false;
    this.additionalNode;
}

FolderPath.prototype = {
    setFolderId: function(folderId) {
        this.folderId = folderId;
    },  
    drawDOMNode: function(nodeId, folderId) {
        if (nodeId) this.nodeId = nodeId;
        if (folderId) this.folderId = folderId;
        if (!$(this.nodeId) || !folderId || this._cancelDraw) return;
        this._cancelDraw = true;
        var Self = this;
        this.clear();

        // get "myself" from user interface first (it is part of most paths and usually cached)
        var userId = config.identifier;
        var folderId = this.folderId;
        internalCache.getUsers([userId], function (user) {
            
            // get display name
            var myName = user[userId].display_name + "";
            
            // get path
            ox.api.folder.getParents({
                folder: folderId,
                success: function (list) {
                    var $l = list.length, i = $l - 1, folder;
                    for (; i >= 0; i--) {
                        
                        folder = ox.util.clone(list[i]);
                        
                        if (folder.id == 1) {
                            // overwrite title
                            folder.title = myName;
                        }
                        
                        var ids = configGetKey("folder");
                        var replacedname = "";
                        switch (String(folder.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;
                        }
                        var read = computePerm(folder.own_rights,7) > 0;
                        var myNode = newnode("span", 0, { className: read  ? Self.className : Self.classNameD },
                            [ document.createTextNode(replacedname ? _(replacedname) : folder.title) ]);
                        if (read) {
                            var fcb = (Self.cb)(folder.module, folder.id);
                            addDOMEvent(myNode, "click", fcb);
                            Self.events.push(["click", fcb]);
                        } 
                        $(Self.nodeId).appendChild(myNode);
                        if (i>0) {
                            $(Self.nodeId).appendChild(document.createTextNode(" / "));
                        } else if (Self.additionalNode != undefined) {
                            $(Self.nodeId).appendChild(Self.additionalNode);
                        }
                    }
                    Self._cancelDraw=false;
                }
            });
        });
    },
    
    drawSearch: function(module, searchTerm) {
        if (!this.nodeId || this.module != module) return;
        this.clear();
        //#. Title for search results (displayed instead of a folder name).
        //#. %s is the search term.
        //#, c-format
        var myNode = newnode("span", 0, 0, [ document.createTextNode(format(_("Results for \"%s\""), searchTerm)) ]);
        $(this.nodeId).appendChild(myNode);
    },
    clear: function() {
        if (!$(this.nodeId)) return;
        for (var i=0; i< this.events.length; i++) {
            removeDOMEvent($(this.nodeId), this.events[i][0], this.events[i][1]);
        }
        this.events = new Array();
        removeChildNodes($(this.nodeId));
    }
};

/**
 * Constructor of the subscribe E-Mail folder dialog
 */

SubscribeFolder = (function () {
    
    var Class = function () {
        
        var self = this;
        this.changedFolders = []; // temp storage for changed items
        
        // ox.api.cache.mailSubscription.clear();
        
        this.listFolder = function (list, node) {
            var i = 0, $l = list.length, folder;
            for (; i < $l; i++) {
                folder = list[i];
                if (ox.api.folder.is("mail", folder)) {
                    self.addFolderToList(folder, node);
                }
            }
            $("subscribe_folder_status").style.display="none";
        };
        
        this.addFolderToList = function (folder, contentNode) {
            var all_cb = jQuery("#subscribe_folder_content INPUT[type='checkbox']");
            var sNode = newnode("td",{ width: "18px" },0,
               [
                   newnode("img",{ verticalAlign: "middle" }, { 
                       className: folder.subfolders ? "tree-children" : "tree-nochildren", 
                       src: folder.subfolders ? getFullImgSrc("img/plus.gif") : getFullImgSrc("img/noplus.gif")
                   })
               ]
            );
            sNode.onclick = function() {
                if (!folder.subfolders) return;
                if (sNode.firstChild.src.match(/plus.gif/)) {
                    centerPopupWindow($("subscribe_folder_status"));
                    $("subscribe_folder_status").style.display="block";
                    $("subscribe_folder_status").style.top="100px"; 
           
                    var tNode = newnode("div",
                        {marginLeft: "18px", whiteSpace: "nowrap"}, 0);
                    sNode.parentNode.parentNode.parentNode.parentNode.appendChild(
                        tNode);
                    // get subfolder
                    ox.api.folder.getSubFolders({
                        folder: folder.id,
                        all: true,
                        tree: "0",
                        storage: ox.api.cache.subscribe,
                        success: function (data) {
                            sNode.firstChild.src = getFullImgSrc("img/minus.gif");
                            sNode.firstChild.className = "tree-nochildren";
                            self.listFolder(data, tNode);
                        }
                    });
                } else {
                    sNode.parentNode.parentNode.parentNode.parentNode.removeChild(sNode.parentNode.parentNode.parentNode.nextSibling);
                    sNode.firstChild.src=getFullImgSrc("img/plus.gif");
                    sNode.firstChild.className = "tree-children";
                }
            };
            
            if (folder.own_rights & 0x3f80) {
                var iNode = newnode("input",0,{ type: "checkbox",
                           id: "sub_folder_" + folder.id, 
                           oxid: folder.id,            
                           className: "noborder",
                           disabled: !(folder.own_rights & 0x3f80)
                       });
                /*
                 * setting checked attribute only if folder is subscribed
                 */ 
                if (folder.subscribed == true) {
                    iNode.setAttribute("checked", "checked");
                }  
                iNode.onchange = function() {
                    self.addChangedItem({ id: iNode.oxid, data: { subscribed: iNode.checked } });
                    checkAllCheckboxes("sub_folder_"+iNode.oxid, iNode.checked)
                };
                
                checkAllCheckboxes = function(id, bool_flag) {
                    var all_cb = jQuery("#subscribe_folder_content INPUT[type='checkbox']");
                    jQuery.each(all_cb, function(i,val){
                        if(val.id.indexOf(id+"/")!=-1 && val.id != id) {
                            if(!all_cb[i].disabled) {
                                jQuery(all_cb[i]).attr("checked", bool_flag);
                                self.addChangedItem({ id: val.id, data: { subscribed: bool_flag } });
                            }
                        }
                    });
                }
            }
            contentNode.appendChild(
               newnode("div", 0, { className: "tree-div" }, [
                   newnode("table",{borderCollapse:"collapse",borderWidth:"0",borderSpacing:"0",width:"100%"},0,
                       [   
                           newnode("tbody",{width:"100%"},0,
                               [
                                   newnode("tr",0,0,
                                       [
                                           sNode,
                                           newnode("td",{ width: "18px" },0,[
                                               newnode("img",{ verticalAlign: "middle" },{ src: getFullImgSrc("img/folder/folder_closed.gif") })]
                                           ),
                                           newnode("td",0,0,[ document.createTextNode(folder.title) ]),
                                           newnode("td", { width: "30px",
                                                           verticalAlign: "middle" }, 0,
                                                         iNode ? [iNode] : 0)
                                       ])
                               ])
                         ])
                   ])
                );
            /*
             * Workaround to fix checkbox selection bug in IE
             * As long as the node hasn't been appended to the DOM tree IE6 will ignore
             * setting the checked attribute. A timeout takes care that the node will be
             * appended first.
             */
            if (folder.subscribed == true) {
                setTimeout(function() { 
                    iNode.setAttribute("checked", "checked");
                }, 10);
            }
        };
        
        this.addChangedItem = function (item) {
            for (var i = 0; i < self.changedFolders.length; i++) {
                if (self.changedFolders[i].id == item.id) {
                    self.changedFolders.splice(i, 1);
                  break;
                }
            }
            item["module"] = "folders";
            item["action"] = "update";
            item.tree = configGetKey("modules.folder.tree") || 0;
            self.changedFolders.push(item);
        };
        
        this.saveChanges = function () {
            if (self.changedFolders.length == 0) {
                self.closeWindow();
                return;
            }
            centerPopupWindow($("subscribe_folder_status"));
            $("subscribe_folder_status").style.display="block";
            $("subscribe_folder_status").style.top="100px";
            
            // update
            ox.api.http.PUT({
                module: "multiple",
                data: this.changedFolders,
                appendColumns: false,
                success: function () {
                    self.closeWindow();
                    ox.api.cache.subscribe.clear();
                    ox.api.folder.refresh({ tree: "0" });
                    ox.api.folder.refresh({ tree: "1" });
                }
            });
        };
        
        this.openWindow = function () {
            // get mail accounts
            ox.api.account.all(function (accounts) {
                // init 
                var scrollBar = accounts.length > 3 ? 4 : null;
                var accSel = new ComboBox3(window, "subscribe_folder_account", "20em", 0, true, "cb_subscribe_folder_acc_chd", scrollBar);
                var i = 0, $l = accounts.length;
                for (; i < $l; i++) {
                    accSel.addElement(noI18n(accounts[i].name),
                        "default" + accounts[i].id);
                }
                accSel.getDomNode();
                register("cb_subscribe_folder_acc_chd", function () {
                    self.changeAccount(accSel.getKey());
                });
                self.changeAccount(accSel.getKey());
            });
        };
        
        this.changeAccount = function (id) {

            this.changedFolders = [];
            ox.api.setModal(true);
            removeChildNodes($("subscribe_folder_content"));
                        
            // get sub folders
            ox.api.folder.getSubFolders({
                folder: id,
                all: true,
                tree: "0", // tree 0 only!
                storage: ox.api.cache.subscribe,
                success: function (list) {
                    self.listFolder(list, $("subscribe_folder_content"));
                    showNode("subscribe_folder");
                    centerPopupWindow($("subscribe_folder"));
                    $("subscribe_folder").style.display = "block";
                    $("subscribe_folder_status").style.top = "100px";
                }
            });
        };
        
        this.closeWindow = function () {
            unregister("cb_subscribe_folder_acc_chd", SubscribeFolder.changeAccount);
            this.changedFolders = [];
            ox.api.folder.refresh({ tree: "0" });
            ox.api.folder.refresh({ tree: "1" });
            hideNode("subscribe_folder");
            $("subscribe_folder").style.display = "none";
            ox.api.setModal(false);
        };
    };
    
    return new Class();
    
}());

register("OX_Folder_Cleared",function(folder_id) {
    var tmpFn=OXCache.join.add();
    var allCollections=OXMailMapping.getSubCollectionsfromObject({ folder_id : folder_id });
    for (var i = 0; i < allCollections.length; i++) {
        OXMailMapping.deleteObjectsInternal(allCollections[i].objects);
    }   
    tmpFn();
});

register("OX_Folder_Mark_Read", function(folder_id) {
    (new JSON).put(AjaxRoot + "/mail?action=update&folder=" + folder_id 
            + "&session=" + session, { flags: 32, value: true }, null,
            function(daten){
                var tmpFn=OXCache.join.add();
                var allCollections=OXMailMapping.getSubCollectionsfromObject({ folder_id : folder_id });
                for (var i = 0; i < allCollections.length; i++) {
                    OXMailMapping.editObjectsInternal(allCollections[i].objects, 
                            null, true, [ OXMailMapping.flagmapping["seen"] ]);
                }
                tmpFn();
            }
    );
});

fileloaded();