jQuery(function ($) {
    'use strict';

    var ENTER_KEY = 13;
    var ESCAPE_KEY = 27;
    var showTimeoutId = null;
    var hideTimeoutId = null;
    var showtd = false;

    var App = {

        init: function () {
            this.cacheElements();
        },

        cacheElements: function () {
            this.$content = $('#content');
            this.$Id = $('#id');
            this.taskId = this.$Id.val();
            this.$taskForm = $('#taskform');
            this.getSearchParentWrap = function () { return $('#mergetask'); };
            this.getParentSearchBox = function () { return $('#parentnumber'); };
            this.getColumns = function () { return $('#columns').val(); };
            this.getSearchFullLink = function () { return $('#searchFullLink'); };
        },


        //#region Методы

        showMergeTicketDialog: function () {
            if (!App.getSearchParentWrap().length)
                $.get('Task/MergeTicketDialog',function (html) {
                    App.$content.append(html);
                    var $searchBox = App.getParentSearchBox();
                    var $searchParentWrap = App.getSearchParentWrap();

                $searchParentWrap.find('#columns').multipleSelect({});

                    $searchParentWrap.find('a.fullsearch').bind("click.search", function () { App.searchParentTask(true, true); return false; });

                    $searchBox.keypress(function (e) {
                    if (e.keyCode === ENTER_KEY) {
                            App.searchParentTask(true, true);
                        return false;
                    }
                    });

                $('html').scrollTop(0);
                $searchBox.focus();
                } );

            return false;
        },

        searchParentTask: function (fullTextSearch, searchById) {
            var searchString = App.getParentSearchBox().val();
            var $parentexist = $('ul.parentexist');
            var $parentTaskList = $('#parenttasklist');
            var $searchParentWrap = App.getSearchParentWrap();
            var $errorBox = $searchParentWrap.find('.description');
            var $searchFullLink = App.getSearchFullLink();
            $errorBox.empty().hide();
            $parentexist.empty();

            var taskId = App.taskId;
            var columns = App.getColumns();//Выбранные колонки по которым будет осуществяться поиск

            var success = function (message) {
                if (message) {
                    if (!message.IsOk) {
                        $parentTaskList.hide();
                        $errorBox.text(message.Description).show();
                    } else {

                        if (message.Data.IsNumber)//Если найдена или не найдена заявка по Id                        
                            $searchFullLink.unbind("click.search").bind("click.search", function () { App.searchParentTask(true, false); return false; }).show();
                        else {

                            if (message.Data.IsFullTextSearch)//Если использовался полнотекстовый поиск
                                $searchFullLink.unbind("click.search").bind("click.search", function () { App.searchParentTask(false, false); return false; }).show();
                            else
                                $searchFullLink.hide();
                        }

                        if (message.Description) {
                            $errorBox.text(message.Description).show();//Если выдано сообщение
                        }

                        if (message.Data.TaskResult) {
                            $parentTaskList.show();

                            $.each(message.Data.TaskResult, function (index, task) {
                                var element = App.createElement(task);
                                $parentexist.append(element);
                            });

                            $parentexist.highlight(searchString);
                        }
                    }
                }
            };

            $.ajax({
                contentType: 'application/json',
                url: 'Task/SearchParentTask',
                data: JSON.stringify({
                    search: searchString,
                    taskId: taskId,
                    isFullTextSearch: fullTextSearch,
                    searchById: searchById,
                    columns: columns
                }),
                type: 'POST',
                success: success
            });

            return false;
        },

        createElement: function (task) {

            var result = [];

            var $li = $('<li class="ticketnumber ticketlabel">#</li>');
            var $span = $('<span class="ticketshow"></span>').text(task.Id);
            var $a = $('<a class="js-mergeToParent pointer" title="Выбрать заявку"></a>').attr('data-taskId', task.Id).append($span);
            $span.on('mouseover', App.showDescription).on('mouseout', App.hideDescription);

            result[0] = $li.append($a);
            result[1] = $('<li class="ticketname"></li>').text(task.Name);
            return result;
        },

        showDescription: function (el) {
            showtd = true;
            var $span = $(el.target);
            var $a = $span.parent('a:first');
            var taskId = $a.attr('data-taskId');

            var showDescription = function () {
                if (!showtd) return;
                var tdkey = '#taskdescription_' + taskId;
                var $taskDetails = $(tdkey);
                $('.taskdescription').hide();

                var offset = $span.offset();
                var h = $span.height();
                var w = $(window).width() - 300;
                if (w < 400) w = 400;
                if (w > 900) w = 900;

                if ($taskDetails.length > 0) {
                    $taskDetails.css('top', offset.top + h + 5).css('left', offset.left + 50).css('width', w).fadeIn('fast');
                } else {
                    $taskDetails = $('<div id="taskdescription_' + taskId + '" class="taskdescription popupwrapper"><div class="popup"></div></div>');
                    $('body').append($taskDetails);

                    $taskDetails.css('top', offset.top + h + 5).css('left', offset.left + 40).css('width', w);
                    var hideDescription = App.hideDescription;
                    $taskDetails.mouseover(function () { clearTimeout(hideTimeoutId); }).mouseout(function () {
                        hideTimeoutId = setTimeout(hideDescription, 500);

                    });

                    $.get('Task/GetTaskDetails/' + taskId, { withoutmark: true }, function (data) {
                        if (!showtd) return;

                        var $target = $('.popup', $taskDetails);
                        $target.html(data);
                        $taskDetails.highlight($('#parentnumber').val()).show();
                    });
                }
            };

            showTimeoutId = setTimeout(showDescription, 400);

            clearTimeout(hideTimeoutId);
        },

        hideDescription: function () {
            showtd = false;
            clearTimeout(showTimeoutId);
            hideTimeoutId = setTimeout(function () { $('.taskdescription').hide(); }, 400);
        },

        mergeToParent: function (e) {
            var $el = $(e.currentTarget);
            var parentId = $el.attr('data-taskId');
            App.$taskForm.attr('action', 'Task/MergeToParent?parentId=' + parentId);
            App.$taskForm.submit();
        },

        destroy: function () {
            App.getSearchParentWrap().remove();
        }

        //#endregion
    };

    App.init();
    $('body').on('click', '.js-mergeTicketDialog',function () { App.showMergeTicketDialog(); return false; });
    $('body').on('click', '.js-mergeToParent', App.mergeToParent);
    $('body').on('click', '.js-close-mergeTaskDialog', App.destroy);
});