var fctn = undefined;
var args = undefined;

function loginCheck(){	
	fctn = arguments[0];
	args = Array.prototype.slice.call(arguments, 1);

	//this is just double checking we arent logged in on another tab or something
	$.ajaxSetup({async: false});
	$.getJSON(baseUrl+'auth/login-check',function(uid) {
		if(uid != 0) {
			casUid = uid;
		}
	});
	$.ajaxSetup({async: true});
	
	if (casUid != 0) { //we actually are logged in, dont try to login
		if (fctn != undefined) {
			fctn.apply(null, args);
		}
	} else {	   //we really arent logged in, we need to do it
		//$("#register-dialog").dialog("close");
		
		$.fn.colorbox({
			inline : true, 
			href   : "#login-dialog",
			onLoad : function () {
					$( '#login-dialog' ).show();
				},
			onComplete : function () {
					$('#credentials-username').focus();
				},
			onCleanup : function () {
					$( '#login-dialog' ).hide();
				}
			});
		
		$('#credentials').unbind();
		$('input#register').unbind();
		$('#update_basics input#confirm').unbind();
		loginListener(arguments);
	}
};

function loginListener(){				
	$('#credentials').submit(function(event){
		event.preventDefault();
		event.stopPropagation();		
		$.post(this.action, $(this).serialize(),
			function(data) {
				if(data.login == 'success') {
					casUid = data.casUid;
					headerBoxLogin();
					$("#login-dialog").colorbox.close();
					if (fctn != undefined) {
						fctn.apply(null, args);
					}
				} else if(data.login == 'Fail') {
					alert('Invalid login or Password');
				} else if(data.login == 'cas') {
					$.ajax({
						url: baseUrl + 'auth/basics?uid='+data.casUid+'&token='+data.token,
						success: function(msg){
							$('#login-dialog').dialog('option', 'height', 330);
							$('#login-dialog').dialog('option', 'width', 400);
							$('#login-dialog').css('height', 300);
							$('#login-dialog').html(msg);
// 							casListener(fctn.apply(null, Array.prototype.slice.call(arguments, 1)));
						}
					});
				}
				else {
					alert('Unknown login error.');
				}
			}, 
			'json');
	});
};

/**
 * Attach click listener to register button.
 */
function registerListener(followlink){
	$('#register').click(function(event) {
		event.preventDefault();
		event.stopPropagation();
		
		// validate some fields
		if($('#basics-email').val() === '') {
			alert('You must enter an email address.');
			return false;
		} else if ($('#username').val() === '') {
			alert('You must enter a username.');
			return false;
		} else if($('#set_password-password').val() !== $('#set_password-password_confirm').val()){
			alert('Password confirmation does not match.');
			return false;
		}

		$.post(
			baseUrl + 'auth/signup', 
			$('#registerForm').serialize(), 
			function(data) {
			
			if(data.account_creation == 'success') {
				casUid = data.casUid;
				alert('Your account has been created.  You have been sent an email, and will need to confirm your email address to use your account again.');
				
				// Close after success
				$.fn.colorbox.close();
				
				$("#login-dialog").close();
				if (fctn != undefined) {
					fctn.apply(null, args);
				}
			} 
			else if(data.account_creation == 'fail') {
				alert(data.msg);	    
			} 
			else {
				alert('Something has gone wrong');
			}
			}, 'json'); 
	});
};

function casListener(fctn) {
	$('#update_basics input#confirm').click(function(event){
		event.preventDefault();		
		var basics = $('form#update_basics').serialize(); 
		$.post(baseUrl+'auth/basics', 
				basics, 
				function loginValidate(data) {
					if(data.login == 'success') {
						casUid = data.casUid;
						headerBoxLogin();
						$("#login-dialog").dialog("close");
						if (fctn != undefined) {
							fctn.apply(null, args);
						}
					} else {
						alert('Error updating your information');
					} 
			}, 'json');
	});
};

function headerBoxLogin(){
	$.ajax({
		url: baseUrl + 'auth/header-box',
		success: function(msg){
			$("#headerBoxLogin").html(msg);
		}
	});
};

$(document).ready(
	function() {
		$("a[href$='signup']").live('click', function(event) {
			event.preventDefault();
			event.stopPropagation();
			$.fn.colorbox({
				width  : '570px', 
				height:  '400px',
				inline : true, 
				href   : "#register-dialog",
				onLoad : function () {
						$( '#register-dialog' ).show();
					},
				onCleanup : function () {
						$( '#register-dialog' ).hide();
					}
				});
			//$('#register-dialog').dialog('open');
			function redirect() {
				window.location = link;
			}
			registerListener(redirect);
		});
		
		$("a[href$='login']").live('click', function(event){
			event.preventDefault();
			event.stopPropagation();

			if($(this).attr('id') == 'user-panel-signin') {
				link = baseUrl + 'my';
			} else {
				var link = $(this).attr('href'); 
				link = link.split('/');
				var newLink = new Array();
				for(var i=0; i< link.length; i++){
					if(link[i] != 'login') {
						newLink [i]= link[i];
					} else {
						break;
					}
				}
				link = newLink.join('/');
			}
			function redirect() {
				window.location = link;
			}
			loginCheck(redirect);
		});
	}
);

