﻿function showPopup(popup_id) {

    if (popup_id == "tell-more-form-popup")
        showTellMoreForm();
    else
        showAuthPopup(popup_id);
}


function showAuthPopup(popup_id, focus_element_id) {

    $('#popup-darkening').fadeIn();
    $("#" + popup_id).css({
        "margin-left": $("#" + popup_id).width() < $(window).width() ? - $("#" + popup_id).width() / 2 : "0",
        "left": $("#" + popup_id).width() < $(window).width() ? "50%" : "0",
        "margin-top": $("#" + popup_id).height() < $(window).height() ? - $("#" + popup_id).height() / 2 : "0",
        "top": $("#" + popup_id).height() < $(window).height() ? "50%" : "0"
    });
    if ($(window).width() < $('#' + popup_id).width() || $(window).height() < $("#" + popup_id).height())
        $('#' + popup_id).css("position", "absolute");

    $('embed, object').css("visibility", "hidden");
    
    $('#' + popup_id).fadeIn();

    $(document.documentElement).unbind('keydown');
    $(document.documentElement).keydown(function (evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode == 27)
            hideAuthPopups();
    });

    if (focus_element_id != undefined)
        $('#' + focus_element_id, '#' + popup_id).focus();
    else
        if (popup_id == 'user-bind-form-popup')
            inst.userBindForm.focusElement();
        else if (popup_id == 'change-password-form-popup')
            $('#new-password').focus();
        else if (popup_id == 'confirm-email-form-popup')
            $('#email-confirm-code').focus();
}

function hideAuthPopups() {
    $('.popup-wrapper').hide();
    $('#user-bind-form').remove();

    $('embed, object').css("visibility", "visible");
    $('body').css('overflow', 'auto');

    $('#popup-darkening').fadeOut();
}

function openPopupWindow(url, width, height) {
    var leftVar = (screen.width - width) / 2;
    var topVar = (screen.height - height) / 2;
    var popup = window.open(url, "", 'width=' + width + ', height=' + height + ', top=' + topVar + ',left=' + leftVar + 'location = 0, status = 1, resizable = 0, scrollbars = 1, toolbar = 0');
}

function validate(container) {
    var validation_success = true;
    var existFocusedElement = false;
    $('.validate', container).each(function () {
        if ($(this).val() == "") {
            $(this).addClass("red-border");
            if(!existFocusedElement){
                $(this).focus();
                existFocusedElement = true;
            }
            validation_success = false;
        }
        else
            $(this).removeClass("red-border");
    });
    return validation_success;
}

function validateEmail(email) {
    if(email != ""){
        var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        return filter.test(email);
    }
    else
        return false;
}

function validateLogin(login) {
    if(login != "") {
        var filter = /^[A-Za-z0-9_]{5,16}$/;
        return filter.test(login);
    }
    else
        return false;
}

function validatePassword(password) {
    if (password.length > 4)
        return true;
    else
        return false;
}

function isEnterPressed(evt) { 

    evt = (evt) ? evt : event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    return charCode == 13;
}

function onPressKeyAuthorize(url, container, evt) {

    if(isEnterPressed(evt)) {
        authorize(url, container);
        return false;
    }
}

function authorize(url, container) {
    $('#myvi-login-error', container).hide();
    var validation_success = validate(container);
    if (validation_success) {
        
        $.ajax({
            url: url,
            type: "POST",
            async: false,
            data: "login=" + encodeURIComponent($('#login', container).val()) + "&password=" + encodeURIComponent($('#password', container).val()) + "&remember=" + ($('#remember-me-checkbox', container).attr('checked') == true || $('#remember-me-checkbox', container).attr('checked') == 'checked'),
            success: function (data, status, jqXHR) {
                var content_type = jqXHR.getResponseHeader("content-type");
                if (content_type != "application/x-javascript; charset=utf-8") {
                    var errorMessage = $('span[error-code="' + data + '"]', container + ' #myvi-login-error');
                    $(container + ' #myvi-login-error').children().hide();
                    $(errorMessage).show();
                    $(container + ' #myvi-login-error').show();
                }
                else
                    $('#login-form-popup').fadeOut();
            },
            error: function () {
                $(container + ' #myvi-login-error #unknown-login-error').show();
                $(container + ' #myvi-login-error').show();
            }
        });
    }
}

function confirmEmailOnKeypress(url, container, evt) {

    if (isEnterPressed(evt)) {
        confirmEmail(url, container);
        return false;
    }
}

function confirmEmail(url, container) {
    $('#reg-code-error').hide();
    var validation_success = validate(container);
    if (validation_success) {
        $.ajax({
            url: url + "?code=" + encodeURIComponent($('#email-confirm-code').val()),
            async: false,
            success: function (data, status, jqXHR) {
                var content_type = jqXHR.getResponseHeader("content-type");
                if (content_type != "application/x-javascript; charset=utf-8") {
                    var errorMessage = $('span[error-code="' + data + '"]', '#reg-code-error');
                    $('#reg-code-error').children().hide();
                    $(errorMessage).show();
                    $('#reg-code-error').show();
                }
                else
                    $('#confirm-email-form-popup').remove();
            },
            error: function () {
                $('#reg-code-error #unknown-error').show();
                $('#reg-code-error').show();
            }
        });
    }
}

function showForgotPasswordForm(url) {

    $.ajax({
        url: url,
        dataType: "html",
        async: false,
        success: function (data) {
            $('.popup-wrapper').hide();
            $('#user-bind-form').remove();
            $('#forgot-password-form-popup').html(data);
            $('#forgot-password-error').children().hide();
            $('#forgot-password-error').hide();
            showAuthPopup('forgot-password-form-popup', 'rp-login');
        }
    });
}

function sendRPMailOnKeyPress(url, container, evt) {

    if (isEnterPressed(evt)) {
        sendRecoveryPasswordMail(url, container);
        return false;
    }
}

function sendRecoveryPasswordMail(url, container) {

    var validation_success = validate(container);
    if (validation_success) {
        var login = $('#rp-login', container).val();
        var email = $('#rp-email', container).val();

        var isValidData = true;
        if (email != "")
            isValidData = validateEmail(email);
        if (isValidData) {

            $('#forgot-password-error').children().hide();
            $('#forgot-password-error').hide();
            $('input', container).attr("disabled", true);

            $.ajax({
                url: url,
                type: "POST",
                async: false,
                data: "login=" + encodeURIComponent(login) + "&email=" + encodeURIComponent(email),
                success: function (data) {
                    if (parseInt(data) == 0) {
                        $('#forgot-password-submit').attr("onclick", "");
                        $('#forgot-password-success').show();
                        setTimeout("hideAuthPopups()", 3000);
                    }
                    else {
                        $('#forgot-password-error').children().hide();
                        $('#forgot-password-error #unknown-error').show();
                        $('#forgot-password-error').show();
                        $('input', container).attr("disabled", false);    
                    }
                },
                error: function (data) {
                    $('#forgot-password-error').children().hide();
                    $('#forgot-password-error #unknown-error').show();
                    $('#forgot-password-error').show();
                    $('input', container).attr("disabled", false);  
                }
            });
        }
        else {
            $('#forgot-password-error').children().hide();
            $('#forgot-password-error #invalid-email-format').show();
            $('#forgot-password-error').show();
        }
    }
    else {
        $('#forgot-password-error').children().hide();
        $('#forgot-password-error').hide();
    }
}

function changePasswordOnKeyPress(url, container, evt) {

    if (isEnterPressed(evt)) {
        changePassword(url, container);
        return false;
    }
}

function changePassword(url, container) {

    var validation_success = validate(container);
    if (validation_success) {
        var new_password = $('#new-password', container).val();
        var new_password_confirm = $('#new-password-confirm', container).val();
        if (new_password == new_password_confirm) {

            $('#change-password-error').children().hide();
            $('#change-password-error').hide();
            $('input', container).attr("disabled", true);

            $.ajax({
                url: url,
                type: "POST",
                async: false,
                data: "new_password=" + encodeURIComponent(new_password) + "&password_confirm=" + encodeURIComponent(new_password_confirm),
                success: function (return_code) {
                    switch (parseInt(return_code)) {

                        case 10:
                            $('div#change-password-error').children().hide();
                            $('div#change-password-error #passwords-not-match').show();
                            $('div#change-password-error').show();
                            $('input', container).attr("disabled", false);
                            break;
                        case 11:
                            $('#change-password-form-popup').fadeOut();
                            showAuthPopup('forgot-password-form-popup', 'rp-login');
                            break;
                        case 100:
                            $('#change-password-submit').attr("onclick", "");
                            $('#change-password-success').show();
                            setTimeout("hideAuthPopups()", 3000);
                            break;
                    }
                },
                error: function () {
                    $('#change-password-form-popup').fadeOut();
                    $('#forgot-password-error').children().hide();
                    $('#forgot-password-error #bad-change-password-link').show();
                    $('#forgot-password-error').show();
                    $('#forgot-password-form-popup').fadeIn();
                    $('input', container).attr("disabled", false);
                }
            });
        }
        else {
            $('div#change-password-error').children().hide();
            $('div#change-password-error #passwords-not-match').show();
            $('div#change-password-error').show();             
        }
    }
    else {
        $('div#change-password-error').children().hide();
        $('div#change-password-error').hide();
    }
}

function showRegistrationForm(url) {

    $.ajax({
        url: url,
        success: function (data) {
            $('#registration-form-popup').html(data);
            showAuthPopup('registration-form-popup', 'reg-email');
        }
    });
}

function showTellMoreForm() {

    $.ajax({
        url: "/registration/ShowTellMoreForm",
        success: function (data) {
            $('#tell-more-form-popup').html(data);
            setTimeout(function () {showAuthPopup('tell-more-form-popup', 'first-name')}, 150);
        }
    });
}

