var taskConcurrency = {
    dlg: undefined,

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

    cacheElements: function () {
        this.$formbody = $('#content .formbody');
        this.$formbottom = $('#content .formbottom');
        this.$shadowbg = $('#content .shadowbg');
        this.getStatus = function () { return $('#statusid'); };
        this.taskId = $('#id').val();
        this.$workflow = $('#workflowid');
        this.serviceId = $('#serviceid').val();
    },

    //#region Методы        

    //Добавление согласующего
    addCoordinator: function (id, userName, companyName, userPosition, $coordinationDialog) {
        var $ul = $coordinationDialog.find('ul:first');
        var $li = $ul.find('li[data-value="' + id + '"]');
        if ($li.length) {
            if ($li.hasClass('archive'))
                taskConcurrency.removeCoordinator($li);
        } else {
            $li = taskConcurrency.getUserTemplate(id, userName, companyName, userPosition);
            $ul.append($li);

            var targetName = $coordinationDialog.attr('data-target');
            var $target = $('[data-prefix="' + targetName + '"]');
            var prefix = targetName + '.Coordinators';
            var $option = $('<input type="hidden" name="' + prefix + '.Index" value="' + id + '"data-coordinator="' + prefix + '[' + id + ']" />' +
                '<input type="hidden" name="' + prefix + '[' + id + '].Id" value="' + id + '"data-coordinator="' + prefix + '[' + id + ']" />');
            $target.append($option);
        }
    },

    addCoordinators: function (ids, names, companies, position) {
        var $coordinationDialog = $('.js-coordination-dialog:visible');
        if (ids) {
            $.each(ids, function (index, id) {
                var userName = names['id' + id];
                var companyName = companies['id' + id].trim();
                var userPosition = position['id' + id].trim();

                taskConcurrency.addCoordinator(id, userName, companyName, userPosition, $coordinationDialog);
            });
        }
    },

    //Удаление согласующих
    removeCoordinator: function ($li) {
        var targetName = $li.parents('.js-coordination-dialog:first').attr('data-target');
        var $target = $('[data-prefix="' + targetName + '"]');

        var isArchive = $li.hasClass('archive');
        var id = $li.attr('data-value');
        var $option = $target.find('[name="' + targetName + '.Coordinators' + '[' + id + '].Id' + '"]');
        var $elements = $target.find('[data-coordinator="' + $option.attr('data-coordinator') + '"]');

        //если этот же пользователь присутствует в других группах, то обработаем его так же
        var $sameUsers = $li.parent().find('li[data-value=' + id + ']');

        if (isArchive) {
            $li.removeClass('archive').addClass('changed');
            $sameUsers.removeClass('archive').addClass('changed');

            if ($elements.length)
                $elements.prop('disabled', false);
            else {
                var prefix = targetName + '.Coordinators';
                $option = $('<input type="hidden" name="' + prefix + '.Index" value="' + id + '"data-coordinator="' + prefix + '[' + id + ']" />' +
                    '<input type="hidden" name="' + prefix + '[' + id + ']" value="' + id + '"data-coordinator="' + prefix + '[' + id + ']" />');

                $target.append($option);
            }
        } else {
            $li.addClass('archive changed');
            $sameUsers.addClass('archive changed');

            $elements.prop('disabled', true);
        }
    },

    next: function (e) {
        var $target = $(e.target);
        var $container = $target.parents('.js-coordination-dialog:first');

        if (taskConcurrency.validate())
            $container.hide().next().show();
    },

    getUserTemplate: function (id, userName, companyName, userPosition) {
        var fullUserName = userPosition.length !== 0 
            ? userName + ' (' + userPosition + ')'
            : userName + ' (' + companyName + ')';

        var $template = $('<li data-value="' + id + '" class="changed"><a class="pointer js-removeCoordinator"><img src="img/trash.gif"></a><span> ' + fullUserName + '</span><div class="spacer10"></div></li>');

        return $template;
    },

    validate: function () {
        var $coordinationDialog = $('.js-coordination-dialog:visible');
        var targetName = $coordinationDialog.attr('data-target');
        var $target = $('[data-prefix="' + targetName + '"]').find('input:enabled');

        var selectedIds = $target.val();
        if (!selectedIds || !selectedIds.length) {
            alert(TaskResources.SelectCoordinator);
            return false;
        }
        return true;
    },

    close: function () {
        $('#assignCoordinationDialog').remove();

        taskConcurrency.$formbody.show();
        taskConcurrency.$formbottom.show();

        var $removedStatusId = $('#removedStatusId');

        if ($removedStatusId.length > 0) {
            taskConcurrency.getStatus().remove();
            $removedStatusId.attr('id', 'statusid').attr('name', 'statusid').removeAttr('disabled');
        }

        $('.save,.saveandreturn').attr('disabled', false);

        $('body').trigger('closeCoordinationDialog');
    },

    showAssignCoordinationDialog: function () {

        var data = { taskId: taskConcurrency.taskId, creatorId: $('#creatorid').val(), statusId: taskConcurrency.getStatus().val(), workflowId: taskConcurrency.$workflow.val(), serviceId: taskConcurrency.serviceId };
        //$.get('Task/GetIsPossibleCoordinators', data, function (result) {
        //    if (result.hasOwnProperty('IsOK') && result.IsOK == false && result.Description) {
        //        if (result.Exception)
        //            alert(result.Exception);
        //        if (result.Description) {
        //            if (confirm(result.Description)) {
        //                $('#isChangeStatusForced').val('true');
        //                $('form button.save').click();
        //            }
        //            else {
        //                result.IsOK = true;
        //            }
        //        }
        //    }
        //    if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
                $.get('Task/AssignCoordinatorsDialog', data, function (result) {
                    if (result.hasOwnProperty('IsOK') && result.IsOK == false) {
                        alert(result.Description);
                    }
                    else {
                        var html = result;
                        taskConcurrency.$formbody.hide();
                        taskConcurrency.$formbottom.hide();

                        var $assignCoordinationDialog = $('<div id="assignCoordinationDialog"></div>');
                        taskConcurrency.$shadowbg.append($assignCoordinationDialog);

                        $assignCoordinationDialog.append(html);

                        $assignCoordinationDialog.find('input.js-add-coordinators').devbridgeAutocomplete({
                            serviceUrl: 'Task/FindCoordinators/' + taskConcurrency.serviceId,
                            minChars: 1,
                            autoClearInputOnSelect: true,
                            onSelect: function (suggestion) {
                                var userName = suggestion.value;
                                var companyName = suggestion.data.companyName;
                                var id = suggestion.data.id;
                                var userPosition = suggestion.data.userPosition;
                                taskConcurrency.addCoordinator(id, userName, companyName, userPosition, $(this).parents('.js-coordination-dialog:first'));
                            }
                        });

                        $assignCoordinationDialog.find('.js-select-many-coordinators').on('click', function () {
                            var url = 'user.ivp/select?cbmode=taskConcurrency&reset=true&tb_mode=all&tb_serviceid=' + $('#serviceid').val();
                            taskConcurrency.dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
                            taskConcurrency.dlg.callback = taskConcurrency.usersCallback;

                            return false;
                        });
                    }
                });
        //  }
        //});
    },

    usersCallback: function usersCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        var companies = result["selectedCompanies"];
        var position = result["selectedPositions"];
        taskConcurrency.addCoordinators(ids, names, companies, position);
    }

    //#endregion
};

jQuery(function ($) {
    taskConcurrency.init();
    $('body').on('click', '.js-close-assignCoordinationDialog', taskConcurrency.close);
    $('body').on('click', '.js-next-coordinationDialog', taskConcurrency.next);
    $('body').on('showCoordinationDialog', taskConcurrency.showAssignCoordinationDialog);
    $('body').on('click', '.js-removeCoordinator', function (e) { taskConcurrency.removeCoordinator($(e.currentTarget).parents('li:first')); });
});