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

var AllstreamTA = {

	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("emailOrPhoneTA",
			function(data, element)
			{
				return ((document.getElementById("companyEmailTA").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');
                        
		jQuery.validator.setDefaults({
			errorPlacement: function(error, element) {
				error.insertAfter('#error-' + element.attr('id'));
			}
		});
	
		$("#userInfoFormTA").validate(
		{
			rules:
			{
                                firstName: {requiredAndIgnoreHint:true},
                                companyName: {requiredAndIgnoreHint:true},
				companyEmail: {requiredAndIgnoreHint:true, email: true, emailOrPhoneTA: true }
			},
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();

				if (errors)
					$("#userInfoFormTA li.required label").show();
				else
					$("#userInfoFormTA li.required label").hide();
			},
			submitHandler: function(form) {
				if ($("#userInfoFormTA input[name=trackSubmit]").val() == 1)
					AllstreamTA.recordGASubmit(form, 'Bundles Submit Form', document.location);
				else
					form.submit();
			},
			messages: {
				companyEmail: "*",
                                companyName: "*",
                                firstName: "*"
			}
		});
	},

	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')
			{
				$('#serverErrorTA').each(function(i)
				{
					this.innerHTML = decodeURIComponent(pair[1]);
					$(this).css('display', 'block');
				});
				continue;
			}
			
			$('#userInfoFormTA input[name='+pair[0]+'],#userInfoFormTA select[name='+pair[0]+'],#userInfoFormTA 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]));
			});
		}
	
		$("#userInfoFormTA").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) {
	  AllstreamTA.validForm = form;

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