$.metadata.setType("attr", "validate");
/*
	CURRENT BUGS:
		#bookmark indexing fixed.
		
	THIS SCRIPT MUST BE LOADED LAST ON ANY PAGE SHOWING THE FORMS.
*/
	var currentStep = 1,
		totalSteps = 1,
		savedData = new Array();
		whichForm = ''; //Initiate the form...

$(document).ready(function()
{
	$('select#aopIssue').removeAttr('disabled');
	$('select#aopIssue').change( function(e) {
		//First, only save old form data if there is a final step.
		//(This prevents old saved data from being overwritten.
		if ($('form#attorneyForm div#steps div.last input#phoneNumber').length > 0) {
			savedData = new Array(
				$('form#attorneyForm div#steps div.last input#phoneNumber').val(),
				$('form#attorneyForm div#steps div.last input#qidemailAddress').val()
				);
		}
		//Make sure the user specifies a selection we honor.
		if (( $(this).val() != '') && ($(this).val().constructor.toString().indexOf("Array") == -1)) {
			switch( $(this).val() ) {
				case 'accidents-injury':
				case 'bankruptcy':
				case 'child-custody':
				case 'criminal-defense':
				case 'divorce':
				case 'dui-dwi':
				case 'estate-planning':
				case 'medical-malpractice':
				case 'workers-compensation':
					whichForm = $(this).val();
				break;
				default:
					whichForm = '';
				break;
			}
		} else {
			whichForm = '';
		}
		if (whichForm != '') {
			/*	WhichForm is set to something we expect.
				First, get the request out for the form data we need.
				Meanwhile, change the 'complete' button to a continue button, add the classes to the form, 
				and change the processing text.  
			*/
			$('input#completeButton').val("Continue >");
			$('form#attorneyForm div#processingButton').text('Retrieving Questions..');
			$('form#attorneyForm').removeClass();
			$('form#attorneyForm').addClass('attorneyForm ' + whichForm + ' noAOPYet processing');
			$('div#bottomQs div#stepStatus span#stepType').text( $(this).children("option:selected").text() );
			$.get('/forms/' + whichForm + '.html',function (data) { return gotFormData(data,savedData); } ,'html');
		} else {
			/*	WhichForm is set to something else, or nothing.
				Remove all classes and set them to the defaults, disable the button, and change the 
				processing button text.
			*/
			$('form#attorneyForm').attr('class','attorneyForm noAOPYet');
			$('input#completeButton').attr("disabled",'disabled');
			$('form#attorneyForm div#steps div.addedStep').remove();
			$('form#attorneyForm div#processingButton').text('(Please Select an Issue)');
		}
		return true;
	});
		/*	gotFormData(data) is used to process data insertion when we get the form.
			Remove the processing & no AOP class, enable the button, change the processing text,
			REMOVE OLD FORM DATA, and add the new step data.
			Also loads the content of the final step with the last-saved data.
			Make sure to set the steps = to the total steps.
		*/
	function gotFormData(data,savedData) {
		$('form#attorneyForm').removeClass('processing noAOPYet');
		$('input#completeButton').removeAttr("disabled");
		$('form#attorneyForm div#processingButton').text('Processing..');
		$('form#attorneyForm div#steps div.addedStep').remove();
		$('form#attorneyForm div#steps').append(data);
		//Loading old data, if the user had any:
		$('form#attorneyForm div#steps div.last input#phoneNumber').val( savedData[0] ),
		$('form#attorneyForm div#steps div.last input#qidemailAddress').val( savedData[1] )
		totalSteps = $('div#steps div.step').size();
		if (currentStep > 1) {
			$('div.step#step' + currentStep).show();
		}
		$('div#bottomQs div#stepStatus span#totStep').text(totalSteps);
		return true;
	}
	
	
	
	/*	Handle the page navigation.
	
	*/
	$('input#completeButton').click(function()
	{
		if (attorneyForm.form()) {
			if (currentStep < totalSteps) {
				$('div.step#step' + currentStep).hide();
				currentStep++;
				$('div.step#step' + currentStep).show();
				$('input#backButton').show();
				$('div#bottomQs div#stepStatus span#currStep').text(currentStep);
				//Google Tracking-- 
				var urlAddText = '?' + ((location.href.indexOf("?") > 0) ? location.href.substring(location.href.indexOf("?") + 1) + '&' : '' ) + 'step=' + currentStep + '&aop=' + $('select#aopIssue').serialize() ;
				pageTracker._trackPageview(location.pathname + urlAddText );
				//alert (currentStep + " is current step, " + totalSteps + " is total steps, equality is: " + (currentStep == totalSteps ? 'true' : 'false') );
				if (currentStep == totalSteps) {
					$('input#completeButton').val("Submit");
				}
			} else if (currentStep != 1) {
				$("form#attorneyForm").submit();
			}
		}
		return false;
	});
	
	$('#backButton').click(function()
	{
		if (currentStep == totalSteps) {
			$('input#completeButton').val("Continue >");
		}
		if (currentStep == 2) {
			$('input#backButton').hide();
		}
		if (currentStep > 1) {
			$('div.step#step' + currentStep).hide();
			currentStep--;
			$('div.step#step' + currentStep).show();
			$('div#bottomQs div#stepStatus span#currStep').text(currentStep);
		}
		return false;
	});
	
	
	
	
	
	
	
	
	
	
	/*	Setting up the validator...
	*/
	var attorneyForm = jQuery('form#attorneyForm').validate({
		highlight: function(element, errorClass) {
			$(element).addClass(errorClass);
			$(element.form).find("label[for=" + element.name + "]").addClass('labelFieldError');
		},
		unhighlight: function(element, errorClass) {
			$(element).removeClass(errorClass);
			$(element.form).find("label[for=" + element.name + "]").removeClass('labelFieldError');
		},
		submitHandler: function (form) { return areDucksInARow(form); }
		});
	
	/*	Setting up the Lead Request form Validator..
	*/
	var leadRequestForm = jQuery('form#joinUsForm').validate({
		highlight: function(element, errorClass) {
			$(element).addClass(errorClass);
			$(element.form).find("label[for=" + element.name + "]").addClass('labelFieldError');
		},
		unhighlight: function(element, errorClass) {
			$(element).removeClass(errorClass);
			$(element.form).find("label[for=" + element.name + "]").removeClass('labelFieldError');
		},
		submitHandler: function (form) { return leadRequestSubmit(form); }
		});
	
	/*	Validator function.
		
	*/	
	function areDucksInARow(form) {
		if (totalSteps == 1) {
			return false;
		}
		$('form#attorneyForm').attr("action","#");
		//The next thing we have to do is concatenate a group of checkboxes into one value.
		//	How this works is that jQuery grabs a list of all the inputs with type=checkbox,
		//	and are checked, within a LI which has a 'qgroupConcat' class inside of it.
		//Then, jQuery combines them all into the value of qid1200002.. but ONLy at the final submit (now).
	
		var concatenations = new Array();
		$('input.qgroupConcat').each( function (whichConcat) {
			$(this).val('');  //First, blank any old data.
			//Then, make an array for what we will be concatenanting.
			concatenations[whichConcat] = new Array();
			//This item's ID is..
			var qID = $(this).attr("id");
			//The parent LI's ID is..
			var pID = $(this).parents("li.question").attr("id");
			//Use the parent LI's ID to gather ALL the child checked checkboxes AND all the child selected options.
			//	(it is unlikely that a list question would contain both.)
			$('#' + pID  + " input[class!=qgroupConcat].checkbox:checked, #" + pID + " input[class!=qgroupConcat].select > option:selected, #" + pID + " input[class!=qgroupConcat].radio:checked").each(function(boo) {
				//For each selected option, or checked checkbox...
				//If we're looking at an 'other' option, there is a field with a 'replacingin' variable matching this field's ID, AND the replacingin field has a length,
				if (
					($(this).is('.other')) 
					&& ($("[replacingin=" + $(this).attr('id') + "]").length == 1 )
					&& ($("[replacingin=" + $(this).attr('id') + "]").val().length > 0 )
					) { 
					//If this checkbox or dropdown is 'other' classed,
					//AND If there exists ONE object whose 'replacingin' attribute is set to this item's ID
					//AND if the aformentioned matching object's value is larger than 0,
					
					//Use the contents of the matching replacingin input instead of this checkbox's.
					concatenations[whichConcat][boo] = $("[replacingin=" + $(this).attr('id') + "]").val();
				} else {
					//Otherwise, stick with what we got and put it into the array of selected values.  (this will be the usual case.)
					concatenations[whichConcat][boo] = $(this).val();
					
				}
				//Alert what the value stored in the concatenation field is
				//alert ( concatenations[whichConcat][boo] );
			});
			//Now that we have a list of all the selected options, join them into comma separated values and
			//	put it into the field of the form that pertains to the question.
			$(this).val(concatenations[whichConcat].join(', '));
			//alert ($(this).val() );
		});
		
		$('input#completeButton').attr("disabled","true");
		$('div#processingButton').text("Sending Form Data.");
		$('form#attorneyForm').addClass('processing');
		
		var useURL = '/send-data/' ;
		
		$.ajax({
			type: 'GET', url: useURL + '?' + $('form#attorneyForm').serialize() + "&time=" + new Date().getTime(),
			dataType: 'JSON', data: {}, async: true, 
			success: function(response) {
				$('form#attorneyForm').removeClass('processing');
				if (response == 'success') {
					$('div#processingButton').text("Submitted successfully-- thanks!");
					$('form#attorneyForm').addClass('complete');
					$.get('/forms/-thankyou.html',function (response) { $('form#attorneyForm div#steps').after(response); return true; } ,'html');
					var urlAddText = '?' + ((location.href.indexOf("?") > 0) ? location.href.substring(location.href.indexOf("?") + 1) + '&' : '' ) + 'form=thanks' + '&aop=' + $('select#aopIssue').serialize() ;
					pageTracker._trackPageview(location.pathname + urlAddText );
//					location.href = location.href.substring(0,location.href.indexOf("?")) + (location.href.indexOf("?") > 0 ? location.href.substring(location.href.indexOf("?")) + '&form=thanks' : '?form=thanks') ;
					return true;
				} else {
					alert ("While attempting to submit your Lawyer Request Form, \n we encountered an error.  Normally, we check everything to prevent this from happening.  \n  Could you please review your form and try again, or possibly try later?  \n");
					$('input#completeButton').removeAttr("disabled");
					$('div#processingButton').css("display","none");
					return false;
				}
				return false;
			}
		});
		
		
		return false;
	};
	
	/*
		Simple lead submitting for 
		
	*/
	function leadRequestSubmit(form) {
	
		$('button#formSubmit').attr("disabled","true").text("Sending..");
		$('form#joinUsForm').addClass('processing');
		
		var useURL = '/request-leads/' + ( $.getUrlVar('changeTheSiteTo') ? '?changeTheSiteTo=' + $.getUrlVar('changeTheSiteTo') : '' ) ;
		
		$.ajax({
			type: 'POST', url: useURL,
			dataType: 'json', data: $('form#joinUsForm').serialize() , async: true, 
			success: function(response) {
				$('form#joinUsForm').removeClass('processing');
				if (response[0] == 1) {
					$('button#formSubmit').text("Thank You!");
					$('form#joinUsForm').addClass('complete');
					var urlAddText = '?' + ((location.href.indexOf("?") > 0) ? location.href.substring(location.href.indexOf("?") + 1) + '&' : '' ) + 'networkJoin=thanks' ;
					pageTracker._trackPageview(location.pathname + urlAddText );
					return true;
				} else {
					$('button#formSubmit').text("Send Request").removeAttr('disabled');
					alert ("While attempting to submit your Lead Inquiry Form, \n we encountered an error.  Normally, we check everything to prevent this from happening.  \n  Could you please review your form and try again, or possibly try later?  \nOur error was: " + response[1] );
					return false;
				}
				return false;
			}
		});
	
		return false;
	}
	
	
	
	// Now, add the custom validator methods.
	// SPARE DATA.
	//This method handles pagination.
	$.validator.addMethod("pageRequired", function(value, element) {
		var $element = $(element);
		function match(index) {
			//Return true IF:
			//	The active step matches the step's contents that we are evaluating, and
			//	If the element we intend to look at is within both the user's active step & the step we are evaluating.
			return (currentStep == index) && $(element).parents("#step" + index ).length ;
		}
		for (var loopor = 1; loopor <= totalSteps ; loopor++) {
			if (match(loopor)) {
				//If this is an element that is relevant to the step we need to validate,
				//Return false if this item is optional, and true if it's not optional.
				return !this.optional(element);
			}
		}  
		//If we exit the loop here, it implies that the element that was observed
		//is not relevant to the active step.
		return "dependency-mismatch";
	}, $.validator.messages.required);

	$.validator.addMethod("nameField", function(value,element) {
		var re = new RegExp(/^[-'a-zA-Z. ]+$/);
		return this.optional(element) || re.test(value);
	}, "Only letters and spaces");
	
	$.validator.addMethod("phone", function(value,element) {
		if (value != 'do not call') {
			var re = new RegExp(/^(1[-\.]?)?(\([2-9]\d{2}\)|[2-9]\d{2})[-\.]?[2-9]\d{2}[-\.]?\d{4}$/);
			return this.optional(element) || (value.length > 9 && re.test(value));
		} else {
			return true;
		}
	}, "Valid US number, please.");
	
	$.validator.addMethod("zipcode", function(value,element) {
		if (this.optional(element)) { 
			return this.optional(element);
		} else {
			if (value.length == 5 && (value - 0) == value ) {
				//the Zip Code is numeric, now do a final check.
				if ($('input#zipMatch').val() != value) {
					
					$("input#stateHidden").val('');
					$("input#cityHidden").val('');
					$('input#zipMatch').val('');
					
					$.lookupZipCode($(element).val(), function(data) {
						$('input#zipMatch').val(value);	//The query was successful-- at least make the validator rely upon blank city/state values.
						if ((data.city != "null") && (data.state != "null")) {  //The zip code is valid-- set city and state to show field is valid.
							$("input#stateHidden").val(data.state.toUpperCase() );
							$("input#cityHidden").val(data.city);
						}
						$(element).valid();
						$("input#zipMatch").valid(); //Unnecessary, but left in case it is.
						return ((data.city != "null") && (data.state != "null"));
					});
					
					return false;
					
				}
				return ($('input#cityHidden').val() != '') && ($('input#stateHidden').val() != '');
				
			}
			return false;
		}
		return false;
	}, "Valid US Zip, please.");
	
	$.validator.addMethod("other", function(value,element) {
		var re = new RegExp(/^[-a-zA-Z0-9=`~!@#$^*()+= {}|;:'",<.>?\\\[\]\/\n\r]+$/);
		return this.optional(element) || re.test(value);
	}, "No %, &, or _ allowed.");
	
	return false;
});











/** 
 * Really simple wrapper around geonames.org's postalcode service.
 *
 * @author Rob Hurring <robert.hurring@lexisnexis.com>
 * @revision 20100518001 by Nathan Bedrick <nathan.bedrick@buyerzone.com>
 * @revision 20101123001 by Nathan Bedrick <nathan.bedrick@buyerzone.com>
 * @copyright 2009 LexisNexis Martindale-Hubbell
 *
 **
 * TODO: handle errors better
 */
(function($)
{
	$.extend({
	lookupZipCode: function(zipCode, callback) {
		zipCode = zipCode.replace(/[^0-9]/g, '').substr(0, 5);
		var callbackStatus = false;
		$.ajax({
			type: 'GET', url: "http://www.attorneys.com/geo_zip/get/" + escape(zipCode) + "/?callback=?",
			dataType: 'json', data: {}, async: true,  //automatically set to true since it's cross-domain, anyways.
			success: function(response) {
				var place = null;
				try {
					var details = response.postalCodes[0];          
					place = {
						"zipCode": zipCode,
						"state": details.adminCode1,
						"state_name": details.adminName1,
						"city": details.placeName,
						"country": details.countryCode,
						"county": details.adminName2,
						"point": {"lat": details.lat, "lng": details.lng}
						};
				} catch(error) {
					if(console)
						console.log(error);
				}
				callbackStatus = callback(place);
				return callbackStatus;
			}
		});
		return callbackStatus;
	}});
})(jQuery);

//URLParameters-retrieving function.
//Retrieved from: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
	var returnVal = $.getUrlVars()[name];
    return ( returnVal ? returnVal : false) ;
  }
});

function restartForm(newVal) {
	currentStep = 1;
	$('div#bottomQs div#stepStatus span#currStep').text(currentStep);
	$('select#aopIssue').val(newVal);
	$('select#aopIssue').trigger('change');
	$('form#attorneyForm div#gratitude').remove();
	$('form#attorneyForm div#steps div#step1').show();
	$('form#attorneyForm').removeClass('complete');
	return true;
}

function goToForm(whichVal) {
	var urlAddText = '?' + ((location.href.indexOf("?") > 0) ? location.href.substring(location.href.indexOf("?") + 1) + '&' : '' ) + 'aCallToAction=clicked&aop=' + whichVal ;
	pageTracker._trackPageview(location.pathname + urlAddText );
	$('li#formID a').trigger('click');
	return restartForm(whichVal);
}
