jQuery(document).ready(function()
{
	AllstreamLP.setupFormValidation();
	AllstreamLP.handleLPProcessorError();
	AllstreamLP.toggleThankyouMsg();
});

var AllstreamLP = {
    submitting : false,

	setupFormValidation : function()
	{
		//borrowed from http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
		jQuery.validator.addMethod("phone",
			function(phone_number, element)
			{
		    	phone_number = phone_number.replace(/\s+/g, ""); 
				return this.optional(element) || phone_number.length > 9 &&
						phone_number.match(/^(1[-.]?)?(\([2-9]\d{2}\)|[2-9]\d{2})[-\.]?[2-9]\d{2}[-.]?\d{4}$/);
			}, "Please specify a valid phone number");
	
		jQuery.validator.addMethod("postalCode",
			function(postalCode, element)
			{
				return this.optional(element) ||
						postalCode.match(/^\w\d\w\-? ?\d\w\d$/i);
			}, "Please specify a valid Postal Code"); 
		
		jQuery.validator.addMethod("emailOrPhone",
			function(data, element)
			{
				return ((document.getElementById("companyPhone").value != "") || 
						(document.getElementById("companyEmail").value != ""))? true : false;
			}, "Please specify a valid Postal Code"); 

		jQuery.validator.addMethod("emailOrEmail",
			function(data, element)
			{
				return ((jQuery("#altEmail").val() != "") || 
						(jQuery("#companyEmail").val() != ""))? true : false;
			}, "Please specify a valid Postal Code"); 

		jQuery("#userInfoForm").validate(
		{
			rules:
			{
//				productOfInterest: { required: true },
//				companyName: { required: true },
				companyEmail: {	email: true, emailOrPhone: true },
				firstName: { required: true },
//				lastName: {	required: true },
/*				altEmail: {	email: true, emailOrEmail: true },
				city: {	required: true },
				province: {	required: true },
				postalCode: { required: true, postalCode: true },*/
				companyPhone: { emailOrPhone: true }
			},
			submitHandler: function(form) {
				if (AllstreamLP.submitting == false)
				{
					AllstreamLP.submitting = true;
					
					jQuery("#serverError").hide ();
					
					jQuery.getJSON(
						"http://mtsallstreamsmallbusiness.com/lib/LandingPageProcessor.php?callback=?",
//						"http://64.69.94.165/~mtsallst/lib/LandingPageProcessor.php?callback=?",
						{
							page: form.page.value,
//							productOfInterest: form.productOfInterest.options[form.productOfInterest.selectedIndex].value,
							productOfInterest: form.productOfInterest.value,
//							companyName: form.companyName.value,
							firstName: form.firstName.value,
							lastName: form.lastName.value,
//							city: form.city.value,
//							province: form.province.options[form.province.selectedIndex].value,
//							postalCode: form.postalCode.value,
							companyEmail: form.companyEmail.value,
//							altEmail: form.altEmail.value,
//							companyPhone: form.companyPhone.value,
							optin: (form.optin.checked)? "1" : "0",
//							numberOfEmployees: form.numberOfEmployees.options[form.numberOfEmployees.selectedIndex].value,
							version: form.version.value
						},
						function(data) {
//							alert ('success: ' + data.status);
							if (data.status == 0)
							{
								jQuery("#serverError").html (data.error);
								jQuery("#serverError").show ();
							}
							else
							{
								jQuery("#asb-contact-form-body").slideToggle (200);
								jQuery("#asb-contact-form-ty").slideToggle (200);
								jQuery("div.asb-qualified").hide ();
								jQuery("div.asb-unqualified").hide ();
								
								if (data.qualified == 1)
									jQuery("div.asb-qualified").show ();
								else
									jQuery("div.asb-unqualified").show ();
								
								if (form.productOfInterest.options[form.productOfInterest.selectedIndex].text == "MOBC_HPS")
									jQuery.get ("/asb-hosted-ty.html");
								else
									jQuery.get ("/asb-bundles-ty.html");
							}
							AllstreamLP.submitting = false;
						}
					);
				}
			}/*,
			invalidHandler: function(form) {
				AllstreamLP.submitting = false;
			}*/
		});
	},

	handleLPProcessorError : function()
	{
		//check if redirected back from form processor
		var params = window.location.search;
		if (params == '')
			return;
		
		//get rid of the leading question mark
		params = params.slice(1);
	
		if (!/error=/.test(params))
			return; 
	
		var pairs = params.split('&');
	
		for (var i=0; i < pairs.length; ++i)
		{
			var pair = pairs[i].split('=');
	
			if (pair.length != 2)
				continue;
	
			//Display message from the server.
			if (pair[0] == 'error')
			{
				jQuery('#serverError').each(function(i)
				{
					this.innerHTML = decodeURIComponent(pair[1]);
					jQuery(this).css('display', 'block');
				});
				continue;
			}
			
			$('input[name='+pair[0]+'],select[name='+pair[0]+'],textarea[name='+pair[0]+']').each(function(i, ele)
			{
				if (this.type == "checkbox")
					this.checked = ((pair[1] == "") || (pair[1] == "0"))? false : true;
				else if (this.type == "radio")
				{
					if ($(this).val() == decodeURIComponent(pair[1]))
						$(this).attr("checked",true);
				}
				else
					$(this).val(decodeURIComponent(pair[1]));
			});
		}
	
		jQuery("#userInfoForm").validate().form();
	},
	
	toggleThankyouMsg : function()
	{
		//check if redirected back from form processor
		var params = window.location.search;
		if (params == '')
			return;
		
		//get rid of the leading question mark
		params = params.slice(1);
		var pairs = params.split('&');
		
		for (var i=0; i < pairs.length; ++i)
		{
			var pair = pairs[i].split('=');
	
			if (pair.length != 2)
				continue;
			
			if (pair[0] == 'el')
			{
				if (pair[1] == '0')
					jQuery("#unqualified").css('display', 'block');
				else if (pair[1] == '1')
					jQuery("#qualified").css('display', 'block');
				
				return;
			}
		}
	}
}
