var dlg = null;

$(function () {
    if ($('#readonly').length > 0) {
        $('input,textarea').attr('readonly', true).addClass('disabled');
        $('select').attr('disabled', true).addClass('disabled');
    }

    if (!$('#serviceid').val() && $('#id').val() === '0') {
        $('#chooseservice').fadeIn('fast');
        $('#createFromUnregUsers').attr('disabled', true)
    }

    $("form").validate();

    //fix 34000
    var validator = $('form').data('validator');
    $.extend(validator.settings,
    {
        rules: {
            server: {
                remote: {
                    url: "ImportMailaccount.ivp/CheckAcountExist",
                    type: "post",
                    data: {
                        id: function () {
                            return $('#id').val();
                        },
                        account: function () {
                            return $("#account").val();
                        }
                    }
                }
            },
            account: {
                remote: {
                    url: "ImportMailaccount.ivp/CheckAcountExist",
                    type: "post",
                    data: {
                        id: function () {
                            return $('#id').val();
                        },
                        server: function () {
                            return $("#server").val();
                        }
                    }
                }
            }
        },
        messages: {
            server: {
                remote: "Такие сервер и логин уже зарегистрированы"
            },
            account: {
                remote: "Такие сервер и логин уже зарегистрированы"
            }
        }
    });

    $("#server").bind('change', resetValidation);

    $("#account").bind('change', resetValidation);

    function resetValidation() {
        validator.resetForm();
    }

    $("form").submit(function () {
        if (!$("#createtask").attr('checked') && !$("#createtaskcommentfromreply").attr('checked')) {
            alert(ImportMailResources.NeedTypeAccount);
            return false;
        }
    });

    //$.validator.addMethod("validateCompany", function (value, element) {
    //    if (!$("#createuserbycompany").prop('checked'))
    //        return true;

    //    return Number($("#companyid").val()) > 0;
    //}, FormResources.FieldRequired);

    //$("#addCompany").rules("add", {
    //    validateCompany: true,
    //    messages: {
    //        validateCompany: FormResources.FieldRequired
    //    }
    //});  

    $("#password2").rules("add", { equalTo: "#password" });

    $('#serviceid').change(function () {
        //$.getJSON(base + 'service.ivp/getserviceuser/' + this.value, { json: true, date: new Date().toString() }, function(users) {
        //    $('#alltasktypefieldsrequired').hide();
        //    //var select = $('#defaultuserid').get(0);
        //    //select.options.length = 0; select.options.add(new Option('', ''));
        //    //$(users).each(function(i, el) { select.options.add(new Option(el.Name, el.Id)); });
        //});

        //подтягивает типы заявок, разрешенные на выбранном сервисе
        var select = $('#tasktypeid').get(0);
        if (select) {
            select.options.length = 0; select.options.add(new Option('', ''));
            if (!this.value) return;

            $.getJSON(base + 'ImportMailAccount.ivp/GetTaskTypes/' + this.value, { timestamp: new Date().toString() }, function (result) {
                $(result.ServiceTaskType).each(function (i, el) { select.options.add(new Option(el.Name, el.Id)); });
                if (result.ServiceTaskType.length > 0) {
                    if (result.ServiceTaskType.length == 1) {
                        select.value = result.ServiceTaskType[0].Id;
                    }
                    $('#alltasktypefieldsrequired').hide();
                    $('#tasktypeid').parents('.field').show();
                    $('#labelfortasktypeid').addClass('required');
                    $('#tasktypeid').addClass('required');
                }
                else {
                    if (!result.IsOK) $('#alltasktypefieldsrequired').show();
                    $('#tasktypeid').parents('.field').hide();
                    $('#labelfortasktypeid').removeClass('required');
                    $('#tasktypeid').removeClass('required');
                }
            });
        }
        $('#createFromUnregUsers').attr('disabled', false);
        $('#chooseservice').fadeOut('fast');
    });

    $('#createFromUnregUsers').click(handleUnregUsers);
    $('#createuser').click(handleAutomaticUser);
    $('#createuserbycompany').click(handleUserByCompany);
    if ($('#createtaskcommentfromreplyTrue').is(':checked')) {
        switchImportMailFields('comment');
    }
    else {
        switchImportMailFields('task');
    }
    handleUnregUsers();
    handleAutomaticUser();
    handleUserByCompany();

    loadRules();

    function handleUnregUsers() {
        var show = $('#createFromUnregUsers').is(':checked');
        var automatic = $('#createuser').is(':checked');
        if (!show) {
            $("label[for='createuser']").hide();
            $('#createuser').removeAttr('checked');
            $('#notifyuser').removeAttr('checked');
            $('#createuserbycompany').removeAttr('checked');
            $('#FromUnregUsers').hide();//.find('select').removeClass('required').val('');
            removedefaultUser();
            $('#FromUnregUsers').find('label').removeClass('required');
            $("#automaticuser").hide().find('select').removeClass('required').val('');
            $('#automaticuser').find('label').removeClass('required');
            $("#companydetails").hide();
            //remove company
            $('#companyholder').hide();
            $('#companyholder a').remove();
            $('#addCompanyTable').hide();
            $('#companyid').val('');
            $("label[for='companyid']").hide().removeClass('required');
            $('#companyholder').parent().find('.details').hide();
        }
        else {
            $("label[for='createuser']").show();
            $('#FromUnregUsers').show();//.find('select').addClass('required');
            $('#FromUnregUsers').find('label').addClass('required');
        }
    }

    function handleAutomaticUser() {
        var automatic = $('#createuser').is(':checked');
        var userbycompany = $('#createuserbycompany').is(':checked');
        var show = $('#createFromUnregUsers').is(':checked');
        if (automatic) {
            $('#FromUnregUsers').hide();//.find('select').removeClass('required').val('');
            $('#FromUnregUsers').find('label').removeClass('required');
            removedefaultUser();
            $('#automaticuser').show().find('select').addClass('required');
            $('#automaticuser').find('label').addClass('required');
            $("label[for='createuserbycompany']").removeClass('required');
            $("label[for='notifyuser']").removeClass('required');
            $("#companydetails").show();
            if (!userbycompany) {
                //$('select#companyid').hide().removeClass('required').val('');
                $('#companyholder').hide();
                $('#addCompanyTable').hide();
                $('#companyid').val('');
                $("label[for='companyid']").hide().removeClass('required');
            }
        }
        else {
            if (show) {
                $('#FromUnregUsers').show();//.find('select').addClass('required');
                $('#FromUnregUsers').find('label').addClass('required');
            }
            $('#automaticuser').hide().find('select').removeClass('required').val('');
            $('#automaticuser').find('label').removeClass('required');
            $('#createuserbycompany').removeAttr('checked');
            $('#companyholder').hide();
            $('#addCompanyTable').hide();
            $('#companyid').val('');
            $("label[for='companyid']").hide().removeClass('required');
            $('companyholder').parent().find('.details').hide();
            $('#notifyuser').removeAttr('checked');
            $("#companydetails").hide();
        }
    }

    function handleUserByCompany() {
        var userbycompany = $('#createuserbycompany').is(':checked');
        if (userbycompany) {
            $('#companyholder').show();
            $('#addCompanyTable').show();
            $("label[for='companyid']").show().addClass('required');
            $('#companyholder').parent().find('.details').show();
        }
        else {
            $('#companyholder').hide();
            $('#companyholder a').remove();
            $('#addCompanyTable').hide();
            $('#companyid').val('');
            $("label[for='companyid']").hide().removeClass('required');
            $('#companyholder').parent().find('.details').hide();
        }
    }

    $('#addCompany').autocomplete(base + 'company.ivp/searchidname/', { minChars: 1 }).result(companySelectedFromAutoComplete);
    $('#adddefaultUser').autocomplete(base + 'importmailaccount.ivp/SearchDefaultUser/', { minChars: 1, cacheLength: 0, extraParams: { serviceid: function () { return $('#serviceid').val(); }, accountid: function () { return $('#id').val(); } } }).result(defaultUserSelectedFromAutoComplete);
    $("#typeid").bind('change', changeType);
});

function changeType() {
    if ($(this).val() == 3) {
        $('#fieldsMsGraph').show();
        $('.fieldsOtherType').hide();
        $('#server').removeClass('required');
        $('#password').add('#password2').attr('disabled', true);
    }
    else {
        $('#fieldsMsGraph').hide();
        $('.fieldsOtherType').show();
        $('#server').addClass('required');
        $('#password').add('#password2').attr('disabled', false);
    }
}
function loadRules(page) {
    $("#importmailaccountrules").load("importmailaccountrule.ivp/list", { tb_page: page, nolayout: true, id: $('#id').val(), reset: true }, function () {
        $('.helplink').unbind('click').click(function () { openDialog($(this).attr('href')); return false; });

        $("#dialog").dialog({
            autoOpen: false,
            width: 740,
            modal: true,
            resizable: true,
            close: function () {
                dialogClose();
            }
        });

        initTable();

        //выставим высоту блока pagination
        var headerRuleTable = $("#importmailaccountrules h2:first");
        var paginationRuleTable = $("#importmailaccountrules #pagination");
        if (headerRuleTable.length > 0 && paginationRuleTable.length > 0) {
            paginationRuleTable.css("top", headerRuleTable.offset().top - $(".formbody:first").offset().top + 5);
        }
        //$("#importmailaccountrules #pagination a").each(function () {
        //    var pageValue = parseInt($(this).data("page"));
        //    $(this).unbind("click");
        //    $(this).click(function () { loadRules(pageValue); });
        //});
        $("#importmailaccountrules table tr:first").before("<tr ><th  colspan = '8' style=\"text-align: center;\">" + ImportMailResources.Parameters + "</th><th  colspan = '5' style=\"text-align: center;\">" + ImportMailResources.Result + "</th></tr>");
    });
    return false;
}

function switchImportMailFields(type) {
    switch (type) {
        case 'task':
            $('#importproperties').show().find('select').addClass('required');
            $('#importproperties').find('label').addClass('required');
            $("label[for='createFromUnregUsers']").removeClass('required');
            $("label[for='createuser']").removeClass('required');
            $("label[for='createuserbycompany']").removeClass('required');
            $("label[for='notifyuser']").removeClass('required');
            if ($('#tasktypeid').find('option').length < 2) {
                $('#tasktypeid').parents('.field').hide();
                $('#labelfortasktypeid').removeClass('required');
                $('#tasktypeid').removeClass('required');
            }
            if (!$('#createFromUnregUsers').is(':checked')) {
                $("label[for='createuser']").hide();
                $('#createuser').removeAttr('checked');
                $('#createuserbycompany').removeAttr('checked');
                $('#notifyuser').removeAttr('checked');
                $('#FromUnregUsers').hide();//.find('select').removeClass('required').val('');
                removedefaultUser();
                $('#FromUnregUsers').find('label').removeClass('required');
                $('#automaticuser').hide().find('select').removeClass('required').val('');
                $('#automaticuser').find('label').removeClass('required');
            }
            $('#accounttype').html(ImportMailResources.TaskFromMailDescription);
            break;
        case 'comment':
            $('#importproperties').hide().find('select').removeClass('required').val('');
            $('#importproperties').find('label').removeClass('required');
            $('#createFromUnregUsers').attr('checked', false);
            $('#importproperties input[type="checkbox"]').attr('checked', false);
            $('#accounttype').html(ImportMailResources.TaskCommentFromMailDescription);
            break;
    }
}

function changePasswordClick() {
    $('#pwdplaceholder').hide(); $('.newpwd').show(); $('#password').add('#password2').attr('disabled', false);
    return false;
}

function verifyEmailServer() {
    $.getJSON(base + 'importmailaccount.ivp/VerifyEmailServer', {
        id: $('#id').val(),
        server: $('#server').val(),
        port: $('#port').val(),
        typeid: $('#typeid').val(),
        authorizationmode: $('#authorizationmode').val(),
        authenticationmode: $('#authenticationmode').val(),
        account: $('#account').val(),
        tenantId: $('#tenantId').val(),
        clientId: $('#clientId').val(),
        mail: $('#mail').val(),
        password: $('#password').val()
    }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            var verify = ImportMailResources.VerifyFailed + "<br>" + result.Description;
            $('#errorholder').empty().css("background-color", "#ffd8d8").css("border-color", "#fca6a6").html("<div id='mailerror'>" + verify + "</div>").show();
            $('#mailerror').css("height", $('#mailerror').height() + 20);
            return;
        }
        var verify = ImportMailResources.VerifySuccess + " ";
        verify += ImportMailResources.InMailbox + " " + result + " " + ImportMailResources.Messages;
        $('#errorholder').empty().css("background-color", "#e3ffd8").css("border-color", "#96e577").html("<div id='mailerror'>" + verify + "</div>").show();
        $('#mailerror').css("height", $('#mailerror').height() + 20);
    });
    return false;
}

function createRule() {
    var link = 'importmailaccountrule.ivp/create';
    getRule(link);
}

function viewRule(ruleId) {
    var link = 'importmailaccountrule.ivp/view/' + ruleId;
    getRule(link);
}

function getRule(link) {
    $("#dialog").load(base + link, { importmailaccountid: $("#id").val() }, function () {
        $("#dialog").dialog("option", "title", FormatString(ImportMailResources.CreateMailRule));

        $('#listCategoryPath').multipleSelect();
        //$('#CompanyIds').multipleSelect();

        $("input[type=radio]").css("margin-right", "5px");

        //если форма открыта на редактирование, подкючим плагин для работы с тегами
        if ($('#tid').length > 0) {
            //добавим класс 'selected' ко всем элементам скрытого списка уже существующих тегов
            //, т.к. мы должны их видеть в строке ввода 
            $('#tid > option').addClass('selected');

            //инициализация плагина
            $('#tid').fcbkcomplete({
                json_url: base + 'importmailaccountrule.ivp/findtags',
                complete_text: KBResources.TagFcbkCompleteMessage,
                maxitems: 100,
                newel: true
            });
        }

        $("#dialog").dialog("option", "minHeight", 550);
        $("#dialog").dialog("open");

        $('input[id$=All]').bind("change", function (e) {
            var div = $(this).closest("div");
            if (div.length) {
                var id = div.attr("id");
                if (id != undefined && id.toLowerCase() == 'listuserall') {
                    $("#listUserId option").removeAttr("selected");
                    $("ul[class='users']").html("");
                }
            }
        });

        $('input[id$=All]').bind("click", function (e) {
            var inputId = $(this).attr("name") + "Select";
            var block = $("#" + inputId).parent();
            var select = block.find("select");

            if (select.length) {
                var id = $(select).attr("id");
                var objs = $('input[id^=' + id + ']');
                var s = $(select).find("option");

                objs.removeAttr("checked");
                s.removeAttr("selected");

                var text = MultipleSelectResources.Choose;
                block.find("a:first").attr('title', text).html(text);
            }

        });

        $.validator.addMethod("validateService", function (value, element) {
            var result = Number($("#ServiceId").val()) > 0;

            return result;
        })

        $('#importmailaccountrule').validate({
            submitHandler: function (form) {
                form.submit();
            },
            ignore: "",
            rules: {
                ServiceId: {
                    required: true
                },
                addService: {
                    validateService: true
                }
            },
            messages: {
                addService: {
                    validateService: FormResources.FieldRequired
                }
            }
        });

        $.multipleSelect.initByClassName('.rulesmultipleselectsingle', { maxwidth: '300px', init: true, single: true });
        $.multipleSelect.initByClassName('.rulesmultipleselect', { maxwidth: '300px', init: true });
    });
}

function userFound(e, d) {
    var id = d[1];
    var name = d[0];
    $(e.target).val('');
    $("#chooseusers").html("");
    _selectUser(id, name);
}

function saveRule() {
    if ($('#importmailaccountrule').valid()) {
        $.ajax({
            type: "POST",
            url: "importmailaccountrule.ivp/save",
            data: $('#importmailaccountrule').serialize(),
            success: function () {
                dialogClose();
                loadRules();
            }
        });
    }

    return false;
}

function selectUsers() {
    var url = 'user.ivp/select?reset=true&tb_mode=forallservices&tb_serviceid=0';
    dlg = openDialog(url, 'all', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var uids = result["selectedIds"];
    var names = result["selectedNames"];
    usersSelected(uids, names);
};

function usersSelected(uids, names) {
    uids.forEach(function (id) {
        //var name = $("#listUserId option[value='" + id + "']").html();
        var name = names['id' + id];
        _selectUser(id, name);

    });

    $("#chooseusers").html("");
}

function _selectUser(id, name) {
    $("#listUserId option[value='" + id + "']").attr("selected", "selected");
    $("ul.users").append("<li class='changed' style='padding-left: 5px;'>" + name + "<span class='hover'> <a onclick='return deleteUser(this," + id + ");' href='#' ,title='HTMLHelper.Resource('Common.Delete')'> <img src='img/trash.gif' > </a></span></li>");

}

function deleteUser(a, id) {
    a = $(a);
    var del = !a.parents('li:first').hasClass('archive');
    $('select option[value="' + id + '"]', a.parents('div:first')).attr('selected', !del);
    if (del) a.parents('li:first').addClass('archive changed'); else a.parents('li:first').removeClass('archive changed');
    $("#listUserId option[value='" + id + "']").removeAttr("selected");

    return false;
}


function deleteRule() {
    var selected = $("#importmailaccountrules").find("tr.selected");
    if (selected.length == 0) { alert(ImportMailResources.NoRulesSelected); return false; }

    if (!confirm(ImportMailResources.SureDeleteRules + '(' + selected.length + ')?')) return false;
    var selectedRulesIds = selected.find(".rowid").map(function () {
        return $(this).val();
    }).get();

    try {
        $.ajax({
            type: "POST",
            url: "importmailaccountrule.ivp/delete",
            data: { ids: selectedRulesIds },
            success: function () {
                loadRules();
            }
        });
    } catch (e) {
        alert(e.message);
    }

    return false;
}

function dialogClose() {
    $("#dialog").dialog("close");
    $("#dialog").html("");
}

//function selectService()

var ImportMailAccount = {
    selectCompany: function selectCompany() {
        dlg = openDialog('company.ivp/selectlist?cbmode=ImportMailAccount', 'selectcompanies', { width: 900, height: 650 });
        dlg.callback = ImportMailAccount.companiesCallback;
        return false;
    },
    companiesCallback: function companiesCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        companySelected(ids, names);
    },
    selectdefaultUser: function selectdefaultUser() {
        var url = 'user.ivp/select?cbmode=ImportMailAccount&reset=true&tb_mode=all';
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = ImportMailAccount.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        defaultUserSelected(uids, names);
    }
}

var ImportMailAccountRule = {
    selectCategory: function selectCategory(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ImportMailAccountRule';

        dlg = openDialog(url, 'selectcompanies', { width: 990, height: 660 });
        dlg.callback = ImportMailAccountRule.categoriesCallback;
        return false;
    },
    categoriesCallback: function categoriesCallback(result) {
        var msName = result["msName"];
        addSelectedPaths(result, msName);
    },

    selectService: function selectService(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ImportMailAccountRule';
        url += '&selectmode=SINGLE';

        var selServicesPath = $("ul[selectid = 'ServicePath'] input");
        var selServicesId = new Array();
        for (i = 0; i < selServicesPath.length; i++) {
            var ids = $(selServicesPath[i]).val().split("|");
            selServicesId.push(ids[ids.length - 2]);
        }
        if (selServicesId.length > 0)
            sessionStorage.setItem('disabledServices', selServicesId);
        else
            sessionStorage.removeItem('disabledServices');

        dlg = openDialog(url, 'selectcompanies', { width: 900, height: 650 });
        dlg.callback = ImportMailAccountRule.servicesCallback;
        return false;
    },
    servicesCallback: function servicesCallback(result) {
        var msName = result['msName'];
        addSelectedSinglePath(result, msName);
    },

    selectTaskType: function selectTaskType(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ImportMailAccountRule';

        dlg = openDialog(url, 'selectcompanies', { width: 900, height: 650 });
        dlg.callback = ImportMailAccountRule.taskTypesCallback;
        return false;
    },
    taskTypesCallback: function taskTypesCallback(result) {
        var msName = result['msName'];
        addSelectedSingleValue(result, msName);
    },

    selectCreator: function selectCreator(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ImportMailAccountRule';
        url += '&selectmode=SINGLE';

        dlg = openDialog(url, 'selectcompanies', { width: 900, height: 650 });
        dlg.callback = ImportMailAccountRule.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var msName = result['msName'];
        addSelectedValues(result, msName);
    },

    selectCompany: function selectCompany(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ImportMailAccountRule';

        dlg = openDialog(url, 'selectcompanies', { width: 900, height: 650 });
        dlg.callback = ImportMailAccountRule.companiesCallback;
        return false;
    },
    companiesCallback: function companiesCallback(result) {
        var msName = result['msName'];
        addSelectedValues(result, msName);
    },

    selectSchedule: function selectSchedule(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ImportMailAccountRule';
        url += '&selectmode=SINGLE';

        dlg = openDialog(url, 'selectschedule', { width: 900, height: 650 });
        dlg.callback = ImportMailAccountRule.selectScheduleCallback;
        return false;
    },
    selectScheduleCallback: function selectScheduleCallback(result) {
        var msName = result['msName'];
        addSelectedSingleValue(result, msName);
        $('input[name="rschedule"][value="1"]').prop('checked', 'ckecked');
    },
}

function companySelected(ids, names) {
    var id = ids[0];
    var sn = names['id' + id];
    _companySelected(id, sn);
}

function _companySelected(id, name, canRemove) {
    removeCompany();
    $('#companyid').val(id).attr('changed', true);
    var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', '#').click(function () { return companyDetails(id); });
    $('#companyholder').append($ag);

    $('#companyholder').removeClass("removed");
}

function removeCompany() {
    $('#companyid').attr('changed', true).val('');
    $('#companyholder').empty();

    return false;
}

function companySelectedFromAutoComplete(e, d) {
    _companySelected(d[1], d[0], $('#readonly').length > 0);
    $('#addCompany').val('');
    return false;
}

function defaultUserSelected(ids, names) {
    var id = ids[0];
    var sn = names['id' + id];
    _defaultUserSelected(id, sn);
}

function _defaultUserSelected(id, name, canRemove) {
    removedefaultUser();
    $('#defaultuserid').val(id).attr('changed', true);
    $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }, function (hashid) {
        var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', '#').click(function () { return userDetails(hashid); });
        $('#defaultUserholder').append($ag);
        $('#defaultUserholder').append('<a href="#" onclick="return removedefaultUser();"><img src="img/trash.gif"></a>')
        $('#defaultUserholder').removeClass("removed");
    });

}

function removedefaultUser() {
    $('#defaultuserid').attr('changed', true).val('');
    $('#defaultUserholder').empty();

    return false;
}



function defaultUserSelectedFromAutoComplete(e, d) {
    _defaultUserSelected(d[1], d[0], $('#readonly').length > 0);
    $('#adddefaultUser').val('');
    $('label[for="adddefaultUser"]').remove();
    return false;
}