﻿Attempts = 0;
Un_pw = "";
LockedMsg = "Sorry, but for security reasons you have been locked out of this website for the next 30 minutes, after which you can try again.<br/>" +
                        "Please use our <a href='/Login/ForgotPassword.aspx'>Forgotten Password Service</a> or " +
                        "contact the Support Centre for further assistance.";
OnLogin = false;
ChangePassword = false;
NewPwd = null;

$(document).ready(function() {

});

function Login() {
    result = false;
    var postURL = "/LLL/WebService/ConsultantLogin.asmx/Login";
    var data = {};
    data["name"] = $("#username").val();
    data["password"] = $("#password").val();
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: $.toJSON(data),
        url: postURL,
        success: function(json) {
            resObject = $.evalJSON(json.d);
            result = resObject.LoginOkay;
            if ($("#rememberMe:checked").length) {
                var expDate = new Date();
                expDate.setDate(expDate.getDate() + 60);
                $.cookies.set('cons_log_pw', $('#password').val(), { expiresAt: expDate });
                $.cookies.set('cons_log_un', $('#username').val(), { expiresAt: expDate });
            } else {
                $.cookies.del('cons_log_pw');
                $.cookies.del('cons_log_un');
            }
            if (!result) {
                if (OnLogin) {
                    ++Attempts;
                }
                if (Attempts > 2) {
                    var msg = "You have 1 more attempt to successfully login.<br/>" +
                        "Please use our <a href='/Login/ForgotPassword.aspx'>Forgotten Password Service</a> to " +
                        "have your details sent to the email address you used at registration.";
                    SetValidationMsg("login", msg);
                } else {
                    SetValidationMsg("login", 'Incorrect username or password.');
                }

                if (Attempts > 3) {
                    var expDate = new Date();
                    expDate.setMinutes(expDate.getMinutes() + 30);
                    $.cookies.set('cons_log_locked', true, { expiresAt: expDate });
                    Attempts = 0;
                }
            } else {
                if (resObject.ChangeRequired) {
                    ChangePassword = true;
                }
            }
        }
    });
    return result;
}

function DoPassword() {
    $('#dChangePassword').show(600);
    $('#newPassword').focus();
    $('#username, #password, #rememberMe').attr('disabled', 'disabled').addClass('disabled');
    $('#bSubmit').val('Change password');

    $('#newPassword').rules("add", { required: true, minlength: 8 });
    $('#newPasswordConfirm').rules("add", { required: true, equalTo: '#newPassword', checkPassword: true });

}

function CheckPassword() {
    pwdResult = false;
    var postURL = "/LLL/WebService/ConsultantLogin.asmx/CheckPassword";
    var data = {};
    data["name"] = $("#username").val();
    data["old"] = $("#password").val();
    data["password"] = $("#newPassword").val();
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: $.toJSON(data),
        url: postURL,
        success: function(json) {
            pwdResult = $.evalJSON(json.d);
            if (pwdResult) {
                ChangePassword = false;
                NewPwd = $('#newPassword').val();
                var expDate = new Date();
                expDate.setDate(expDate.getDate() + 60);
                $.cookies.set('cons_log_pw', $('#newPassword').val(), { expiresAt: expDate });
                $.cookies.set('cons_log_un', $('#username').val(), { expiresAt: expDate });
            }
        }
    });
    return pwdResult;
}

function OnLoginLoad() {
    $.validator.addMethod('locked',
        function(value) {
            if (!value.length || !$("#password").val().length) {
                return true;
            }
            var locked = $.cookies.get('cons_log_locked');
            if (locked != null) {
                Attempts = 0;
            }
            return locked == null;
        }, LockedMsg
    );
    $.validator.addMethod('login',
        function(value) {
            if (!value.length || !$("#password").val().length) {
                return true;
            }
            return Login();
        },
        'Incorrect username or password.'
    );
    $.validator.addMethod('checkPassword',
        function(value) {
            if (!value.length || !$("#newPassword").val().length) {
                return true;
            }
            return CheckPassword();
        },
        'Password should be new, have at least 1 letter, <br/>1 digit and may have some special symbols.'
    );

    $("#aspnetForm").validate();

    $("#bSubmit").click(function() {
        OnLogin = true;
        var ok = $("#aspnetForm").valid();
        if (ok) {
            if (ChangePassword) {
                DoPassword();
            } else {
                $("#UserID").val($("#username").val());
                $("#Passwd").val($("#password").val());
                if (NewPwd != null) {
                    $("#Passwd").val(NewPwd);
                }
                $("#login").submit();
            }
        }
        OnLogin = false;
    });

    $("#content input").clickbutton("#bSubmit");
    $("#username").focus();

    var pw = null;
    var un = null;
    try {
        pw = $.cookies.get('cons_log_pw');
        un = $.cookies.get('cons_log_un');
    } catch (e) { };
    if (pw != null && un != null) {
        $('#password').val(pw);
        $('#username').val(un);
        $("#rememberMe").val(["y"]);
    } else {
        $('#password, #username').val("");
    }
}
