$(document).ready(function (){
    $('#login_btn').click(function(event){
        event.preventDefault();
        url = "/user/login/";
        $.post(url,$('#login_form').serialize(),function(data){
            if(data.success){
                $("#profile_link").html(data.user);
                $("#profile_link").attr("href","/user/"+data.user+"/");
                $(".logged_in").show();
                $(".logged_out").hide();
                $("#error_msg2").html("");
                $('#crystals').html(data.credits+' crystals')
                
            }
            else {
                $("#error_msg2").html("<img src='/media_kaetherya/images/error_login.png' width='160' height='87' alt='The account name or password you entered is incorrect.' />");
            }
        }, 'json');
        return false;
    })

    

    
    $('#register_btn').click(function(event){
        event.preventDefault();
        url = "/user/ajax_register/";
        $.post(url,$('#registration_form').serialize(),function(data){
            if(data.success){
                $("#profile_link").html(data.user);
                $("#profile_link").attr("href","/user/"+data.user+"/");
                $('#crystals').html(data.credits+' crystals')
                $(".logged_in").show();
                $(".logged_out").hide();
                $("#error_msg1").html("");
            }
            else {
               $("#error_msg1").html('');
                for(err in data.errors){
                    if(data.errors[err]=='r1')
                        $("#error_msg1").prepend("<img src='/media_kaetherya/images/error_username_chars.png' width='160' height='100' alt='Account names must have between 3 and 15 characters. You may use letters, numbers and the underscore.' />")
                    else if(data.errors[err]=='r2')
                        $("#error_msg1").prepend("<img src='/media_kaetherya/images/error_username_inuse.png' width='160' height='70' alt='The Account names you have choosen is already in use.' />")
                    else if(data.errors[err]=='r3')
                        $("#error_msg1").prepend("<img src='/media_kaetherya/images/error_passwords.png' width='160' height='87' alt='Passwords must have at least 6 characters and the two Passwords must match.' />")
                }
                
            }
        }, 'json');
        return false;
    })


    $('#logout_btn').click(function(event){
        event.preventDefault();
        url = "/user/logout/";
       
        $.post(url,{},function(data){
            $(".logged_in").hide();
            $("#error_msg").html("");
            $(".logged_out").show();
        });
        return false;
    })
})