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

var AllstreamLP = {

	validForm : null,

	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("validFirstName",
			function(data, e)
			{
				return (e.value != "*First")? true : false;
			}, "First name is required");
                /* 
                 * The hints() method puts the title in the value as a tooltip, but doesn't remove it on form submission. 
                 * This validation method returns true if the element is not empty AND the title != value
                */
                jQuery.validator.addMethod('requiredAndIgnoreHint',
                        function(data, elm){
                            
                            return elm.value!=elm.title && jQuery.trim(elm.value)!=''
                            //return false;
                        },'Field is required');

		// MyOwnBoss.ca form and new landing pages.
		if ($("#userInfoForm input[name=version]").val() == 2)
		{
			$("#userInfoForm").validate(
			{
				rules:
				{
					companyName: { required: true },
					firstName: { required: true, validFirstName : true },
					companyEmail: {	/*required: true,*/ email: true, emailOrPhone: true },
					companyPhone: { /*required: true*//*, phone: true*/ emailOrPhone: true }
				}
			});
		}
		// 2010 Q4 landing pages.
		else if ($("#userInfoForm input[name=version]").val() == 3)
		{
			$("#userInfoForm").validate(
			{
				rules:
				{
					companyName: { required: true },
					firstName: { required: true, validFirstName : true },
					postalCode: { required: true, postalCode: true },
					companyEmail: {	email: true, emailOrPhone: true },
					companyPhone: { emailOrPhone: true }
				}
			});
		}
		else if ($("#userInfoForm input[name=version]").val() == 4)
		{
			jQuery.validator.setDefaults({
				errorPlacement: function(error, element) {
					error.insertAfter('#error-' + element.attr('id'));
				}
			});
                           

			$("#userInfoForm").validate(
			{
				rules:
				{
					companyName:    {'requiredAndIgnoreHint':true},
                                        firstName:      {'requiredAndIgnoreHint':true},
					companyEmail:   {'requiredAndIgnoreHint':true, email: true, emailOrPhone: true },
					companyPhone:   {'requiredAndIgnoreHint':true, emailOrPhone: true }
				},
				invalidHandler: function(form, validator) {
					var errors = validator.numberOfInvalids();

					if (errors)
						$("#userInfoForm li.required label").show();
					else
						$("#userInfoForm li.required label").hide();
				},
				submitHandler: function(form) {
					if ($("#userInfoForm input[name=trackSubmit]").val() == 1)
						AllstreamLP.recordGASubmit(form, 'Bundles Submit Form', document.location);
					else
						form.submit();
				},
				messages: {
                                    	firstName: "*",
					companyName: "*",
					companyEmail: "*",
					companyPhone: "*"
				}
			});
		}
		// Find a solution
		else if ($("#userInfoForm input[name=version]").val() == "FIND_A_SOLUTION")
		{
			$("#userInfoForm span.asterisk").hide();
			
			$("#userInfoForm").validate(
			{
				rules:
				{
					companyEmail: {	email: true, emailOrPhone: true },
					companyPhone: { emailOrPhone: true }
				},
				invalidHandler: function(form, validator) {
					var errors = validator.numberOfInvalids();

					if (errors)
						$("#userInfoForm span.asterisk").show();
					else
						$("#userInfoForm span.asterisk").hide();
				}
			});
		}
		// Old landing pages.
		else
		{
			$("#userInfoForm").validate(
			{
				rules:
				{
					companyName: { required: true },
					firstName: { required: true },
//					lastName: {	required: true },
//					city: {	required: true },
//					province: {	required: true },
					companyEmail: {	email: true, emailOrPhone: true },
					companyPhone: { emailOrPhone: true },
					postalCode: { required: true, postalCode: true }
//					companyEmail: {	required: true, email: true },
//					companyPhone: { required: true }
				}
			});
		}
	},

	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')
			{
				$('#serverError').each(function(i)
				{
					this.innerHTML = decodeURIComponent(pair[1]);
					$(this).css('display', 'block');
				});
				continue;
			}
			
			$('#userInfoForm input[name='+pair[0]+'],#userInfoForm select[name='+pair[0]+'],#userInfoForm 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]));
			});
		}
	
		$("#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')
					$("#unqualified").css('display', 'block');
				else if (pair[1] == '1')
					$("#qualified").css('display', 'block');
				
				return;
			}
		}
	},
	
	enableInputHints : function()
	{
		if ($(".hint-enabled").get(0))
		{
			// find all the input elements with title attributes
			$('input[title!=""]').hint();
		}
	},
	
	recordOutboundLink : function(link, category, action) {
	  try {
		var myTracker=_gat._getTrackerByName();
		_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
//		setTimeout('document.location = "' + link.href + '"', 100);
		setTimeout('window.open("' + link.href + '")', 100);
	  }catch(err){}
	},
	
	recordGASubmit : function(form, category, action) {
	  AllstreamLP.validForm = form;

	  try {
		var myTracker=_gat._getTrackerByName();
		_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
		setTimeout('AllstreamLP.validForm.submit()', 100)
	  }catch(err){}
	}
}
