var redirect_to = '';
$(document).ready(function() {
    if(!logged_in){
	    $('.require_login').bind("click",function () {
    		redirect_to = $(this).attr('href'); 
			$("#lightbox").width('348');
            $('#lightboxArea').load("/ajax/login.php",{},function(){
				$('#ajax_login').click(function () {ajax_authenticate($('#ajax_email').val(),$('#ajax_password').val());});
				$('#ajax_get_register').click(function () {
					
                    $('#lightboxArea').load("/ajax/register.php",{},function(){
                        $("#lightbox").width('530');
						centerPopup(); // tidy up lightbox now new content;
						$('#ajax_register_button').click(function () {
							$.post("/ajax/register_process.php", $("#ajax_register_form").serialize(),
								function(data){
									
									if(data.result=='FAIL'){
										// registration failed. Output why
										alert(data.errors);
									}
									if(data.result=='PASS'){
										// new user registered so get moving
										if(redirect_to){
											window.location = redirect_to;
										}else{
											// no redirect so just reload the page
											location.reload(true);
										}
                                        disablePopup();									
									}
								},"json");
						});
					});
				});

				
				loadPopup();            
			});  
      		return false;
	    });
	}
    

});

function ajax_authenticate(email,password){
	if(!email || !password){
		alert("Please enter both your username and your password");
		return false;
	}
	$.post("/ajax/login_process.php", { email: email, password: password },
		function(data){		
			if(data=='PASS'){
				if(redirect_to){
					window.location = redirect_to;
                    
				}else{
					// no redirect so just reload the page
					location.reload(true);
				}
                disablePopup();	
			}else{
				alert("Login Failed. If you cannot remember your details you can use the forgotten password option below.");
			}
	});

	
	
}
