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/index/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");
		$("#login-dialog").dialog("open");
		$('.credentials-login').unbind();
		$('input#register').unbind();
		$('#update_basics input#confirm').unbind();
		loginListener(arguments);
	}
};

function loginListener(){				
	$('.credentials-login').click(function(event){
		event.preventDefault();
		event.stopPropagation();
		var login = $(this).parents('form').serialize();		
		$.post(baseUrl+'login', 
			login,
			function loginValidate(data) {
				if(data.login == 'success') {
					casUid = data.casUid;
					headerBoxLogin();
					$("#login-dialog").dialog("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/index/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 if(data.login == 'confirm') {
					alert('You have been sent a confirmation email, you will need to confirm your account to use it again.');
				} else {
					alert('Unknown login error.');
				}
			}, 
			'json');
	});
};

function registerListener(followlink){
	$('#register').click(function(event) {
		event.preventDefault();
		event.stopPropagation();	

		if('#basics-email' == '') {
			alert('You must enter an email address.');
			return;
		} else if ('#username' == '') {
			alert('You must enter a username.');
			return;
		}

		$.post(baseUrl+'auth/index/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.')
				$("#register-dialog").dialog("close");
				$("#login-dialog").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/index/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/index/header-box',
		success: function(msg){
			$("#headerBoxLogin").html(msg);
		}
	});
};

$(document).ready(
	function(){			
		$("a[href$='signup']").live('click', function(event){
			event.preventDefault();
			event.stopPropagation();
			$('#register-dialog').dialog('open');
			function redirect() {
				window.location = link;
			}
			registerListener(redirect);
		});
		
		$("a[href$='login']").live('click', function(event){
			event.preventDefault();
			event.stopPropagation();
			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);
		});

		$('#login-dialog').dialog({
			autoOpen: false,
			width: 300,
			height: 200,
			resizable: false,
			modal: true,
			overlay: {
				opacity: 0.5,
				background: 'black'
			},
			open: function(event, ui) {$(event.target).find('input:first').trigger('focus')}
		});

		$('#register-dialog').dialog({
			autoOpen: false,
			width: 240,
			height: 380,
			modal: true,
			overlay: {
				opacity: 0.5,
				background: 'black'
			} 
		});			
	}
);