var login_overlay;

$(document).ready(function () {
  
	// Any page can add this div to show an animation during 
	// ajax calls. 
	$("#ajax_loading").ajaxStart(function(){
		$(this).show();
	});
 	$("#ajax_loading").ajaxStop(function(){
 		$(this).hide();
 	});
	
	// Any page with ajax pagination 
	ajaxpages_bindscroll(); 
	
	
	// Login/registration forms. 
	$('.container input').focus(function(){
		$(this).parents('.highlight').addClass("over");
	}).blur(function(){
		$(this).parents('.highlight').removeClass("over");
	});
	
	// If the user is not currently logged in, display the ajax login form whenever 
	// they click on a link with the ajax_login class. Otheriwse, link will function 
	// normally. 
	// 
	// This expects that logged_in_user is defined in the base.html template
	if(!logged_in_user){ 
		login_overlay = $("a.ajax_login").overlay({ 
			api: true, 
			effect: 'apple',
			target: '#login_overlay', 
			onBeforeLoad: configure_login_form, 
			expose: '#B5B5B5' 
		});
	} 
});

function configure_login_form() { 
	// Get the url that the user is trying to access
	var api_object = this; 
	var success_url = api_object.getTrigger().attr('href') ;
	
	// Set the registration url to include the "next" parameter for the url that 
	// the user is trying to access, so we can redirect or provide a link after registration.
	var register_url = $('#login_overlay a#register_link').attr('href'); 
	register_url += '?next=' + success_url 
	$('#login_overlay a#register_link').attr('href', register_url); 
	
	// Set the login form to do an ajax post, and redirect to the success_url on successful login. 
	$('#ajax_login_form').ajaxForm({
		beforeSubmit: function(){ 
		 	// clear error div 
			$('#login_overlay .errorlist').html(''); 
		},  
		success: function(data) {
			if(data.success) { 
				window.location=success_url;
			} else { 
				var error_msg; 
				if (data.error) { 
					error_msg = data.error; 
				} else { 
					error_msg = "Error submitting login form."; 
				}
				$('#login_overlay .errorlist').html('<li>' + error_msg + '</li>'); 
			} 
		}, 
		dataType: 'json'
	}); 
} 

function ajaxpages_bindscroll(){ 
	$('.ajax_pagination a').click(function(){ 
		$('body').scrollTo(0, 0); 														   
	});	
}
