(function () {
    var desktop = window.desktop = {};
    var tree = null;
    var category = "";
    var textBoxNewFolder = null;
    var count = 0;
    var $newFolderContainer = null;
    var NEW_FOLDER_TEXT = "New Folder";
    var DEFAULT_COUNT = " (0)";
    var systemFolders = ["Inbox", "Junk", "Drafts", "Deleted", "All", "Personal", "Work", "Development", "Design", "Marketing"];
    var addedByContextMenu = -1;
    var addedByContextMenuNode = null;
    var enterPressed = false;
    var escapePressed = false;
    var readonly = false;

    desktop.initialize = function (nav) {
        if (nav === "desktop") {
            var newFolderElement = document.getElementById('newFolderContainer');
            textBoxNewFolder = $telerik.findControl(newFolderElement, 'rtbFolder');
            tree = $find($('div.RadTreeView').attr('id'));
            category = $('.home-btn span.text').text();
            $newFolderContainer = $("#newFolderContainer");
            readonly = $(".readonly").val();

            $(".riTextBox").keyup(function (event) {
                if (event.which === 27) {
                    escapePressed = true;
                    hideNewFolderContainer();
                    event.preventDefault();
                }
            })
        }
    };

    desktop.nodeDataBound = function (sender, args) {
        var node = args.get_node();

        var hasChildren = node.get_value().split('|');
        if (hasChildren[1] === 'False') {
            args.get_node().set_expandMode(0);
        }

        var folderText = getFolderText(node.get_text());
        if ($.inArray(folderText, systemFolders) === -1) {
            $(node.get_element()).addClass("editable");
        } else {
            node.set_allowEdit(false);
            if (folderText === "Deleted" || folderText === "All") {
                $(node.get_element()).addClass("last");
            }
        }
    };

    desktop.editStart = function (sender, args) {
        var input = args.get_node().get_inputElement();
        var text = input.value;
        var regex = /\(.*\)/;
        count = text.match(regex);
        input.value = text.replace(regex, '').trim();
    };

    desktop.nodeEdited = function (sender, args) {
        var node = args.get_node();
        var folderId = getFolderId(node);
        var newName = node.get_text();
        var parentId = null;

        if (node.get_parent() !== sender) {
            parentId = getFolderId(node.get_parent());
        }
        updateNode(newName, folderId, parentId);
        node.set_text(newName + " " + count);
        count = 0;
    };

    desktop.addNewFolderClick = function (parentId) {
        if ($newFolderContainer.hasClass('hidden')) {
            $newFolderContainer.removeClass('hidden');
            $newFolderContainer.find(".riTextBox").focus();
        }
        else {
            addFolder(parentId);
        };
    }

    desktop.contextMenuShowing = function (sender, args) {
        if (readonly === "True") {
            args.set_cancel(true);
        }

        var node = args.get_node();
        var menu = args.get_menu();
        var renameItem = menu.findItemByText("Rename");
        var deleteITem = menu.findItemByText("Delete");

        if (node.get_allowEdit()) {
            renameItem.set_enabled(true);
            deleteITem.set_enabled(true);
        } else {
            renameItem.set_enabled(false);
            deleteITem.set_enabled(false);
        }
    };

    desktop.contextMenuClicked = function (sender, args) {
        var command = args.get_menuItem().get_text();
        var node = args.get_node();

        switch (command) {
            case "Add New Folder":
                addedByContextMenuNode = node;
                addedByContextMenu = getFolderId(node);
                desktop.addNewFolderClick(desktop.getSelectedFolderValue());
                break;
            case "Delete":
                deleteFolder(getFolderId(node), node);
                break;
            case "Rename":
                node.startEdit();
                break;
            default:
        }
    };

    desktop.rtbFolderKeyPress = function (sender, args) {        
        if (args.get_keyCode() === 13) {
            var event = args.get_domEvent();

            event.cancelBubble = true;
            event.returnValue = false;
            if (event.stopPropagation) {
                event.stopPropagation();
                event.preventDefault();
            }
            enterPressed = true;
            if (addedByContextMenu !== -1) {
                addFolder(addedByContextMenu);
            } else {
                addFolder(null);
            }
            
        }
    };

    desktop.rtbBlur = function (sender, args) {
        if (addedByContextMenu !== -1 && !enterPressed && !escapePressed) {
            addFolder(addedByContextMenu);

        } else if (!enterPressed && !escapePressed) {
            addFolder(null);
        }
        enterPressed = false;
        escapePressed = false;
    }

    desktop.getSelectedFolderText = function () {
        var node = tree.get_selectedNode();
        if (node) {
            var regex = /\(.*\)/;
            var text = node.get_text().replace(regex, '');
            return text.trim();
        }
    };

    desktop.getSelectedFolderValue = function () {
        var node = tree.get_selectedNode();
        if (node) {
            return getFolderId(node);
        }
    };

    desktop.treePopulated = function (sender, args) {
        var nodes = sender.get_nodes();
        if (nodes.getNode(0) !== null) {
            nodes.getNode(0).select();
        }
    };

    desktop.updateCount = function (folder, increase) {
        if (folder === null) return;
        var $folderText = $(".rtIn:contains('" + folder + "')");
        if ($folderText.size() === 0) return;
        var text = $folderText.text();
        var regex = /\((.*?)\)/;
        count = parseInt(text.match(regex)[1], 10);
        if (increase === undefined || increase === true) {
            count++;
        } else {
            if (count === 0) return;
            count--;
        }
        var updatedNode = tree._extractNodeFromDomElement($folderText[0]);
        updatedNode.set_text(text.replace(regex, '(' + count + ')'));
    };

    desktop.get_navigationControl = function () {
        return this.tree;
    }

    desktop.get_selected = function () {
        return tree.get_selectedNode();
    }

    desktop.addFolderClicked = function () {
        tree.add_nodeClicked(function (sender, args) {
            var nodeValue = args.get_node().get_value();
            var folderId = parseInt(nodeValue.split('|')[0], 10);
            var folderText = getFolderText(args.get_node().get_text());
            if (typeof mail === 'object') {
                mail.filterGrid(folderId);
            } else if (typeof notes === "object") {
                notes.filterGrid(folderText);
            }
        });
    }

    function addFolder(parentId) {
        var folder = { Name: getFolderName(), ParentId: parentId, Attributes: category };
        sender = tree.get_selectedNode() === null ? tree : tree.get_selectedNode();

        $.ajax({
            type: "POST",
            data: JSON.stringify(folder),
            url: "api/folders",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                tree.trackChanges();
                var node = new Telerik.Web.UI.RadTreeNode();
                node.set_text(getFolderName() + getFolderCount(count));
                node.set_value(result.Id + "|False");
             
                if (parentId !== null && addedByContextMenu === -1) {
                    sender.get_nodes().add(node);
                } else if (parentId !== null && addedByContextMenu !== -1) {
                    addedByContextMenuNode.get_nodes().add(node);
                } else {
                    tree.get_nodes().add(node);
                }

                tree.commitChanges();
                textBoxNewFolder.clear();
                addedByContextMenu = -1;
                addedByContextMenuNode = null;
                hideNewFolderContainer();
            }
        });
    }

    function getFolderId(node) {
        return node.get_value().split('|')[0];
    }

    function getFolderText(text) {
        return text.replace(/\(.*\)/, '').trim();
    }

    function getFolderName() {
        return textBoxNewFolder.get_textBoxValue() !== "" ? textBoxNewFolder.get_textBoxValue() : NEW_FOLDER_TEXT;
    }

    function getFolderCount(value) {
        if (!value) {
            return DEFAULT_COUNT;
        } else {
            return " " + value;
        }
    }

    function deleteFolder(folderId, node) {
        $.ajax({
            type: "DELETE",
            url: "api/folders/" + folderId,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                node.get_parent().get_nodes().remove(node);
            }
        });
    }

    function getParentId() {
        var node = tree.get_selectedNode();
        if (!node) return null;
        return get;
    }

    function updateNode(folderName, folderId, parentId) {
        var folder = { Id: folderId, Name: folderName, ParentId: parentId, Attributes: category };
        $.ajax({
            type: "PUT",
            data: JSON.stringify(folder),
            url: "api/folders/" + folderId,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
            }
        });
    }

    function hideNewFolderContainer() {
        $newFolderContainer.addClass("hidden");
    }
})();