(function () {
    var notes = window.notes = {};
    var url = "api/notes/";
    var grid = null;
    var radWindow = null;
    var editor = null;
    var selectedNoteId = null;
    var masterTableView = null;

    notes.initialize = function () {
        radWindow = $find("ctl00_MainContent_rwNotesPreview");
        editor = $find($(".RadEditor").attr("id"));
        grid = $find('ctl00_MainContent_rgNotes');
        masterTableView = grid.get_masterTableView();
        worker.addFolderClicked();
    };

    notes.contextMenuItemClicked = function (sender, args) {
        var command = args.get_item().get_text();
        var row = $(args.get_targetElement()).parent();
        var id = document.getElementById("clickedRowNoteId").value;
        var categoryId = document.getElementById("clickedRowCategoryId").value;
        var url = "api/notes/" + id;
        
        switch (command) {
            case "Open":
                previewNote(id);
                break;
            case "Move":
                markAsRead(url, row);
                break;
            case "Delete":
                deleteNotes(id);
                break;

            default:
        }
    };

    notes.nodeClicked = function (sender, args) {
        var command = args.get_node().get_text();

        switch (command) {
            case "Delete":
                deleteNotes();
                break;
            case "All":
                break;
            case "Personal":
                break;
            case "Work":
                break;
            default:
        }
    };

    notes.cancelEditClick = function (sender, args) {
        radWindow.hide();
    };

    notes.updateNoteClick = function (sender, args) {
        var noteContent = editor.get_html();
        updateNode(selectedNoteId, noteContent);
    };

    notes.DataParse = function (sender, args) {
        var notes = args.get_response();

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

        args.set_parsedData(notes);
    };

    notes.search = function (sender, args) {
        if (args.get_value()) {
            previewNote(args.get_value());
        }
    }

    function updateNode(noteId, noteContent, categoryId) {
        var note = { Id: noteId, CategoryId: categoryId, NoteContent: noteContent };

        $.ajax({
            type: "PUT",
            data: JSON.stringify(note),
            url: url + noteId,
            contentType: "application/json; charset=utf-8",
            success: function () {
                radWindow.hide();
            }
        });
    }

    function previewNote(noteId) {
        selectedNoteId = noteId;

        $.ajax({
            type: "GET",
            url: url + noteId,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                editor.set_html(data.NoteContent);
                radWindow.set_title(data.Subject);
                radWindow.show();
            }
        });
    }

    function deleteNotes(noteId) {
        $.each(getSelectedRows(), function (index, value) {
            $.ajax({
                type: "DELETE",
                url: url + value._dataItem.Id,
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    rebindGrid();
                    deselectGridRows();
                    worker.updateCount(worker.getSelectedFolderText(), false);
                }
            });
        });
    }

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

        if (value !== "All") {
            var columnUniqueName = "Name";
            var dataField = "Name";
            var filterFunction = Telerik.Web.UI.GridFilterFunction.EqualTo;
            var filterValue = value;
            addFilterExpression(columnUniqueName, dataField, filterFunction, filterValue);
        } else {            
            rebindGrid();
        }
    }

    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();
    }

    notes.removeGridFiltering = function () {
        masterTableView.get_filterExpressions().clear();
        rebindGrid();
    }

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

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

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

    notes.contextMenu = function (sender, args) {
        var menu = $find("notesContextMenu");
        var evt = args.get_domEvent();
        if (evt.target.tagName === "INPUT" || evt.target.tagName === "A") {
            return;
        }

        var index = args.get_itemIndexHierarchical();

        document.getElementById('clickedRowNoteId').value = args._dataKeyValues.Id;
        document.getElementById('clickedRowCategoryId').value = args._dataKeyValues.CategoryId;
        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();
        }
    };
})();