var strongPassword = 0;

var passwordPolicy = {
    Length: 1,
    Letters: 2,
    Caps: 4,
    Digits: 8,
    Special: 16
}

var ethalonWeight = passwordPolicy.Special | passwordPolicy.Digits | passwordPolicy.Caps | passwordPolicy.Letters | passwordPolicy.Length;

strongPassword = $('#strongPassword').val();

$(function () {
    'use strict';

    var App = {

        init: function () {

            this.StateEnum = {
                NewUserAndComany: 0, // Новый пользователь, новая компания
                NewUserInCompany: 1, // Новый пользователь в имеющейся компании                
                ExistUserAndCompany: 2, // Имеющийся пользователь в имеющейся компании
                ByAsset: 3 // Актив
            };

            this.cacheElements();
            this.bindEvents();
        },

        cacheElements: function () {
            this.$dialog = $('<div class="js-create-user-dialog"></div>');
            this.$body = $('body');
            this.$body.append(this.$dialog);

            this.$taskServiceId = $('#serviceid');
            this.serviceId = this.$taskServiceId.val();

            this.$taskServiceName = $('#taskservicename');
            this.defaultTaskService = {
                name: this.$taskServiceName.text(),
                value: this.serviceId
            };

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

            this.taskId = parseFloat($id.val());
        },

        bindEvents: function () {

            $(document).ready(function () {
                var $isError = $('#iserror');
                var isError = $('#iserror').length > 0 && $isError.val() === 'True';
                if (this.taskId <= 0 && !isError) {
                    this.showCreateUserDialog();
                }

            }.bind(this));

            this.$body.on('click', '.js-close-create-user-dialog', this.destroy.bind(this));

            this.$body.on('click', '.js-save-and-continue', this.saveAndContinue.bind(this));

            this.$body.on('click', '.js-create-user-dialog-toggle', this.toggleLogin.bind(this));

            this.$body.on('click', 'button.js-save-and-send-userdata', function (e) {
                $('#sendpassword').val('True');
                this.$form.submit();
            }.bind(this));
        },

        //#region Методы

        showGetUserSendTemplate: function (userId, userPassword) {

            $.ajax({
                url: 'UserInput/GetUserNotificationTemplate',
                data: { userId: userId, password: userPassword },
                success: function (data, textStatus, jqXhr) {

                    this.$dialog.append(data);

                    var title = this.$dialog.find('.formbody').attr('data-title');

                    var $dialog = this.$dialog.dialog({
                        autoOpen: true,
                        open: function () {
                            this.$dialog.find('.js-close-sendnotification').on('click', function () { this.destroy(); }.bind(this));
                            var $form = this.$dialog.find('form.js-notification-user-form');

                            $form.ajaxForm({

                                beforeSubmit: function () {
                                    var isValid = $form.validate().valid();
                                    return isValid;
                                },

                                success: function (json) {
                                    if (json.IsOk) {
                                        this.destroy();
                                    } else {
                                        alert(json.Description);
                                    }

                                }.bind(this)
                            });

                        }.bind(this),
                        width: '720px',
                        maxWidth: screen.width - 25,
                        modal: true,
                        position: { my: "center" },
                        resizable: false,
                        close: this.destroy.bind(this),
                        closeOnEscape: false,
                        title: title
                    });

                }.bind(this)
            });
        },

        setCreator: function (userId, userName) {

            //меняем сервис только когда нашли пользователя или компанию
            if (this.State != this.StateEnum.NewUserAndComany) {
                this.$taskServiceId.val(this.$serviceTaskId.val());
                var nTaskServiceName = this.$serviceTaskId.find('option:selected').text();
                this.$taskServiceName.text(nTaskServiceName).attr('title', nTaskServiceName);
            }

            $('#creatorid').val(userId).attr('changed', true);

            var $ul = $('#taskform #creator ul.users').empty();

            $ul.append($('<li>' + userName + '</li>'));

            // Устанавливаем автоназначенные на заявителя группы
            $.ajax({
                type: 'POST',
                url: 'Task/GetExecutorGroupByCreator',
                dataType: 'json',
                data: { creatorId: userId, serviceId: this.$taskServiceId.val(), taskId: $('#id').val(), statusId: $('#statusid').val(), typeId: $('#typeId').val() },

                success: function (json) {
                    if (json && json.Data) {

                        if (json.Data.hasOwnProperty('Name') && json.Data.hasOwnProperty('Id')) {
                            _executorGroupsSelected(json.Data.Id, json.Data.Name);

                            if (json.Data.Observers.length > 0) {
                                var observersData = { DeleteObservers: false, Observers: json.Data.Observers };
                                updateObserversOnStatusChange(undefined, observersData);
                            }

                            $('#taskform a').removeClass('changed');
                            $('#taskform li').removeClass('changed');
                        }
                    }
                }
            });

            // автоназначение и тд по новому сервису
            if (this.defaultTaskService.value != this.$serviceTaskId.val()) {
                updateTaskOnStatusChange();
                getWorkflowAndSLA(null, 'Service');
            }

            this.destroy();

            var $name = $('#name');
            if ($name.length)
                $name.focus();
        },

        initAjaxForm: function () {

            this.$form.ajaxForm({

                beforeSubmit: function (arr, $form, options) {

                    //Валидация формы
                    if (!$form.valid()) {
                        return false;
                    } else {

                        if (this.State != this.StateEnum.ExistUserAndCompany) {

                            var $sendPassword = $('#sendpassword');

                            if ($sendPassword.val() === 'True') {

                                var $userEmail = $('#useremail');
                                var email = $userEmail.val();
                                if (!$.trim(email).length) {
                                    alert(UserInputResources.EmailErrorMessage);
                                    return false;
                                }
                            }
                        }
                    }
                }.bind(this),

                success: function (json) {

                    if (json.IsOk) {
                        var userId = json.Data.Id;
                        var userName = json.Data.Name;
                        this.setCreator(userId, userName);

                        if (json.Data.hasOwnProperty('UserPassword') && this.State != this.StateEnum.ExistUserAndCompany) {
                            this.showGetUserSendTemplate(userId, json.Data.UserPassword);
                        }

                    } else {
                        alert(json.Description);
                    }

                }.bind(this)
            });
        },

        toggleLogin: function (e, forceShow) {
            var $self = $(e.currentTarget);
            var min = $self.attr('data-minimize');
            var max = $self.attr('data-max');
            var $target = $($self.attr('data-target'));

            if (forceShow) {
                if (forceShow) {
                    if (!$target.is(':visible')) {
                        $self.text(min);
                        $target.show();
                    }
                }
            }
            else {
                if ($target.is(':visible')) {
                    $self.text(max);
                } else {
                    $self.text(min);
                }

                $target.toggle();
            }

            return false;
        },

        saveAndContinue: function (e) {

            if (!this.$form.valid())
                return false;

            $('#sendpassword').val('False');

            //var userId = parseFloat(this.$userId.val());
            //var userName = this.$dialog.find('#username').val();

            //if (userId) {//Если пользователь был выбран
            //    this.setCreator(userId, userName);
            //} else {
            //    this.$form.submit();
            //}

            // теперь всегда запрос, т.к. возможно нужно обновить поля
            this.$form.submit();
            if (this.$assetId && this.$assetId.val()) {
                this.addAssetOnTask(this.$assetId.val(), this.$dialog.find('#assetname').val());
            }
            
            return false;
        },
        addAssetOnTask: function(id, name){
            var wrapper = $('#assets');
            var ul = wrapper.find('ul:first');
            var select = wrapper.find('select:first');
            if (!select)
                return;
            formchanged = true;
            if ($('option[value="' + id + '"]', select).length > 0) return;

            select.append('<option selected value="' + id + '">' + name + '</option>');
            var html;
            html = '<li data-id="' + id + '" class="changed">' + name;
            html += '<span class="hover"><a href="#"><img src="img/trash.gif" /></a></span></li>';
            ul.append(html).show();
            ul.find('.empty').hide();

            $('li:last span.hover a', ul).click(function () {
                var a = $(this);
                a.parents('li.changed').remove();
                if (ul.children().length == 0)
                    $('#tal').addClass('middle');
                $('option[value="' + id + '"]', select).remove();

               // getWorkflowAndSLA(null, 'AssetType');
                $('#addasset').valid();
                $('#assetids').trigger('change');
                return false;
            });
        },
        destroy: function () {
            this.$dialog.dialog("destroy").empty();
        },

        showCreateUserDialog: function () {

            $.ajax({
                url: 'UserInput/GetCreateUserDialog',
                data: { serviceId: this.serviceId },
                success: function (data, textStatus, jqXhr) {
                    var $dialog = this.$dialog.dialog({
                        autoOpen: false,
                        open: this.initDialog.bind(this),
                        width: 'auto',
                        maxWidth: ((screen.width - 25) < 1080 ? (screen.width - 25) : 1080),
                        minWidth:675,
                        modal: true,
                        position: { my: "center bottom" },
                        resizable: false,
                        close: this.destroy.bind(this),
                        closeOnEscape: false,
                        title: UserInputResources.DialogTitle
                    });

                    $dialog.append(data);

                    $dialog.dialog('open');

                }.bind(this)
            });
        },

        initDialog: function () {

            this.$dialog.find('#username')
            .devbridgeAutocomplete({
                serviceUrl: 'UserInput/FindUsers/' + this.serviceId,               
                minChars: 1,
                preserveInput: false,
                onSelect: this.selectUser.bind(this),
                params: function () {
                    var p = {};
                    if (this.State == this.StateEnum.NewUserInCompany) {
                        p = $.extend({}, p, { companyId: this.$usercompanyid.val()});
                    }
                    else if (this.State == this.StateEnum.NewUserAndComany) {
                        
                    }
                    return p;
                }.bind(this)
            });

            this.$dialog.find('#newusercompanyname')
             .devbridgeAutocomplete({
                 serviceUrl: 'UserInput/FindUserCompany/',                 
                 minChars: 1,
                 preserveInput: false,
                 onSelect: this.selectUserCompany.bind(this)
             });

            this.$assetId = this.$dialog.find('#assetid');
            this.$assetName = this.$dialog.find('#assetname');

            this.$assetName
             .devbridgeAutocomplete({
                 serviceUrl: 'UserInput/FindAssetsForDialog/',
                 minChars: 1,
                 preserveInput: false,
                 onSelect: this.selectAsset.bind(this)
             });

            this.$body.on('click', 'a.js-clear-create-user-dialog', this.clearDialog.bind(this));
            this.$body.on('click', '.js-create-user-dialog-clear-company', this.clearUserCompany.bind(this));
            this.$body.on('click', '.js-create-user-dialog-clear-asset', this.clearAsset.bind(this));

            this.$saveAndContinue = $('.js-save-and-continue');
            this.$toggleLoginData = $('a.js-create-user-dialog-toggle');
            this.$userLogin = this.$dialog.find('#userlogin');
            this.$userPassword = this.$dialog.find('#userpassword');
            this.$confirmPassword = this.$dialog.find('#userpassword2');
            this.$usercompanyid = this.$dialog.find('#usercompanyid');
            this.$userRoleId = this.$dialog.find('#userroleid');
            this.$serviceTaskId = this.$dialog.find('#servicetaskid');
            this.$userId = this.$dialog.find('#userinputid');

            this.$form = this.$dialog.find('.js-create-user-form');

            this.initAjaxForm();

            $('#serviceids').multiselect({
                minWidth: 624,
                noneSelectedText: UserInputResources.Services,
                selectedText: UserInputResources.SelectedText,
                header: UserInputResources.Services + ':'
            }).multiselectfilter({
                label: UserInputResources.Search,
                placeholder: ''
            });

            this.$dialog.find('#useremail').blur(function (e) {
                var $self = $(e.currentTarget);
                this.$userLogin.val($self.val());

            }.bind(this));

            var appThis = this;
            // валидация + скрытые доп. поля
            this.$form.validate({
                ignore: '',
                rules: {
                    userpassword2: {
                        equalTo: "#userpassword"
                    }
                },
                showErrors: function (errorMap, errorList) {
                    
                    if (this.numberOfInvalids() > 0)
                    {
                        $.each(errorMap, function (i, v) {
                            if (i.lastIndexOf('field', 0) === 0) {
                                appThis.$body.find('.js-create-user-dialog-toggle').trigger('click',true);
                                return false;
                            }
                        })
                    }

                    this.defaultShowErrors();
                }
            });
            

            $.validator.addMethod("validatePasswordStrength", function (value, element) {
                var result = validatePasswordStrength($("#userpassword").val());

                return result;
            });

            if (strongPassword == 1) {
                $("#userpassword").rules("add", {
                    validatePasswordStrength: true,
                    messages: {
                        validatePasswordStrength: UserResources.PasswordTooWeak
                    }
                });

                $("#userpassword").keyup(function () {
                    var weight = getPasswordWeight($("#userpassword").val());

                    if (weight & passwordPolicy.Special) {
                        $('#special').removeClass('invalid').addClass('valid');
                    } else {
                        $('#special').removeClass('valid').addClass('invalid');
                    }

                    if (weight & passwordPolicy.Digits) {
                        $('#digits').removeClass('invalid').addClass('valid');
                    } else {
                        $('#digits').removeClass('valid').addClass('invalid');
                    }

                    if (weight & passwordPolicy.Caps) {
                        $('#caps').removeClass('invalid').addClass('valid');
                    } else {
                        $('#caps').removeClass('valid').addClass('invalid');
                    }

                    if (weight & passwordPolicy.Letters) {
                        $('#letters').removeClass('invalid').addClass('valid');
                    } else {
                        $('#letters').removeClass('valid').addClass('invalid');
                    }

                    if (weight & passwordPolicy.Length) {
                        $('#length').removeClass('invalid').addClass('valid');
                    } else {
                        $('#length').removeClass('valid').addClass('invalid');
                    }
                }).focus(function () {
                    $('#pswd_info').show();
                }).blur(function () {
                    $('#pswd_info').hide();
                })
            }

            this.$serviceTaskId.change(function () {
                if (this.State == this.StateEnum.ExistUserAndCompany) {
                    var req = $.get('UserInput/GetActualUserRoleOnService', { userId: this.$userId.val(), serviceId: this.$serviceTaskId.val() });
                    req.done(function (data) {
                        if (data) {
                            var $roleId = $('#userroleid');
                            var $roleOption = $roleId.find('option[value="' + data.RoleId + '"]');
                            if (!$roleOption.length)
                                $roleId.append($('<option value="' + data.RoleId + '">' + data.RoleName + '</option>'));
                            $roleId.val(data.RoleId);

                            this.$dialog.find('input[name="userroleid"]').val(data.RoleId);
                        }
                    }.bind(this)).fail(function (data) {
                        //console.log('fail', data);
                    });
                }
            }.bind(this));

            this.$userRoleId.change(function () {

                this.$dialog.find('input[name="userroleid"]').val(this.$userRoleId.val());

            }.bind(this));

            this.setState(this.StateEnum.NewUserAndComany);

        },

        selectUser: function (suggestion) {

            var id = suggestion.data.id;

            this.$userId.val(id);
            this.$dialog.find('button.js-save-and-send-userdata').attr('disabled', 'disabled');

            //promise, т.к. запросы асинхронны, а нужна последовательность при работе с инпутами
            var req = this.intSelectedUserFields(id);
            req.done(function () {
                this.setState(this.StateEnum.ExistUserAndCompany);
            }.bind(this));
            req.fail(function () {
                this.setState(this.StateEnum.NewUserAndComany);
            }.bind(this));
        },

        selectUserCompany: function (suggestion) {

            var name = suggestion.value;
            var id = suggestion.data.id;
            var $companyName = this.$dialog.find('#newusercompanyname');
            this.$dialog.find('#usercompanyid').val(id);

            $companyName.val(name).attr('disabled', 'disabled');
            this.$dialog.find('.js-create-user-dialog-clear-company').show();

            this.setState(this.StateEnum.NewUserInCompany);
        },

        selectAsset: function(suggestion) {
            this.$assetName.attr('disabled', 'disabled');
            this.$dialog.find('.js-create-user-dialog-clear-asset').show();
            
            var ownerId = suggestion.data.ownerId;
            var ownerName = suggestion.data.ownerName;
            var assetId = suggestion.data.id;

            this.$assetId.val(assetId);
            this.$dialog.find('#username').val(ownerName);
            this.$userId.val(ownerId);
            this.$dialog.find('button.js-save-and-send-userdata').attr('disabled', 'disabled');

            //promise, т.к. запросы асинхронны, а нужна последовательность при работе с инпутами
            var req = this.intSelectedUserFields(ownerId);
            req.done(function () {
                this.setState(this.StateEnum.ExistUserAndCompany);
            }.bind(this));
            req.fail(function (data) {
                alert(CommonResources.Error + ': GetUserData');
                this.setState(this.StateEnum.NewUserAndComany);
            }.bind(this));            
        },

        intSelectedUserFields: function (userId) {

            var req = $.ajax({
                dataType: "json",
                url: 'UserInput/GetUserData',
                data: { id: userId, serviceId: this.serviceId },
                success: function (json) {

                    if (json) {

                        if (json.FieldValues) {//Инициализация дополнительных полей
                            for (var key in json.FieldValues) {
                                var id = '#field' + key;
                                var $field = $(id);

                                // браузер запрещает вставлять значение в инпут с типом файл
                                if ($field.length && $field.prop('type') !='file')
                                    $field.val(json.FieldValues[key]);
                            }
                        }

                        var $email = $('#useremail');
                        var $mobilePhone = $('#usermobilephone');
                        var $phone = $('#userphone');
                        var $comment = $('#usercomments');

                        $email.val(json.Email);
                        $mobilePhone.val(json.MobilePhone);
                        $phone.val(json.Phone);
                        $comment.val(json.Comment);

                        var $roleId = $('#userroleid');

                        this.$usercompanyid.val(json.CompanyId);
                        $('#newusercompanyname').val(json.CompanyFullName);
                        var $roleOption = $roleId.find('option[value="' + json.RoleId + '"]');
                        if (!$roleOption.length)
                            $roleId.append($('<option value="' + json.RoleId + '">' + json.RoleName + '</option>'));
                        $roleId.val(json.RoleId);

                        var $login = $('#userlogin').val(json.Login);
                        var $position = $('#userposition').val(json.Position);
                        var $timezone = $('#usertimezone').val(json.TimeZone);
                        var $currentlanguage = $('#usercurrentlanguage').val(json.CurrentLanguage);

                        this.disableFormField();

                        $('a.js-clear-create-user-dialog').show();
                        this.$saveAndContinue.removeAttr('disabled').focus();
                    }
                }.bind(this)
            });

            return req;
        },

        disableFormField: function () {

            //какие поля не нужно отключать
            var excludeNames = ['usermobilephone', 'userphone', 'usercomments', 'userposition', 'servicetaskid'];

            this.$dialog.find('button.js-save-and-send-userdata, textarea, select, input[type="text"],input[type="password"], input[type="chekbox"]')
                .filter(function () {
                    for (var i = 0; i < excludeNames.length; i++)
                        if (excludeNames[i] == this.name)
                            return false;
                    return true;
                })
                .attr('disabled', 'disabled');

            this.$dialog.find('#serviceids').multiselect('disable');
            this.$dialog.find('.js-create-user-dialog-clear-company').hide();
        },

        enableFormField: function () {
            this.$dialog.find('button.js-save-and-send-userdata, textarea, select, input[type="text"],input[type="password"], input[type="chekbox"]').removeAttr('disabled');

            this.$dialog.find('#serviceids').multiselect('enable');
        },

        clearDialog: function () {
            this.enableFormField();
            this.$dialog.find('button.js-save-and-send-userdata, textarea, select, input[type="text"], input[type="chekbox"]').val('');
            this.$userId.val('');
            this.$assetName.val('').removeAttr('disabled');
            this.$assetId.val('');
            $('a.js-clear-create-user-dialog').hide();
            this.$dialog.find('.js-create-user-dialog-clear-asset').hide();
            this.setState(this.StateEnum.NewUserAndComany);
        },

        clearUserCompany: function () {
            this.State = this.StateEnum.NewUserAndComany;
            this.$dialog.find('.js-create-user-dialog-clear-company').hide();
            this.$dialog.find('#newusercompanyname').val('').removeAttr('disabled');
            this.$usercompanyid.val(0);

            this.setState(this.StateEnum.NewUserAndComany);
        },

        clearAsset: function(){
            this.clearDialog();
            
        },

        setState: function(state){
            this.OldState = this.State;
            this.State = state;

            this.$dialog.find('#state').val(state);

            if (this.State == this.StateEnum.NewUserAndComany) {
                // нужно вернуть сервис заявки в начальное состояние
                this.$taskServiceId.val(this.defaultTaskService.value);
                this.$taskServiceName.text(this.defaultTaskService.name).attr('title', this.defaultTaskService.name);

                // создаем нового в дефолтном сервисе заявки
                this.$serviceTaskId.html('<option value="' + this.defaultTaskService.value + '">' + this.defaultTaskService.name + '</option>');

                this.showServiceTaskId(false);
                return;
            }

            var data = { state: this.State, typeId: $('#typeid').val() };

            if (this.State == this.StateEnum.NewUserInCompany) {
                data = $.extend({}, data, { companyId: this.$usercompanyid.val() })
            }
            else if (this.State == this.StateEnum.ExistUserAndCompany) {
                data = $.extend({}, data, { userId: this.$userId.val(), assetId: this.$assetId.val() });
            }

            var request = $.ajax({
                url: 'UserInput/LoadTaskServices',
                data: data
            });

            request.done(function (response, textStatus, jqXHR) {

                this.$serviceTaskId.html('');
                //if (response.length > 1) {
                //    this.$serviceTaskId.append('<option></option>');
                //}

                // создаем нового в дефолтном сервисе заявки
                this.$serviceTaskId.html('<option value="' + this.defaultTaskService.value + '">' + this.defaultTaskService.name + '</option>');

                $.each(response, function (i, v) {
                    // с сервера может подгрузиться дубль
                    if (v.value != this.defaultTaskService.value) {
                        this.$serviceTaskId.append('<option value="' + v.value + '">' + v.text + '</option>');
                    }
                }.bind(this));

                this.$serviceTaskId.trigger('change');

                this.showServiceTaskId(true);

            }.bind(this));

            request.fail(function (jqXHR, textStatus, errorThrown) {
                alert(CommonResources.Error + ': ' + errorThrown);
            });

        },

        showServiceTaskId: function (val) {
            if (val) {
                this.$serviceTaskId.addClass('required');
                //this.$serviceTaskId.removeAttr('disabled');
                this.$serviceTaskId.closest('.row').show();
            }
            else {
                this.$serviceTaskId.removeClass('required');
                //this.$serviceTaskId.attr('disabled', 'disabled');
                this.$serviceTaskId.closest('.row').hide();
            }
        }

        //#endregion
    };

    App.init();    
});

function bindPwEvents() {
    $("#pass").keyup(function () {
        var weight = getPasswordWeight($("#pass").val());

        if (weight & passwordPolicy.Special) {
            $('#pwspecial').removeClass('invalid').addClass('valid');
        } else {
            $('#pwspecial').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Digits) {
            $('#pwdigits').removeClass('invalid').addClass('valid');
        } else {
            $('#pwdigits').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Caps) {
            $('#pwcaps').removeClass('invalid').addClass('valid');
        } else {
            $('#pwcaps').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Letters) {
            $('#pwletters').removeClass('invalid').addClass('valid');
        } else {
            $('#pwletters').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Length) {
            $('#pwlength').removeClass('invalid').addClass('valid');
        } else {
            $('#pwlength').removeClass('valid').addClass('invalid');
        }
    });
}

function getPasswordWeight(password) {
    var weight = 0;

    $.ajax({
        type: 'POST',
        url: base + "login.ivp/getpasswordweightajax",
        data: { password: password },
        async: false,
        dataType: "json",
        success: function (result) {
            weight = ((result.hasOwnProperty('IsOK') && result.IsOK)) ? Number(result.Result) : 0;
        }
    });

    return weight;
}

function validatePasswordStrength(password) {
    var isValid = 0;

    $.ajax({
        type: 'POST',
        url: base + "login.ivp/validatepasswordstrengthajax",
        data: { password: password },
        async: false,
        dataType: "json",
        success: function (result) {
            isValid = ((result.hasOwnProperty('IsOK') && result.IsOK)) ? result.Result == "TRUE" : false;
        }
    });

    return isValid;
}