var timer = null;
var show_error = function(message) {
    $("#confirm").append("<span id='confirm_error'>" + message + "</span>");
    timer = setTimeout(function(){
        $("#confirm_error").hide(500);
        $("#confirm_error").remove();
    }, 5000);
}

var register = function() {

    var email = $("#email").val();
    var password = $("#password").val();
    var password_repeat = $("#confirmation").val();
    var promo_code = $('#promo_code').val();
    var terms_agree = $('input[name="terms_agree"]').is(':checked');
    
    if ( timer )   {
        clearTimeout( timer);
        timer = null;
    }

    $('#confirm_error').remove();

    if (password != password_repeat) {
        show_error("Passwords don't match each other");
        return;
    }
    if(password.length<6){
        show_error("Password is to short(min of 6 characters)");
        return;
    }
    
    if(!terms_agree){
        show_error("You must read and agree Terms & Conditions");
        return;
    }
    //console.log("login="+login+" email="+email+" password="+password+" confirm_password="+password_repeat);

  
    $.ajax({
        type: "POST",
        url: "/ajax/register/",
        data: ({
            'password': password,
            'email' : email,
            'promo_code' : promo_code,
            'terms_agree' : terms_agree
        }),
        success: function(response) {
            response =$.parseJSON( response );
            if ( response && response.code && response.code > 0 ) { // success 
                var event = jQuery.Event("userLogin");
                event.uid = response.code;
                $(document).trigger(event);
                
                return;
            }

            if(! response || ! response.code ) {
                response = { code : 0 };
            }

            var msg = '';
            switch ( response.code ) {
                case -2: 
                case -1: msg = "Email Already registered"; break;
                case -6: msg = "Invalid Email Address"; break;
                case -4: msg = "Password is too short ( required at least 6 characters ) "; break;
                case -17: msg = "Provided promotion code isn't valid"; break;
                default: msg = "Unkown server error. Please try again later "; break;
            }

            show_error(msg);
        }

    });
}

// moved from subscriptions.html
function loginUser() {
    $("#l_password, #l_email").attr('disabled', 'disabled');
    $.ajax({
        type: "POST",
        url: "/ajax/login/?nocache=" + Math.random(),
        cache: false,
        data: ({password: $("#l_password").val(), email:$("#l_email").val()}),
        success: function(response) {
        	$("#l_password, #l_email").removeAttr('disabled');
            response = $.parseJSON( response );
            console.log(response);
            if ( response && response.uid && response.uid > 0 ) {
                var event = jQuery.Event("userLogin");
                event.uid = response.uid;
                $(document).trigger(event);
            } else {
                showLoginErrorMessage();
            }
        }
    });
}

function showLoginErrorMessage()
{
    $("#l_confirm").html("<div id='l_confirm_error'>User not found</div>");
    timer = setTimeout(function(){
        $("#l_confirm_error").hide(500);
        $("#l_confirm_error").remove();
    }, 5000);
}

passwd = function() {
    var password = $('#password').val();
    var new_password1 = $('#new_password1').val();
    var new_password2 = $('#new_password2').val();

    if ( timer )   {
        clearTimeout( timer);
        timer = null;
    }

    $('#confirm_error').remove();

    if(password.length == 0) {
        show_error('Please enter your current password');
        return;
    }

    if(new_password1.length < 6) {
        show_error("Password is to short(min of 6 characters)");
        return;
    }

    if(new_password1 != new_password2) {
        show_error("Passwords don't match each other");
        return;
    }
    
    $("#password, #new_password1, #new_password2").attr('disabled', 'disabled');
    $.ajax({
        type: "POST",
        url: "/my/passwd/",
        cache: false,
        data: ({password: password, new_password:new_password1}),
        success: function(response) {
            $("#password, #new_password1, #new_password2").removeAttr('disabled');
            if ( response && response.code && response.code > 0 ) {
                $('#passwd').html('<div style="text-align:center;font-size:16pt;padding-top: 30px">Password is sucessfully changed.</div>');
                return;
            }

            if(response && response.message) {
                show_error(response.message);
            }
        },
        error: function(jqXHR) {
            show_error('Internal error. Please, try again later.');
        }
        
    });
}

$(document).ready(function() {
    $('.toggle-button').click(function(e) {
        e.stopPropagation();

        $('.login-form, .registration-form').toggle();
    });
});
