(function () {
    var mail = window.mail = {};
    var hoveredRowId = "";
    var url = "api/messages/";
    var menu = null;
    var grid = null;
    var nav = null;
    var masterTableView = null;
    var rowElement = null;
    var $activeRowAction = null;

    mail.initialize = function () {
        menu = $find("messagesContextMenu");
        grid = $find($(".RadGrid").attr("id"));
        masterTableView = grid.get_masterTableView();
        worker.addFolderClicked();
        self = this;

        this.hideColumnsInGrid(true);

        $(".rightScndNav .button").on("click", function (e) {
            self.changeView(e);
        });

        mail.filterGrid(1);
    };

    mail.action = function (command) {
        switch (command) {
            case "view":
                loadMessage(hoveredRowId, rowElement);
                break;
            case "delete":
                deleteMessage(hoveredRowId);
                break;
            case "spam":
                moveToJunk(hoveredRowId);
                break;
            default:
        }
    }

    mail.hideColumnsInGrid = function (isTopGrid) {
        var columnCount = masterTableView.get_columns().length - 1;
        var hiddenColumnsUniqName = [];

        if (isTopGrid) {
            hiddenColumnsUniqName.push("FolderId","Compact");
        }
        else {
            hiddenColumnsUniqName.push("From", "Subject", "Received", "FolderId");
        }

        // Show all columns
        for (var i = 0; i <= columnCount; i++) {
            masterTableView.showColumn(i);
        }


        // hide columns
        for (var j = 0; j < hiddenColumnsUniqName.length; j++) {
            var columnName = hiddenColumnsUniqName[j];
            var columnIndex = masterTableView.getColumnByUniqueName(columnName).get_element().cellIndex;
            masterTableView.hideColumn(columnIndex);
        }

        // fix grid colspan
        if (isTopGrid) {
            $(".rgHeaderDiv thead td:first-child").prop("colspan", "5");
            $(".rgGroupHeader .rgGroupCol + td").prop("colspan", "4");
        }
        else {
            $(".rgGroupHeader td:nth-child(2)").prop("colspan", "2");
        }
    };

    mail.changeView = function (e) {
        var command = $(e.currentTarget).attr("data-command-name");
        var $section = $(".section");

        if (command === "right") {
            this.hideColumnsInGrid(false);

        } else if (command === "bottom") {
            this.hideColumnsInGrid(true);
        }
        else {
            return;
        }

        $section.attr("class", "section");
        $section.addClass(command);
        grid.repaint();
    };

    mail.rowDataBound = function (sender, args) {
        var row = args.get_item().get_element();
        var dataItem = args.get_dataItem();
        if (dataItem.IsRead === false) {
            var row = args.get_item().get_element();
            $(row).css("font-weight", "500");
        }
        $(row).find(".subject").append(emailActions());
    };

    mail.showEmailActions = function (sender, args) {
        hoveredRowId = args._dataKeyValues.MessageID;
        rowElement = args.get_item().get_element();
        $activeRowAction = $(rowElement).find(".emailActions");
        $activeRowAction.show();
    };

    mail.hideEmailActions = function (sender, args) {
        $activeRowAction.hide();
    };

    mail.hoverAction = function (command) {
        switch (command) {
            case "view":
                loadMessage(hoveredRowId, rowElement);
                break;
            case "delete":
                deleteMessage(hoveredRowId);
                break;
            case "spam":
                moveToJunk(hoveredRowId);
                break;
            default:
        }
    };

    mail.rowClick = function (sender, args) {
        var id = args.getDataKeyValue("MessageID");
        loadMessage(id, args.get_item().get_element());
    };

    mail.contextMenu = function (sender, args) {
        var evt = args.get_domEvent();
        if (evt.target.tagName === "INPUT" || evt.target.tagName === "A") {
            return;
        }

        var index = args.get_itemIndexHierarchical();

        document.getElementById('clickedRowMessageId').value = args._dataKeyValues.MessageID;

        sender.get_masterTableView().selectItem(sender.get_masterTableView().get_dataItems()[index].get_element(), true);

        menu.show(evt);
        evt.cancelBubble = true;
        evt.returnValue = false;

        if (evt.stopPropagation) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };

    mail.onClientSearch = function (sender, args) {
        var value = args.get_value();
        if (value !== null) loadMessage(args.get_value());
    };

    mail.contextMenuItemClicked = function (sender, args) {
        var command = args.get_item().get_text();
        var row = $(args.get_targetElement()).parent();
        var id = document.getElementById("clickedRowMessageId").value;

        switch (command) {
            case "Mark as read":
                markAsRead(id, row);
                break;
            case "Mark as unread":
                markAsUnread(id, row);
                break;
            case "Delete":
                deleteMessage(id, row);
                break;
            case "Junk":
                moveToJunk(id);
                break;
            case "Print":
                printMessage();
                break;
            default:
        }
    };

    mail.nodeClicked = function (sender, args) {
        var command = args.get_node().get_text();
        var selectedFolder = worker.getSelectedFolderText();

        if (command === selectedFolder) {
            return;
        }

        switch (command) {
            case "Inbox":
                if (selectedFolder !== "Inbox")
                    itterateSelectedItems(moveToInbox);
                break;
            case "Delete":
                itterateSelectedItems(deleteMessage);
                break;
            case "Deleted":
                itterateSelectedItems(deleteMessage);
                break;
            case "Junk":
                if (args.get_node().get_parent() != sender)
                    itterateSelectedItems(moveToJunk);
                break;
            case "Report Spam":
                itterateSelectedItems(moveToJunk);
                break;
            case "Drafts":
                itterateSelectedItems(moveToDrafts);
                break;
            case "Print":
                printMessage();
                break;
            case "Mark as read":
                itterateSelectedItems(markAsRead);
                break;
            case "Mark as unread":
                itterateSelectedItems(markAsUnread);
                break;
            default:
        }
    };

    function itterateSelectedItems(func) {
        var selectedItems = getSelectedRows();
        for (var i = 0; i < selectedItems.length; i++) {
            var item = selectedItems[i];
            func(item._dataItem.MessageID, item.get_element());
        }
    }

    mail.dataBound = function (sender, args) {
        var dataItems = sender.get_masterTableView().get_dataItems();
        if (dataItems.length > 0) {
            var row = dataItems[0];
            row.set_selected(true);
            loadMessage(row._dataItem.MessageID, row.get_element());
            hoveredRowId = row._dataItem.MessageID;
        }
    };

    mail.dataParse = function (sender, args) {
        var messages = args.get_response();

        for (var i = 0; i < messages.length; i++) {
            var date = new Date(messages[i].Received).format("M/dd/yyyy h:mm tt");
            messages[i].Received = date;
            args.set_parsedData(messages);
        }
    };

    function loadMessage(id, element) {
        $.getJSON(url + id).done(function (data) {
            $("#from").text(data.From);
            $("#subject").text(data.Subject);
            $("#recieved").text(data.Received);
            $("#body").html(data.Body).text();

            if (data.IsRead === false && element !== undefined) {
                markAsRead(id, element);
            }
        });
    }

    function markAsRead(id, row) {
        $.post(url + id + "/mark?read=true", function () {
        }).done(function () {
            $(row).css("font-weight", "");
        });
    }

    function markAsUnread(id, row) {
        $.post(url + id + "/mark?read=false", function () {
        }).done(function () {
            $(row).css("font-weight", "bold");
        });
    }

    mail.filterGrid = function (value) {
        masterTableView.get_filterExpressions().clear();

        var columnUniqueName = "FolderId";
        var dataField = "FolderId";
        var filterFunction = Telerik.Web.UI.GridFilterFunction.EqualTo;
        var filterValue = value;
        addFilterExpression(columnUniqueName, dataField, filterFunction, filterValue);
    }

    function addFilterExpression(columnUniqueName, dataField, filterFunction, filterValue) {
        var filterExpression = new Telerik.Web.UI.GridFilterExpression();
        var column = grid.get_masterTableView().getColumnByUniqueName(columnUniqueName);
        column.set_filterFunction("EqualTo");
        filterExpression.set_fieldName(dataField);
        filterExpression.set_fieldValue(filterValue);
        filterExpression.set_filterFunction(filterFunction);
        filterExpression.set_columnUniqueName(columnUniqueName);
        masterTableView._filterExpressions.add(filterExpression);
        rebindGrid();
    }

    function rebindGrid() {
        masterTableView.rebind();
    }

    function deleteMessage(id) {
        $.ajax({
            type: "DELETE",
            url: url + id,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                var selectedFolder = worker.getSelectedFolderValue();
                var link = worker.get_selected();
                if (link !== null) {
                    worker.updateCount(worker.getSelectedFolderText(), false);
                    worker.updateCount("Deleted");
                    rebindGrid();
                    deselectGridRows();
                }
            }
        });
    }

    function moveToJunk(id) {
        $.ajax({
            type: "POST",
            url: url + id + "/spam",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                worker.updateCount("Junk");
                worker.updateCount(worker.getSelectedFolderText(), false);
                rebindGrid();
            }
        });
    }

    function moveToDrafts(id) {
        $.ajax({
            type: "POST",
            url: url + id + "/drafts",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                worker.updateCount("Drafts");
                worker.updateCount(worker.getSelectedFolderText(), false);
                rebindGrid();
            }
        });
    }

    function moveToInbox(id) {
        $.ajax({
            type: "POST",
            url: url + id + "/inbox",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                worker.updateCount("Inbox");
                worker.updateCount(worker.getSelectedFolderText(), false);
                rebindGrid();
            }
        });
    }

    function getSelectedRows() {
        return masterTableView.get_selectedItems();
    }

    function deselectGridRows() {
        var selectedRows = getSelectedRows();
        for (var i = 0; i < selectedRows.length; i++) {
            selectedRows[i].set_selected(false);
        }
    }

    function printMessage() {
        var messageWindow = window.open('', 'Print Message', 'height=400,width=600');
        messageWindow.document.write("<html><head><title>" + $("#subject").text() + "</title>");
        messageWindow.document.write("</head><body >");
        messageWindow.document.write($("#pnlMessage").html());
        messageWindow.document.write("</body></html>");
        messageWindow.document.close(); // necessary for IE >= 10
        messageWindow.focus(); // necessary for IE >= 10
        messageWindow.print();
        messageWindow.close();

        return true;
    }

    function emailActions() {
        return $('<div class="emailActions" style="display:none">' +
                    '<span class="icon icon-View" onclick="mail.action(\'view\')"></span>' +
                    '<span class="icon icon-Delete" onclick="mail.action(\'delete\')"></span>' +
                    '<span class="icon icon-Spam" onclick="mail.action(\'delete\')"></span>' +
                '</div>').get(0);
    }

})();