(function () {
    var contacts = window.contacts = {};

    var contactId = null;
    var contactName = null;
    var contactEmail = null;
    var contactCountry = null;
    var contactCity = null;
    var contactCompany = null;
    var contactPhone = null;
    var url = "api/contacts/";

    contacts.initialize = function () {
        $(".rsbInput ").keyup(function (event) {
            filterContactList(event.target.value);
            if (event.keyCode === 13) {
                $('.itemTemplate:visible').addClass("focused");
            }
        });

        $.expr[":"].contains = $.expr.createPseudo(function (arg) {
            return function (elem) {
                return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
            };
        });

        $(".contacts-list").on("click", ".button.mail", function () {
            var $contactWrapper = $(this).parents(".itemTemplate");
            var email = $contactWrapper.attr("data-contact-email");
            window.location.href = 'new.aspx?email=' + email;
        });

        $(".contacts-list").on("click", ".button.edit", function () {
            editContact(this);
        });

        $(".contacts-list").on("click", ".button.delete", function () {
            var $contactWrapper = $(this).parents(".itemTemplate");
            $contactWrapper.addClass("removed");
            $(".section").append($("#contactActionMenu"));
            if ($('#contactEditForm').parent(".itemTemplate").hasClass("selected") === false) {
                $(".section").append($('#contactEditForm'));
            }
            var contactId = $contactWrapper.attr("data-contact-id");

            $.ajax({
                type: "DELETE",
                url: url + contactId,
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    $contactWrapper.parent().remove();
                }
            });
        });

        $(".contacts-list").on("mouseenter", "div.itemTemplate", function () {
            showContactMenu(this);
        });

        $(".contacts-list").on("mouseleave", "div.itemTemplate", function () {
            $(this).removeClass("hovered");
        });

        worker.addFolderClicked();
    };

    function showEditForm(contact) {
        contactName.set_value(contact.Name);
        contactEmail.set_value(contact.Email);
        contactCountry.set_value(contact.Country);
        contactCity.set_value(contact.City);
        contactCompany.set_value(contact.Company);
        contactPhone.set_value(contact.Phone);
        $('#editFormImg').attr("src", 'Images/contacts/' + contact.ImageUrl);
        $('#contactEditForm').show();
    }

    function initializeEditForm() {
        var element = document.getElementById('contactEditForm');

        contactName = $telerik.findControl(element, "rtbContactName");
        contactEmail = $telerik.findControl(element, "rtbContactEmail");
        contactCountry = $telerik.findControl(element, "rtbContactCountry");
        contactCity = $telerik.findControl(element, "rtbContactCity");
        contactCompany = $telerik.findControl(element, "rtbContactCompany");
        contactPhone = $telerik.findControl(element, "rtbContactPhone");
    }

    function showContactMenu(element) {
        $(element).addClass("hovered");
        if (!$(element).hasClass("removed")) {
            $(element).append($("#contactActionMenu"));
        }
    }

    function setEditFormPosition($contactWrapper) {
        var selectedClassName = "selected";
        var $editFormElement = $('#contactEditForm');

        $editFormElement.appendTo($contactWrapper);
        $("." + selectedClassName).removeClass(selectedClassName);
        $contactWrapper.addClass(selectedClassName);
    }

    function editContact(buttonElement) {
        var $contactWrapper = $(buttonElement).parents(".itemTemplate");
        contactId = $contactWrapper.attr("data-contact-id");
        initializeEditForm();
        setEditFormPosition($contactWrapper);
        showEditContact(contactId);
    }

    function showEditContact(contactId) {
        return $.get(url + contactId, function (data) {
            showEditForm(data);
        });
    }

    function filterContactList(text) {
        $('.itemTemplate:visible').removeClass("focused");
        $(".header:not(:contains('" + text + "'))").parent().parent().hide();
        $(".header:contains('" + text + "')").parent().parent().show();
    }

    contacts.clientNodeClicked = function (sender, args) {
        var command = args.get_node().get_text();
        var clientExportManager = $find("ctl00_MainContent_clientExportManager");

        switch (command) {
            case "Export to PDF":
                var pdfSettings = {
                    fileName: "contacts.pdf",
                    proxyURL: "contacts.aspx",
                    title: "RadClientExportManager Sample",
                    author: "Telerik",
                    subject: "Contacts",
                    keywords: "a keyword",
                    creator: "Telerik"
                };

                clientExportManager.set_pdfSettings(pdfSettings);
                clientExportManager.exportPDF(".RadListView");
                break;
            default:
        }
    };

    contacts.saveContact = function () {
        var updatedContact = {
            Company: contactCompany.get_value(),
            Name: contactName.get_value(),
            City: contactCity.get_value(),
            Country: contactCountry.get_value(),
            Phone: contactPhone.get_value(),
            Email: contactEmail.get_value()
        };

        $.ajax({
            type: "PUT",
            data: JSON.stringify(updatedContact),
            url: url + contactId,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                contacts.updateContactListItem(updatedContact, contactId);
                contacts.hideEditForm();
            }
        });
    };

    contacts.hideEditForm = function () {
        var seelctedClassName = "selected";

        $('#contactEditForm').hide();
        $(".itemTemplate." + seelctedClassName).removeClass(seelctedClassName);
    };

    contacts.updateContactListItem = function (updatedContact, contactId) {
        var itemTemplate = $("div[data-contact-id='" + contactId + "']");
        $(itemTemplate).find('.header').text(updatedContact.Name);
        var fields = $(itemTemplate).find('.info');

        $(fields[0]).text(updatedContact.Country);
        $(fields[1]).text(updatedContact.City);
        $(fields[2]).text(updatedContact.Company);
        $(fields[3]).text(updatedContact.Phone);
    };

    contacts.onClientSearch = function (sender, args) {
        filterContactList(args.get_text());
        $('.itemTemplate:visible').addClass("focused");
    };

    contacts.filterGrid = function (value) {
    };
})();