/* Registration Page Javascript */

/* Initial Page Loader */
jQuery(document).ready(function()
{
	eventSetting2();						// load all user events
	jQuery(".scroller").scrollLeft(0);	// set scrollbar to start point
});





/* User Event Settings */
function eventSetting2()
{
	/* === All input, textarea, select === */
	jQuery(":input").bind("keypress", fieldtab);
	
	/* === Country Select Field === */
	jQuery("select[name=country]").bind("change", updateCountryCode);
	
	/* === Horizontal Scrolling Effect === */
	// for all <li>
	jQuery("#regpanel").find("#nextstep").bind("click", function()		// next button
	{
			var e = jQuery("#regpanel").find("li");
			var i = e.eq(1).offset().left - e.eq(0).offset().left;			// get gap from 1st <li> n 2nd <li>
			var l = jQuery(".scroller").scrollLeft();						// current horizontal scroll position
			
			jQuery(".scroller").stop(false, true).animate({ "scrollLeft":(l + i) }, 500);		// animate the scrolling
	});
	
	jQuery("#regpanel").find("#prevstep").bind("click", function()		// previous button
	{
			var e = jQuery("#regpanel").find("li");
			var i = e.eq(1).offset().left - e.eq(0).offset().left;			// get gap from 1st <li> n 2nd <li>
			var l = jQuery(".scroller").scrollLeft();						// current horizontal scroll position
			
			jQuery(".scroller").stop(false, true).animate({ "scrollLeft":(l - i) }, 500);		// animate the scrolling
	});
	
	/* === Submitting Form === */
	jQuery("#submitstep").bind("click", function()		// submit button
	{
		// form validation result (pass or fail)
		if (validation())
		{
			var hash = jQuery.fn.sha1hash(jQuery("input[name=password1]").val());	// SHA1 hash the password
			jQuery("input[name=password1]").val(hash);								// store in password field
			jQuery("input[name=password2]").val(hash);								// store in password field
			jQuery("form").submit();												// send out form
		}
		else
		{
			var li = jQuery("#regpanel").find("li");	// all <li>
			
			loop1:								//1st loop
				for (var a=0; a<li.length; a++)		// loop <li>
				{
			loop2:								// 2nd loop
					for (var b=0; b<li.eq(a).find("span").length; b++)		// loop <li> <span>
					{
						var span = jQuery("#regpanel").find("li").eq(a).find("span").eq(b);
						
						if (span.attr("class") == "error")	// with class .error
						{
							if (span.html() != "&nbsp;")	// check that is not empty = got error exists
							{
								var i = li.eq(1).offset().left - li.eq(0).offset().left;		// get gap from 1st <li> n 2nd <li>
								jQuery(".scroller").stop(false, true).animate({ "scrollLeft":(i * a) }, 500);		// animate the scrolling
								break loop1;
							}
						}
					}
				}
			
			jQuery("#loading").stop(false, true).hide();			// hide loading screen
		}
	});
	
	
}





/* Prevent Tab from Spoiling scroll effect */
function fieldtab(event)
{
	if (event.keyCode == 9)		// tab key
	{
		// last input, textarea or select field of the current table
		var last = jQuery(this).parents("table").find(":input:last").attr("name");

		if (jQuery(this).attr("name") == last) return false; // last field is current field then disable tab
	}
}





/* Update Country Code depending on the country chosen */
function updateCountryCode()
{
	var cry		= jQuery("select[name=country]");		// country drop-down field
	var code	= jQuery("input[name=code]");			// country code textfield
	
	jQuery.ajax(
	{
		type		: "POST",									// post method
		url			: "ajax/registration.php",					// server url fo retrieval
		data		: 
		{
			"type"		:	"countrycode",						// post query
			"country"	:	cry.find(":selected").val()
		},
		datatype	: "text",									// return type
		success		: function(text)
		{
			code.val(text);		// store country code in field
		}
	});
}





/* Form Validation */
function validation()
{
	/* === Form Elements === */
	var name		= jQuery("input[name=username]");		// username textfield
	var pwd1		= jQuery("input[name=password1]");		// password textfield
	var pwd2		= jQuery("input[name=password2]");		// confirm password textfield
	var name1		= jQuery("input[name=name1]");			// firstname textfield
	var name2		= jQuery("input[name=name2]");			// lastname textfield
	var email		= jQuery("input[name=email]");			// email textfield
	var code		= jQuery("input[name=code]");			// country code textfield
	var contact		= jQuery("input[name=contact]");		// contact no. textfield
	var question	= jQuery("input[name=question]");		// secret question textfield
	var answer		= jQuery("input[name=answer]");			// answer textfield
	var token		= jQuery("input[name=token]");			// captcha token hidden field
	var imgveri		= jQuery("input[name=imgveri]");		// captcha textfield
	var terms		= jQuery("input[name=terms]");			// terms and condition checkbox

	// all the <span>
	jQuery("span").filter(".error").html("&nbsp;");	// reset all error message area
	
	/* Align Loading Screen */
	function alignLoader()
	{
		jQuery("#loading").stop(false, true).fadeIn("normal");
		
		var winsize = {	h:jQuery("#loading").height(), w:jQuery("#loading").width() };	// browser size
		var size	= { h:jQuery("#loader").height(), w:jQuery("#loader").width() };			// loader size
		
		jQuery("#loader").css({ "left":((winsize.w - size.w) / 2) +"px", "top":((winsize.h - size.h) / 2) +"px"});
	}
	
	/* is empty field, show error */
	function isblank(field, fieldname)
	{
		if (field.val().length < 1)
			field.parent().find(".error").text(fieldname +" must be filled.");
	}
	
	if (name.val().length < 3) name.parent().find(".error").text("Username must be of 3-20 characters.");	// username length not enough
	if (pwd1.val().length < 6) pwd1.parent().find(".error").text("Password must be of 6-20 characters.") ;	// password length not enough
	if (pwd1.val() != pwd2.val()) pwd2.parent().find(".error").text("Passwords do not match.");				// confirm password not match
	
	// check fields are not blank
	isblank(name1, "First Name");
	isblank(name2, "Last Name");
	isblank(email, "Email");
	isblank(contact, "Contact No.");
	isblank(question, "Secret Question");
	isblank(answer, "Answer");
	isblank(imgveri, "Image Verification");
	
	if (!terms.is(":checked")) terms.parent().find(".error").text("Terms and Condition must be agreed for using our service.");		// terms and condition checked
	if (isNaN(contact.val())) contact.parent().find(".error").text("Contact No. must be a valid one.");								// contact no. is numeric
	
	if (code.val().length > 0)	// country code is numeric if it is filled
		if (isNaN(code.val())) contact.parent().find(".error").text("Contact No. must be a valid one.");
	
	/* === Server-Client Validation === */
	/* Validate email, username existed */
	/* Validate captcha valid or not */
	jQuery.ajax(
	{
		type		: "POST",							// post method
		async		: false,							// must receive data before process end
		url			: "ajax/registration.php",			// server url fo retrieval
		data		: 
		{
			"type"	:	"validation",					// post query
			"name"	:	name.val(),
			"email"	:	email.val(),
			"token"	:	token.val(),
			"image"	: 	imgveri.val()
		},
		datatype	: "json",							// return type
		beforeSend	: function()						// before send data out
		{
			alignLoader();
		},
		success		: function(xhr)
		{
			var json = (typeof xhr == "object") ? xhr : eval("(" + xhr + ")");
			
			user_result		= json.username;	// <username>
			email_result	= json.email;		// <email>
			captcha_result	= json.captcha;		// <captcha>
			
			if (user_result == "used") name.parent().find(".error").text("Username has already been registered.");		// prompt username exist or not
			
			if (email_result == "used")
				email.parent().find(".error").text("Email has already been registered.");
			else
				if (email_result == "invalid") email.parent().find(".error").text("Email is not a valid one.");			// prompt email exist or not or invalid
			
			// captcha verified fail
			if (captcha_result != "correct")
			{
				token.val(captcha_result);		// set new captcha value
				jQuery("#captcha").attr("src", "graphics/form/captcha_image.php?token="+ captcha_result);	// load new captcha image
				imgveri.parent().find(".error").text("Image Verification failed.");		// prompt error
			}
		}
	});
	
	// for all <span>
	for(var a=0; a<jQuery("span").length; a++)
	{
		if (jQuery("span").eq(a).attr("class") == "error")	// with class .error
		{
			if (jQuery("span").eq(a).html() != "&nbsp;")	// check that is not empty = got error exists
				return false;	// don't submit
		}
	}
	return true;	// submit
}