/*
 * validation.js
 */
$(document).ready(function(){
// global vars
var form 				= $("#customForm");
var formPart2 			= $("#formPart2");
var emailConf 			= $("#emailConf");
var email 				= $("#email");
var emailInfo 			= $("#emailInfo");
var confirmEmail 		= $("#confirmEmail");
var confirmEmailInfo 	= $("#confirmEmailInfo");
var firstname 			= $("#firstname");
var firstNameInfo 		= $("#firstNameInfo");
var lastname 			= $("#lastname");
var lastNameInfo 		= $("#lastNameInfo");
var pass1 				= $("#pass1");
var pass1Info 			= $("#pass1Info");
var pass2 				= $("#pass2");
var pass2Info 			= $("#pass2Info");
var tos					= $("#tosagree");

var send 				= $("#send");
var processing 			= $("#processing");
var processingLogo 		= $("#processingLogo");
var formPart3 			= $("#formPart3");
var intro 				= $("#intro");

var showingEmailConf = false;
var showingFormPart2 = false;

function setup()
{
	email.val('');
	confirmEmail.val('');
	firstname.val('');
	lastname.val('');
	pass1.val('');
	pass2.val('');
	
	formPart2.hide();
	formPart3.hide();
	
	intro.show();
	//emailConf.hide();
	//disableObj(formPart2);
	email.val("");
	email.focus();
}



/**
 * Check that the email is valid
 */
function validateEmail()
{
	if (email.val() != email.lastValue && email.val() != '')
	{	
		this.timer = setTimeout(function ()
		{
			
			//	track the valuse of this test, so that we don't send unnessirary requests
			email.lastValue = email.val();
			
			//	reset our classes, so that styling is neutral
			email.removeClass("success");
			email.removeClass("error");
			emailInfo.removeClass("success");
			emailInfo.removeClass("error");
			confirmEmail.removeClass("success");
			confirmEmail.removeClass("error");
			confirmEmailInfo.removeClass("success");
			confirmEmailInfo.removeClass("error");
			confirmEmailInfo.html("Sorry to make you repeat yourself, but it's really important!");
			disableObj(emailConf);
			confirmEmail.val("");
			
			
			
			//	give the user some feedback that we're checking the email
			emailInfo.html('<img src="/images/ajax-loader1.gif" height="16" width="16" /> checking availability...');
			
			var emailString = $("#email").val();
			
			if (validateEmailOnClient(emailString))
			{
				validateEmailOnServer(emailString);
			}
			else
			{
				email.addClass("error");
				emailInfo.text("Whoa, there! Type a valid e-mail please :P");
				emailInfo.addClass("error");
				disableObj(emailConf);
				disableObj(formPart2);
				
			}
		},
		200);
		
	}
}

function validateEmailOnClient(emailString) 
{
	// Testing regex
	var filter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	
	return filter.test(emailString);
}

function validateEmailOnServer(emailString)
{	
	//	make an ajax call to the server to test our email address
	$.ajax(
	{
		url: '/signup/testemail/',
		data: 'email=' + emailString,
		dataType: 'json',
		type: 'post',
		success: function (j) {
			handleEmailResponse(j);	        	
		},
		error: function () {
			handleEmailCheckFailure();
		}
	});
}


function handleEmailResponse(response)
{
	console.debug(response);
	//alert("handle: "+response);
	if (response.ok == true)
	{
		//alert("ok");
		//emailInfo.html(response.msg);
		//emailInfo.addClass("success");
		
		
		//emailInfo.html('<img src="/images/green-check.jpg" height="40" width="35" />');
		emailInfo.html('OK');
		email.addClass("success");
		enableObj(emailConf);
		if (! showingEmailConf)	// This keeps us from making the email conf slide in five times...
		{
			showingEmailConf = true;
			showObj(emailConf);
		}
		
		
	}
	else
	{
		//alert("unok");
		emailInfo.html(response.msg);
		emailInfo.addClass("error");
		email.addClass("error");
		disableObj(emailConf);
		disableObj(formPart2);
	}
}

function handleEmailCheckFailure()
{
	
}

function validateConfirmEmail()
{
	if (confirmEmail.val() != confirmEmail.lastVal)
	{
		confirmEmail.lastVal = confirmEmail.val();
		
		confirmEmail.removeClass("success");
		confirmEmailInfo.removeClass("success");
		confirmEmail.removeClass("error");
		confirmEmailInfo.removeClass("error");

		if (email.val() == confirmEmail.val() && !email.hasClass("error") && confirmEmail.val() != "")
		{
			confirmEmail.addClass("success");
			//confirmEmailInfo.html('<img src="/images/green-check.jpg" height="40" width="35" />');
			confirmEmailInfo.html('OK');
			//confirmEmailInfo.addClass("success");
			enableObj(formPart2);
			
			if (! showingFormPart2)
			{
				showingFormPart2 = true;
				showObj(formPart2);
				//formPart2.attr("disabled","false");
			}
			return true;
		}
		else if (!email.hasClass("error") && confirmEmail.val() != "")
		{

			confirmEmail.addClass("error");
			confirmEmailInfo.addClass("error");
			confirmEmailInfo.html("Email must match.");
			return false;
		}
	}
	
}

/**
 *	Check that the First Name is at least 2 characters
 */
function validateFirstName()
{
	//If it's not valid...
	if (firstname.val().length < 2)
	{
		firstname.addClass("error");
		firstNameInfo.text("Sorry, but we only accept names with at least 2 letters :(");
		firstNameInfo.addClass("error");
		return false;
	}
	else
	{
		firstname.removeClass("error");
		firstname.addClass("success");
		firstNameInfo.removeClass("error");
		//firstNameInfo.html('<img src="/images/green-check.jpg" height="40" width="35" />');
		firstNameInfo.html('OK');
		return true;
	}
}

/**
 *	Check that the Last Name is at least 2 characters
 */
function validateLastName()
{
	//If it's not valid...
	if (lastname.val().length < 2)
	{
		lastname.addClass("error");
		lastNameInfo.text("Sorry, but we only accept names with at least 2 letters :(");
		lastNameInfo.addClass("error");
		return false;
	}
	else
	{
		lastname.removeClass("error");
		lastname.addClass("success");
		lastNameInfo.removeClass("error");
		//lastNameInfo.html('<img src="/images/green-check.jpg" height="40" width="35" />');
		lastNameInfo.html('OK');
		return true;
	}
}

/**
 * Check the length of passwords (must be longer then 5 characters).
 */
function validatePass1()
{
	var a = $("#password1");
	var b = $("#password2");
	
	if (pass1.val().length < 5)
	{
		pass1.addClass("error");
		pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
		pass1Info.addClass("error");
		return false;
	}
	else
	{
		pass1.removeClass("error");
		pass1.addClass("success");
		pass1Info.removeClass("error");
		//pass1Info.html('<img src="/images/green-check.jpg" height="40" width="35" />');
		pass1Info.html('OK');
		return true;
	}
}

/**
 * Check that both password fields match.
 */
function validatePass2()
{
	var a = $("#password1");
	var b = $("#password2");
	
	if ( pass1.val() != pass2.val() )
	{
		pass2.addClass("error");
		pass2Info.text("Passwords do not match!");
		pass2Info.addClass("error");
		return false;
	}
	else
	{
		pass2.removeClass("error");
		pass2.addClass("success");
		pass2Info.removeClass("error");
		//pass2Info.html('<img src="/images/green-check.jpg" height="40" width="35" />');
		pass2Info.html('OK');
		return true;
	}
}

function enableObj(object)
{
	//object.removeAttr("disabled");
}

function disableObj(object)
{
	//object.attr("disabled","true");
}

function hideObj(object)
{
	//object.hide("drop", {direction: "up"}, 500);
	object.hide();
}

function showObj(object)
{
	//object.show("drop", {direction: "down"}, 500);
	object.fadeIn();
}





//	Call the above functions on blur and keyup events

email.blur(validateEmail);
confirmEmail.blur(validateConfirmEmail);
firstname.blur(validateFirstName);
lastname.blur(validateLastName);
pass1.blur(validatePass1);
pass2.blur(validatePass2);

email.keyup(validateEmail);
confirmEmail.keyup(validateConfirmEmail);
firstname.keyup(validateFirstName);
lastname.keyup(validateLastName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);

$("#customForm").submit(function(){
	if (validateEmailOnClient(email.val()) && validateFirstName() && validateLastName() && validatePass1() && validatePass2())
	{
		if (tos.attr('checked'))
		{
			intro.hide();
			emailConf.hide();
			formPart2.hide();
			processingLogo.html('<img src="/images/ajax-loader1.gif"/> ');
			formPart3.show();
			
			return true;
		}
		else
		{
			alert("In order to sign up for an account, you must agree to the Terms of Service.");
			return false;
		}
		
	}
	else
	{
		alert("Whoops...\nIt looks like you need to correct some of the information in the signup form.");
		return false;
	}
});

setup();

});


