if (!String.format) {
    String.format = function (format) {
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
              ? args[number]
              : match
            ;
        });
    };
}

function editRule(params, link) {
    var url = base + 'notificationrule/edit';
    var title;
    if (params.fromTaskList) {
        title = NotificationRuleResources.EditTitle;
    } else {
        var roleName = $(link).find('input.entityname').val();
        title = String.format(NotificationRuleResources.EditTitleWithRole, roleName);
    }
    if (params.userId != undefined) {
        params.workflowId = $('#CurrentUsersWorkflowId').val();
    }
    $.get(url, params, function (result) {
        createModalDialog(title, result, saveRule, onRuleLoaded);
    });

    return false;
}

function onRuleLoaded() {
    $('input[type="checkbox"].cb.data').on('change', onTeplateCheckboxChange);
    $('.template-select').on('change', onTemplateSelectChange);
    $('#addstatus').devbridgeAutocomplete({
        lookup: window.statuses,
        triggerSelectOnValidInput: false,
        autoClearInputOnSelect: true,
        autoQueryOnEmptyField: true,
        closeAfterOnEnter: true,
        minChars: 1,
        onSelect: onStatusSelected,
        formatResult: function (suggestion, currentValue) {
            var cValue = '<span class="ac-value" statusId="' + suggestion.data.id + '">' + suggestion.value + '</span>';
            return cValue;
        },
        beforeRender: function (container) {
            window.statuses.forEach(function (e) {
                if (e.data.hidden) {
                    container.find('[statusId="' + e.data.id + '"]').closest('div').hide();
                }
            });
        }
    });
}

function onTeplateCheckboxChange() {
    var eventid = $(this).attr('eventid');
    var checked = $('input[eventid="' + eventid + '"]:checked').length > 0;
    var $emailSelect = $('[name="EmailTemplates[' + eventid + ']"]');
    var $pushSelect = $('[name="PushTemplates[' + eventid + ']"]');
    var $smsSelect = $('[name="SmsTemplates[' + eventid + ']"]');
    if (checked) {
        var $defaultEmailTemplate = $emailSelect.find('option[default="true"]');
        if ($defaultEmailTemplate.length > 0) {
            $emailSelect.val($defaultEmailTemplate.val());
        }
        var $defaultPushTemplate = $pushSelect.find('option[default="true"]');
        if ($defaultPushTemplate.length > 0) {
            $pushSelect.val($defaultPushTemplate.val());
        }
    } else {
        $emailSelect.val(0);
        $pushSelect.val(0);
        if ($smsSelect.length > 0) {
            $smsSelect.val(0);
        }
    }
}

function onTemplateSelectChange() {
    var $this = $(this);
    if ($this.val() === '0') return;
    var name = $this.attr('name');
    var indexOfFirst = name.indexOf('[');
    var eventid = name.slice(indexOfFirst + 1, name.indexOf(']'));
    $('input[eventid="' + eventid + '"]').prop('checked', true);
}

function saveRule() {
    $.ajax({
        type: 'POST',
        url: base + 'notificationrule/edit/',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(GetFormModel()),
        complete: function (response) {
            if (typeof (loadNotificationRule) != 'undefined')
                loadNotificationRule();
        }
    });
}

function GetFormModel() {
    var fromTaskList = $('#fromTaskList').val().toLowerCase() == 'true';
    var model = new Object();
    var $form = $('#notificationruleform');
    model.Id = $form.find('#id').val();
    model.RoleId = $form.find('#roleid').val();
    model.WorkflowId = $form.find('input[name="ruleworkflowid"]').val();
    model.ServiceId = $form.find('input[name="serviceid"]').val();
    model.UserId = $form.find('input[name="userid"]').val();
    model.NotificationRuleTemplates = new Array();
    $form.find('table tr:visible').each(function (i, e) {
        var $e = $(e);
        var $templateSelects = $e.find('.template-select');
        if ($templateSelects.length < 1) return;
        var emailTemplate = $($templateSelects[0]);
        var pushTemplate = $($templateSelects[1]);
        var notificationRule = {
            TemplateId: emailTemplate.val(),
            PushTemplateId: pushTemplate.val()
        };
        if (fromTaskList) {
            if (!emailTemplate.is(':checked')) {
                notificationRule.TemplateId = 0;
            }
            if (!pushTemplate.is(':checked')) {
                notificationRule.PushTemplateId = 0;
            }
        }
        if ($templateSelects.length > 2) {
            notificationRule.SmsTemplateId = $($templateSelects[2]).val();
        }

        if (notificationRule.TemplateId === '0' && notificationRule.PushTemplateId === '0' && (notificationRule.SmsTemplateId == undefined || notificationRule.SmsTemplateId === '0'))
            return; //Если не выбран ни один шаблон

        if ($e.hasClass('status-row')) {
            notificationRule.NotificationStatusId = $e.attr('statusid');
        } else {
            var $checkbox = $e.find('input.cb.data:checked');
            if ($checkbox.length < 1) return;
            notificationRule.Event = $checkbox.attr('eventid');
            model[$checkbox.attr('name')] = true;
        }
        model.NotificationRuleTemplates.push(notificationRule);
    });
    return model;
}

function onStatusSelected(suggestion) {
    $('tr[statusId="' + suggestion.data.id + '"]').show();
    var allHidden = true;
    window.statuses.forEach(function (e, i) {
        if (e.data.id == suggestion.data.id) {
            window.statuses[i].data.hidden = true;
        }
        if (!window.statuses[i].data.hidden) {
            allHidden = false;
        }
    });
    if (allHidden) {
        $('#addstatus').hide();
    }
}

function removeSelectedStatus(id) {
    $('tr[statusId="' + id + '"]').hide();
    window.statuses.forEach(function (e, i) {
        if (e.data.id == id) {
            window.statuses[i].data.hidden = false;
        }
    });
    $('#addstatus').show();
}

function deleteNotificationRule(id) {
    if (!confirm(NotificationRuleResources.SureDelete)) return false;
    $.post(base + 'NotificationRule/Delete/', { id: id }, function () { loadNotificationRule(); });
    return false;
}