$(document).ready(function() {
	// Setup colorbox options
	var colorbox_options = {
			inline:true,
			href:"#login",
			scrolling:false
		};
	
	// Bind colorbox to the login link
	$('.login-link').colorbox(colorbox_options);
	
	// Catch the login button click
	$('input[name="login"]').live('click', function() {
		// Fade out any previous erros
		$('#login div.error').fadeOut('slow');
		
		// Get the form values
		username = $('#login input[name="username"]').val();
		password = $('#login input[name="password"]').val();
		remember = $('#login input[name="remember"]').attr('checked');
		if (remember == true) {
			remember = "Y";
		} else {
			remember = "N";
		}
		
		// Submit the form
		$.ajax({
			url: $('input[name="login_url"]').val(), //URLS/ajax.php
			data: "action=login&username="+username+"&password="+password+"&remember="+remember,
			type:"post",
			dataType: 'json',
			success: function(data) {
				// Got a response, is it valid
				if (data.status == "invalid") {
					// Invalid login 
					$('#login div.error').html(data.response);
					$('#login div.error').fadeIn('slow');
					$.colorbox(colorbox_options).resize(); //resize otherwise it gets chopped off
				} else {
					// Login success
					$('#login div.error').hide();
					$('#login div.success').fadeIn('fast');
					$.colorbox(colorbox_options).resize(); //resize otherwise it gets chopped off
					
					// Set a delay so the login message can be read
					setTimeout(function() {
						window.location = data.redirect;
					},1500);
				}
			},
			failure: function() {
				// AJAX connection error
				$('#login div.error').html('Failed to connect. Please go here: <a href="login.php">Login</a>');
				$('#login div.error').fadeIn('slow');
			}
		});
	});
});
