/**
 * plenty of show/hides and actions for the forms page "request quote form"
 **/

var d = new Date();
var curYear = d.getFullYear();
var currentTab = $(".ui-tabs-nav li:first");
var requestForm = $("#form_quoteRequest");
var totalSteps = $("#form_quoteRequest fieldset").length;
//var calcMessage = $(".calculatorMessage");
var errors = false;

// replace all jquery messages with short reqired message
jQuery.each(jQuery.validator.messages, function(i) {
	jQuery.validator.messages[i] = "required*";
});

// used to scroll to the top of the form inbetween steps
function scrollToTop(){
	setTimeout("$(document.window).scrollTo( '#form_quoteRequest', {duration:500} );", 200);
}

// check value to see if it is numeric
function isNumeric(sText) {
	var validChars = "0123456789.";
	var isNumber=true;
	var myChar;

	for (i = 0; i < sText.length && isNumber == true; i++) { 
		myChar = sText.charAt(i); 
		if (validChars.indexOf(myChar) == -1) {
			isNumber = false;
		}
	}	
	return isNumber;
}

//make sure inputs are numbers, all chars that arent numbers return 0
function cleanNumericInput(x) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if( !regExpr.test(x) ) {
      // Case of error
      return 0;
    }
    return parseFloat(x);
}

// make sure all averages work out equal
function validateCalculator() {
	//check to see if the totals = avg
	var avgOutput = parseInt( $("#avg_output span").text() );
	var activitiesTotal = parseInt( $("#participantTable tfoot .tot").text() );
	var teamsTotal = parseInt( $("#ageBreakdownTable tfoot .tot").text() );	
	errors = false;
	
	//--activitiesTotal errors
	if( avgOutput != activitiesTotal ) {
		$('.activitesMSG').addClass("calcError").html("Please ensure your <b style='font-size:1.2em;'>average monthly participant <em>activities</em></b> total equals your average participants per month!");
		errors = true;
	} else {
		$('.activitesMSG').removeClass("calcError").empty();
	}
	
	//--teamsTotal errors
	if( avgOutput != teamsTotal ) {
		$('.teamsMSG').addClass("calcError").html("Please ensure your <b style='font-size:1.2em;'>average monthly participant <em>ages</em></b> total equals your average participants per month!");
		errors = true;
	} else {
		$('.teamsMSG').removeClass("calcError").empty();
	}
	
}

/**
 * cloneAndInsert (num, whereToInsert)
 * Clones the last <num> entries of 'this' (best if used with lists)
 * Then takes the clones, and increments the name field of each form input element & label (assuming attribute name=<name><#>)
 * Finally inserts after <whereToInsert>
 * */
$.fn.cloneAndInsert = function(num, whereToInsert) {
	var start = $(this).length - num;
	return $(this)
			//select the last nth elements before 'this'(aka the add button container)
			.slice( start , $(this).length )
			//duplicate the element with events attached to it
			.clone(true)
			//find all fields with inputs(input, & textbox) to be manipulated
			.find(":input:not([type=button])")
				.each(function() {
					//zero out the value and increse the input's name by 1
					if( $(this).attr("type") == "text" ){
						$(this).val("");
					}
					
					var name = $(this).attr("name");
					var number = parseInt( name.substring( name.length-1, name.length ) );
					name = name.substring(0, name.length-1)+(number+1);
					$(this).attr("name", name);
					$(this).siblings("label").attr("for", name);
				})
			.end()
			//now that all the new items have been cleaned and made unique, insert them.
			.insertAfter( whereToInsert );
}

/**
 * used to insert a temporary form around an element for step validation
 * this function will:
 * 		wrap this object (whatever element your using as a step_content-container) in a temp form
 * 		validate with options from validationOptions(takes same arguments as jquery.validate plugin)
 * 		check if validation has passed
 * 		remove temporary form and move to next step.
 */
$.fn.validateStep = function (validationOptions, stepNum){
	var stepObj = $(this);
	var tempFormID = "tmpForm";	

	//remove the temp form
	$(this).removeTempForm(tempFormID);

	//wrap the form and recheck
	stepObj.wrap('<form id="'+tempFormID+'"></form>');
	
	//alert("before the validate plugin init on #"+tempFormID);
	var v = $("#"+tempFormID).validate(validationOptions)
	
	if( v.form() ) {
		//remove the temp form
		$(this).removeTempForm(tempFormID);
		
		//Proceed to next tab
		$("#form_quoteRequest").tabs("enable", parseInt(stepNum) );
		currentTab = currentTab.next();
		currentTab.children().filter("a:first").click();
	} else {
		//var elementsBeforeLength = $(this).prevAll().length + 2;
		//for(var i=elementsBeforeLength; i < (totalSteps); i++) {
		//	requestForm.tabs('disable', i);
		//}
	}

}

/**
 * used to insert a temporary form around an element for step validation
 * this function will:
 * 		check to see if the tempForm is there
 * 		insert the content from this object (whatever element your using as a step_content-container) before the tempForm
 * 		remove the temp form
 */
$.fn.removeTempForm = function(tempFormID) {
	//check if we can remove the tempFormElement
	if( $("#"+tempFormID).length ) {
		//insert this element before the temp form
		$(this).insertBefore("#"+tempFormID);
		//Finally, remove the temp form.
		$("#"+tempFormID).remove();
		return true;
	}
	return false;
}

/**
 *	When DOM READY
 **/
$(document).ready(function() 
{
//first check if form exists
if( requestForm.length ) {
//===vars available for the form
	var previous, next;
//===javascript styling & plugin init
	//style all radio buttons
	$("input[type=radio]").addClass("radioButton");
	$("input[type=checkbox").addClass("checkBox");
	
	//init tabs

	requestForm.tabs( {
		panelTemplate: '<fieldset></fieldset>',
		disabled: [1,2,3,4,5]
	});
	
	//date picker
	$(".datepicker").datepicker();

	//to reset each step at the top of the form just call toTop.click()
	//the form comes with an <a href="#toTop"></a> and an <a name="toTop"></a>
	var toTop = $("#toTop");

//===events	
	//---reset current tab if the tab navigation is clicked
	$(".ui-tabs-nav li a").click(function() {
		//make sure the disabled state or the current selected state aren't included in the event
		if( !$(this).hasClass("ui-state-disabled") || !$(this).hasClass("ui-state-active")) {
			currentTab = $(this).parent();
			$("input[name=currentTab]").val(currentTab);
		}
	});

	//---previous Button actions
	$(".btn_prev").click(function() {
		//set current tab back a step
		currentTab = currentTab.prev();
		//trigger new currentTab
		currentTab.children().filter("a:first").click();
	});

	//---general show hide for an "I am interested in..." checkbox
	// the change at the end triggers the event incase you've already answered yes to it and refreshed
	$(".answerWithDetails").change(function(){
		if( $(this).is(":checked") ) {
			$(this).parent().next("li").slideDown(300);
		} else {
			$(this).parent().next("li").slideUp(300);
		}
	})
	.blur(function (){$(this).trigger("change");})
	.click(function (){$(this).trigger("change");});

	//---general show hide a nested yes/no "I am interested in..." checkbox
	// the change at the end triggers the event incase you've already answered yes to it and refreshed
	$(".answerWithDetails2").change(function(){
		if( $(this).val() == "yes" ) {
			$(this).siblings(".followUpQuestion").slideDown(300);
		} else {
			$(this).siblings(".followUpQuestion").slideUp(300);
		}
	})
	.blur(function (){$(this).trigger("change");})
	.click(function (){$(this).trigger("change");});

	//TODO: seperate events in to their respective steps
	// it can then load actions based on what is the current step to save processing / load times


//------step 1 events
	//check the current year, compair it to whats in the date the business started, if >3, provide resume
	$("input[name=business_StartYear]").keyup(function(){
		var yearsInBusiness = curYear - parseInt( $(this).val() );
		if( yearsInBusiness < 3 ) {
			$("#businessOwnerResume").slideDown(300);
		} else {
			$("#businessOwnerResume").slideUp(300);
		}
	}).blur(function(){$(this).trigger("keyup");});

	//check if business type is "other"
	$("input[name=business_Type]").change(function() {
		if($("input[name=business_Type]").filter(":checked").val() == "other" ) {
			$(this).siblings().filter("input[type=text]").show();
		} else {
			$(this).siblings().filter("input[type=text]").hide();
		}
	});	

	//if the first option is chosen, they are new
	//if the last option is chosen, they are renewing
	// so show the appropriate 
	$("select[name=business_ApplicationType]").change(function() {
		if ( $(this).val() == "I am a new applicant with SIS" ) {
			$(this).parent().next("li").slideDown(300);
		} else {
			$(this).parent().next("li").slideUp(300);
		}
	});

	//remove the previous li's
	$("input[name=removeLocation]").live("click",function(){
		var removeButtonLi = $(this).parent();
		for(var i=0; i < 6; i++) {
			removeButtonLi.prev().remove();
		}
		//if this is the only add / remove button, dont delete it, just change it to an add button
		if( $("#businessFacilities ul li").length > 1){
			removeButtonLi.remove();
		} else {
			$(this).attr({name: "addLocation"}).val("Add Location");
		}
	});

	//add the previous li's(representing the 4 fields needed for an injury report)
	$("input[name=addLocation]").live("click",function() {
		$("#businessFacilities ul li").cloneAndInsert(7, "#businessFacilities ul li:last-child");
		$(this).attr({name: "removeLocation"}).val("Remove Location");
	});
	
//// set facilities address fields to mailing fields if they are blank
	$('#businessFacilities input[name=businessFacility_Address1]').focus( function(){
		if( $(this).val() == "" ) {
			$(this).val( $('input[name=business_Address]').val() );
		}
	});
	
	$('#businessFacilities input[name=businessFacility_City1]').focus( function(){
		if( $(this).val() == "" ) {
			$(this).val( $('input[name=business_City]').val() );
		}
		
		var bs_selected_val = $('select[name=business_State] :selected').val();
		var bfs_obj = $('#businessFacilities select[name=businessFacility_State1]');
		var bfs_selected_obj = bfs_obj.find("option:selected");
		
		//fill state along with city
		if( bfs_selected_obj.val() == "" ) {
			bfs_obj.find('option:contains('+bs_selected_val+')').attr( "selected", "selected" );
		}
	});
	
	$('#businessFacilities input[name=businessFacility_Zip1]').focus( function(){
		if( $(this).val() == "" ) {
			$(this).val( $('input[name=business_Zip]').val() );
		}
	});

	
//------step 2 events

	
//------step 3 events
	//change the type of proof and show dates if event
	$(".insuranceAdditionalProof option").live("click",function(){
		
		if( $(this).val() == "Event")
		{
			$(this).parent().parent().next(".insuranceEventDate").show();
		} else {
			$(this).parent().parent().next(".insuranceEventDate").hide();
		}
	}).live("blur", function(){$(this).trigger("click");});
	
	//remove Proof
	$("input[name=removeProof]").live("click",function(){
		var removeButtonLi = $(this).parent();
		
		for(var i=0; i < 9; i++) {
			removeButtonLi.prev().remove();
		}
		//if this is the only add / remove button, dont delete it, just change it to an add button
		if( $("#insuranceAdditionalProofEntries ul li").length > 1){
			removeButtonLi.remove();
		} else {
			$(this).attr({name: "addProof"}).val("Add Another");
		}
	});	
	//add Proof
	$("input[name=addProof]").live("click",function() {
				
		$("#insuranceAdditionalProofEntries ul li")
			.cloneAndInsert(10, "#insuranceAdditionalProofEntries ul li:last-child")
			//reset all datepckers
			.find(".datepicker")
				.removeAttr("id")
				.removeClass("hasDatepicker")
				.datepicker();			
		$(this).attr({name: "removeProof"}).val("Remove Entry");
	});

	
	//remove Injury
	$("input[name=removeInjury]").live("click",function(){
		var removeButtonLi = $(this).parent();
		for(var i=0; i < 4; i++){
			removeButtonLi.prev().remove();
		}
		//if this is the only add / remove button, dont delete it, just change it to an add button
		if( $("#insuranceInjuries ul li").length > 1 ){
			removeButtonLi.remove();
		} else {
			$(this).attr({name: "addInjury"}).val("Add Injury");
		}
	});
	//add Injury
	$("input[name=addInjury]").live("click",function() {
		$("#insuranceInjuries ul li")
			.cloneAndInsert(5, "#insuranceInjuries ul li:last-child")
			//reset all datepckers
			.find(".datepicker")
				.removeAttr("id")
				.removeClass("hasDatepicker")
				.datepicker();			
		$(this).attr({name: "removeInjury"}).val("Remove Injury");
	});
	
	
//------step 4 events

	//---events for adding dynamic form elements
	$("input[name=addEvent]").live("click",function() {
				
		$("#Events li").cloneAndInsert(10, "#Events li:last-child");		
		$(this).attr({name: "removeEvent"}).val("Remove Event");
	});	
	
	$("input[name=removeEvent]").live("click",function() {
		var removeButtonLi = $(this).parent();
		
		for(var i=0; i < 9; i++) {
			removeButtonLi.prev().remove();
		}

		//if this is the only add / remove button, dont delete it, just change it to an add button
		if( $("#Events li").length > 1){
			removeButtonLi.remove();
		} else {
			$(this).attr({name: "addEvent"}).val("Add Another");
		}
	});

	
//------step 5 events

	//---Monthly average calculator - each of the inputs represents a month
	//---so total all inputs and average ( total / 12months )
	$("#monthlyAvgCalc .month input").keyup( function() {
		var total = 0;
		$("#monthlyAvgCalc .month input").each( function() {
			if( $(this).val() != "" ) {
				total = parseInt( $(this).val() ) + total;
			}
		});

		// ensure we do not divide by zero
		total = (total == 0) ?  0 : Math.round( (total/12) );
		
		$("#monthlyAvgCalc #avg_output span").empty().text(total);
		$("#monthlyAvgCalc input[name=avg_output]").val(total+" average participants per month");
		
		//if the monthly calc changes, you must do all checks to the participant table to make sure they are still equal
		//$("#participantTable tbody .col2 input").keyup();
		
	}).keyup();
	
	//For totals of the 2nd and 3rd column (18 under column)
	$("#participantTable tbody .col2 input, #participantTable tbody .col3 input").keyup( function(){
		
		var className = $(this).parent().attr("class");
		var total1 = 0;
		var total2 = 0;
		var thisVal = ( $(this).val() == "" && isNumeric($(this).val()) ) ? 0 : $(this).val();
		var thisName = $(this).attr("name");
		
		//make sure to count blank inputs as zeros and total all fields in column2
		$("#participantTable tbody .col2 input").each( function(){
			var value = ( $(this).val() == "" ) ? 0 : $(this).val();
			total1 = total1 + parseInt( value );
		});
		//replace the sub-total in DOM
		$("#participantTable tfoot  .col2 span").empty().text(total1);
		
		//make sure to count blank inputs as zeros and total all fields in column3
		$("#participantTable tbody  .col3 input").each( function(){
			var value = ( $(this).val() == "" ) ? 0 : $(this).val();
			total2 = total2 + parseInt( value );
		});		
		//replace the sub-total in DOM
		$("#participantTable tfoot .col3 span").empty().text(total2);
		
		//replace the total in DOM
		$("#participantTable tfoot .tot").empty().text( total1 + total2 );
		
		//used for show/hide of the 'other' subquestions
		function tableShowHide(thisVal, x) {
			if( thisVal != 0 && thisVal != "" && thisVal != "0" ) {
				$(x+"").show();
			} else {
				$(x+"").hide();
			}
		}
		
		//Specific tableshowhide cases
		if( thisName == "cheer_1a" || thisName == "cheer_1b" ||	
			thisName == "cheer_2a" || thisName == "cheer_2b" || 
			thisName == "gymnastics_1a" || thisName == "gymnastics_1b" || 
			thisName == "dance_1a" || thisName == "dance_1b") {
				
				var topVals = 0;
				var count = 0;
				$("#participantTable tbody input").each( function() {
					if(count < 8) { 
						var value = cleanNumericInput( $(this).val() );//( thisVal = "" ) ? 0 : parseInt( $(this).val() );
						topVals = topVals + value;
						count += 1;
					}
				});
				
				if( topVals > 0){	$( "#eventSubQuestions").show();} 
				else { 	$( "#eventSubQuestions").hide();};
		}
		if( thisName == "martialArts_1a" || thisName == "martialArts_1b" ) {			
			tableShowHide(thisVal, "#martialArtSubQuestions");			
		}
		if( thisName == "otherActivities_1a" || thisName == "otherActivities_1b" ) {
			tableShowHide(thisVal, "#otherSubQuestions");			
		}
		if( thisName == 'swimming_1a' ||  thisName == 'swimming_1b' ) {			
			tableShowHide(thisVal,"#swimmingSubQuestions");
		}
		
		//make sure all the monthy totals are correct
		validateCalculator();
		
	});
	//init rows
	$("#participantTable tbody .col2 input:first-child").keyup();
	$("#participantTable tbody .col3 input:first-child").keyup();


	//for the age break down of team vs NON team participants
	$("#ageBreakdownTable tbody .col2 input, #ageBreakdownTable tbody .col3 input").keyup( function(){		
		var className = $(this).parent().attr("class");
		var total1 = 0;
		var total2 = 0;
		var thisVal = ( $(this).val() == "" && isNumeric($(this).val()) ) ? 0 : $(this).val();
		var thisName = $(this).attr("name");
		
		//make sure to count blank inputs as zeros and total all fields in column2
		$("#ageBreakdownTable tbody .col2 input").each( function(){
			var value =( $(this).val() == "" ) ? 0 : $(this).val();
			total1 = total1 + parseInt( value );
		});
		$("#ageBreakdownTable tfoot .col2 span").empty().text(total1);
		
		//make sure to count blank inputs as zeros and total all fields in column3
		$("#ageBreakdownTable tbody .col3 input").each( function(){
			var value = ( $(this).val() == "" ) ? 0 : $(this).val();
			total2 = total2 + parseInt( value );
		});
		$("#ageBreakdownTable tfoot .col3 span").empty().text(total2);
			
		//replace the sub-total in DOM
		var colOneTot = cleanNumericInput( total1 );
		var colTwoTot = cleanNumericInput( total2 );
		$("#ageBreakdownTable tfoot .tot").empty().text( total1 + total2 );
		
		validateCalculator();
		
	}).keyup();
	$("#ageBreakdownTable tbody .col2 input").keyup();
	$("#ageBreakdownTable tbody .col3 input").keyup();

	$("#eventType option").live("click", function(){
		var condQuestions = $(this).parent().parent().siblings()
		switch( $(this).val().toLowerCase() ) {
			case "dance":
				//console.log( "show dance questions" );
				condQuestions.next(".gymCheerSubQuestions").hide();
				condQuestions.next(".danceSubQuestions").show();
				break
			case "gymnastics":
			case "cheer":
				//console.log( "show gym and cheer questions" );
				//console.log( $(this).val() );
				condQuestions.next(".danceSubQuestions").hide();
				condQuestions.next(".gymCheerSubQuestions").show();
				break;
			default:
				//console.log( "show default questions" );
				condQuestions.next(".danceSubQuestions").hide();
				condQuestions.next(".gymCheerSubQuestions").hide();
			break;
		}
	});



//====Form Submit Actions		
	//---for going from step2 -> step3
	var formOption1 = {
		rules: {
			business_Name: "required",
			business_Owner: "required",
			business_StartYear: "required",
			business_Address: "required", business_City: "required", business_State: "required", business_Zip: "required"
		},
		submitHandler: function(form) {	return false; }
	}
	
	//---for going from step1 -> step2
	var formOption2 = {
		rules: {
			contact_Name: "required",
			contact_Email: "required",
			contact_Position: "required",
			contact_PhoneNum: "required"
		},
		submitHandler: function(form) {	return false; }
	}
	//---for going from step3 -> step4
	var formOption3 = {
		rules: {
			insurance_Injury: "required"
		},
		submitHandler: function(form) {	return false; }
	}
	//---for going from step4 -> step5
	var formOption4 = {
		rules: {
			general_q02: "required",
			general_q03: "required",
			general_q04: "required",
			general_q05: "required",
			general_q06: "required",
			general_q07: "required",
			general_q08: "required",
			general_q09: "required",
			general_q10: "required",
			general_q11: "required",
			general_q12: "required",
			general_q13: "required",
			general_q14: "required",
			general_q15: "required",
			general_q16: "required",
			general_q18: "required",
			general_q19: "required",
			general_q20: "required",
			general_q21: "required",
			general_q21a: "required"
		},
		submitHandler: function(form) {	return false; }
	}
	//---for going from step5 -> step6
	var formOption5 = {
		rules: {
			jan: "required",
			feb: "required",
			mar: "required",
			apr: "required",
			may: "required",
			jun: "required",
			jul: "required",
			aug: "required",
			sept: "required",
			oct: "required",
			nov: "required",
			dec: "required",
			event_q01:"required",
			abuse_q01:"required",
			abuse_q02:"required",
			abuse_q03:"required",
			abuse_q04:"required",
			abuse_q05:"required"
		},
		submitHandler: function(form) { return false; }
	}
	
	//---button located in step 1 and a user wants to  move to step2
	$("#form_quoteRequest input[name=toStep2]").click(function() {
		//declare the options to use then which step to proceed
		$("#step1").validateStep(formOption1, 1);
		scrollToTop();
		return false;
	});
	
	//---button located in step 2 and a user wants to  move to step3
	$("#form_quoteRequest input[name=toStep3]").click(function() {
		$("#step2").validateStep(formOption2, 2);
		scrollToTop();
		return false;
	});

	//---button located in step 3 next button action to move to step 4
	//---no validation necessary
	$("#form_quoteRequest input[name=toStep4]").click(function() {
		$("#step3").validateStep(formOption3, 3);
		scrollToTop();

		return false;
	});
	
	//---button located in step 4 next button action to move to step 5
	//---no validation necessary
	$("#form_quoteRequest input[name=toStep5]").click(function() {
		//declare the options to use then which step to proceed
		$("#step4").validateStep(formOption4, 4);
		scrollToTop();
		return false;
	});
		
	//---button located in step 5 next button action to move to step 6
	//---no validation necessary
	$("#form_quoteRequest input[name=toStep6]").click(function() {
		
		
		if( errors ) {
			alert("Please double check your Average monthly student enrollment, Average Monthly Participant Activities, and Average Monthly Participant Ages to make sure the totals for each are equal.");
		} else {
			$("#step5").validateStep(formOption5, 5);
			/*
			$('#form_quoteRequest').tabs('enable', 5);
			currentTab = currentTab.next();
			currentTab.children().filter("a:first").click();
			*/
		}
		scrollToTop();
		return false;
	});	
	
	//check the form before submitting with this - this is validation of the FORM, not a section
	// the only thing that needs to be checked at this point is the
	function checkSubmission(){
		var agreementErrors = '';		
		
		if ($("input[name=userAgreement]:checked").val() != "yes") {
			agreementErrors += '<strong>PLEASE ACCEPT THE USER AGREEMENT TO CONTINUE!</strong>';
		}
		if ($("input[name=userAgreementName]").val() == "") {
			agreementErrors += '<br/><strong>PLEASE ENTER YOUR NAME!</strong>';
		} 
		if ($("input[name=userAgreementTitle]").val() == "") {
			agreementErrors += '<br/><strong>PLEASE ENTER YOUR POSITION AT THE COMPANY YOU ARE TYRING TO INSURE!</strong>';
		}
		
		//actions to preform when there are errors
		if( agreementErrors.length > 0 ){
			$("#formErrors").empty().html( agreementErrors );
			return agreementErrors;
		}
		
		//no errors
		$("#formErrors").empty()
		return '';
	}
	
	$("#step6 input")
		.keyup( function(){	checkSubmission(); })
		.blur(  function(){ checkSubmission(); })
		.click( function(){ checkSubmission(); })
		.focus( function(){ checkSubmission(); });
	
	//---submit form
	$("#form_quoteRequest").submit( function() {
		var fe = checkSubmission();
		
		//show errors and do not submit
		if (fe.length > 0) {
			return false;
		} else {
			//submit form
			return true;
		}
	});

	
}	
});
