/**
 * @author Nathan Andersen
 */
/*
 * 
 * preload images
 * 
 */
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$.preloadImages("../../images/mortgageForm/nextArrow-on.png", "../../images/mortgageForm/prevArrow-on.png");
	

	/*
	 * 
	 * Set up pop-ups for helper info when a form element is hovered over with the mouse
	 * 
	 */

function setUpRows(myString) {
			$(myString).find(".formRow").each(function() {
			
			// create pop ups
			
			var popUp = $(this).find(".fsSupporting").clone();
			$(popUp).removeClass("fsSupporting").addClass("fsSupportingPopUp").hide();
			
			
			

			$(popUp).prepend('<img src="../../images/mortgageForm/arrow.png" alt="" class="arrow">');
			
			$(this).find(".fsSupporting").remove();
			$(this).prepend(popUp);
			
			// refresh variable because cloned divs don't need previous steps in this function
			popUp = $(this).find(".fsSupportingPopUp");
			
			$(this).find('input, select').focus(function() {
				
				$(popUp).show();
				
				
			});
			
			
			
			
			$(this).mouseover(function() {
			
				
				$(".fsSupportingPopUp:not('.validationError')").hide();
				
				$(popUp).show();
			});
			
				$(this).find('input, select').blur(function() {
				
				$(popUp).hide();
			});
				
		});
	} // end function setUpRow
	
	// on document ready:

$(function() {
		
		
		$("#mortgageFormTabs").tabs();
		
		
		setUpRows("#mortgageFormTabs");
	
		$("#mortgageFormTabs").fadeIn(300);
	
		
	});
	
	/*
	 * 
	 * conditional code if there is a co-borrower
	 * 
	 */
	
	$(function () { 
		
		
		
		$(".coborrowerYes").click(function() {
			turnOnCoborrower();
			});
		
			$(".coborrowerNo").click(function() {
				turnOffCoborrower();
			});
			
			$(".coborrowerNo").trigger('click');
	});	
	
	function turnOffCoborrower() {
		
		$("#coborrowerPersonalInfo").hide();
		$("#revenueSection2").hide();
		removeValidationFromCoborrower("#coborrowerPersonalInfo");
		$("#coborrowerHomeSameQuestion").hide();
		$("#coborrowersMainHome").hide();
		removeValidationFromCoborrower("#coborrowersMainHome");
		$("#investments .col1").hide();
		$("#coborrowerHealth").hide();
		$("#coborrowerMain2").trigger('click');
		
	}

	function turnOnCoborrower() {
		$("#coborrowerPersonalInfo").show(200);
		$("#coborrowerHomeSameQuestion").show();
		$("#revenueSection2").show();
		$("#investments .col1").show();
		$("#coborrowerHealth").show();
		copyValidationToCoborrower("#personalInfo");
	}
	
	function copyValidationToCoborrower(myDiv) {
		
		$(myDiv).find(".formRow").each(function(){
			
			$(this).find("input, select, textarea").each(function(){
				var Id = $(this).attr("id");
				var myClass = $(this).attr("className");
				
				var newId = "";
				
				newId = "#" + Id.substr(0,Id.length-1) + "2";
				$(newId).attr("className",myClass);
				
				
				
			});
	
		});
		
		var curCur = $("#DEFAULT_CURRENCY").val();
		// since the value of these options has the three character code in parenthesis, we'll reduce the string to just that code
		curCur = curCur.substr(curCur.length-4,3);
		
		$("#C_MONTHLY_ALIMONY_CURR_2").val(curCur);
		
		
	
	}
	
	function removeValidationFromCoborrower(myDiv) {
		
		$(myDiv).find(".formRow").each(function(){
			
			$(this).find("input").each(function(){
				
				$(this).attr("className","");
				var thisID = "#" + $(this).attr('id');
				removeValidationErrors(thisID);
				
			});
			
			
	
		});
		
		var totalErrors = showErrors();
		
	}
	
	
	/*
	 * 
	 * conditional code if coborrower does not live with borrower, display fields for coborrower's home
	 * 
	 */
	
	

	$(function() {
		
		
	
		
		
		$(".coborrowerHomeSameNo").click(function() {
			$("#coborrowersMainHome").show();
			copyValidationToCoborrower("#mainHome");
			
			var tempSelect = '<select id="C_PRINCIPLE_RES_TYPE_2" name="C_PRINCIPLE_RES_TYPE_2" size="1" class="fsField fsRequired">' +
			'<option value="co_residence_owner">Homeowner</option>'+
			'<option value="co_residence_renter">Renter</option>'+
			'<option value="co_residence_emp">Employer pays for housing</option>'+
			'<option value="co_residence_free">Housed by friends/family for free</option>'+
        '</select>';
			
			$("#C_PRINCIPLE_RES_TYPE_2").replaceWith($(tempSelect));
			
			$("#C_PRINCIPLE_RES_TYPE_2").change(function(){
			    

				removeValidationFromCoborrower("#coborrowersMainHome");
				


				
				var resType = $("#C_PRINCIPLE_RES_TYPE_2").find("option:selected").val();
				
				switch(resType) {
					case 'co_residence_owner':
						
						showHomeDivs2();
						$("#HOME_VALUE_ESTIMATE_2").attr('className','validate[required,custom[onlyNumber]]');
					break;
					case 'co_residence_renter':
						
						hideHomeDivs2();
						$("#monthlyRentPaidDiv2").show();
						$("#C_MONTHLY_RENT_2").attr('className','validate[required,custom[onlyNumber]]');
					
					break;
					case 'co_residence_emp':
						
						hideHomeDivs2();
						$("#monthlyRentPaidDiv2").hide();
					break;
					case 'co_residence_free':
						
						hideHomeDivs2();
						$("#monthlyRentPaidDiv2").hide();
					break;
					default:
					break;
				}
				
				
			});
			
			$("#C_PRINCIPLE_RES_TYPE_2").trigger('change');
			
		});
		
		
		
		// turn off the coborrower home section
		$(".coborrowerHomeSameYes").click(function() {
			$("#coborrowersMainHome").hide();
			removeValidationFromCoborrower("#coborrowersMainHome");
			$("#C_PRINCIPLE_RES_TYPE_2").replaceWith('<input type="hidden" id="C_PRINCIPLE_RES_TYPE_2" name="C_PRINCIPLE_RES_TYPE_2" value="co_residence_same">');
			

			
		});
		
		$(".coborrowerHomeSameYes").trigger('click');
		
	});
	
	/*
	 * 
	 * conditional code to show additional properties when user clicks yes to the question, do you have additional properties?
	 */
	$(function() {
		var mycount = $("#additionalPropertyCount").val();
		
			$("#additionalPropertyDiv").hide();
		
		addNumbersToHeaders();
		
		$(".additionalPropertiesYes").click(function() {
			addProperty();
		});
		
	  
		
	});
	function addNumbersToHeaders() {
		var mycount = $(".additionalProperty").size();
		
		for (var i=1; i<=mycount; i++){
			$(".additionalProperty").eq(i).find("legend .count").text(i);
			
		}
		$(".additionalProperty").find(".otherProps").hide();
		$(".additionalProperty:last").find(".otherProps").show();
		
	}
	
	function incrementIDs_and_Names(myvar) {
		var mycount = $(myvar).size();
		
		for (var i=0; i<=mycount-1; i++){
			
			$(myvar).eq(i).find(".count").text((i+1));
			$(myvar).eq(i).find("input, select, textarea").each( function () {
				
				var newName = $(this).attr("name");
				
				newName = newName.substr(0,newName.length-1) + (i+1);
				$(this).attr("name",newName);
				
				var newId = $(this).attr("id");
				
				newId = newId.substr(0,newId.length-1) + (i+1);
				$(this).attr("id",newId);
				
			});
					}
		
		$(".currency").trigger('change');
	}
	
	
	function removeProperty() {
			var mycount = $(".additionalProperty").size();
			
			mycount--;
			if (mycount <= 0) {
			 mycount = 0
			 $("#additionalPropertiesSelector").show();
			$("#additionalPropertiesSelector").find(".additionalPropertiesNo").trigger("click");

			 ;}
			 
			$("#additionalPropertyCount").attr("value", mycount);
		
			addNumbersToHeaders();
			incrementIDs_and_Names(".propertyClone");
	}
	function addProperty() {
			$("#additionalPropertiesSelector").hide();
			var mycount = $(".additionalProperty").size();
			
			
			mycount++;
			
			$("#additionalPropertyCount").attr("value", mycount);
			
		
			var currentProperty = $("#additionalPropertyDiv").clone();
			$(currentProperty).removeAttr("id");
			
			$(currentProperty).addClass("propertyClone");
			$("#clonedProperties").append(currentProperty);
			
			var curCur = $("#DEFAULT_CURRENCY").val();
			// since the value of these options has the three character code in parenthesis, we'll reduce the string to just that code
			curCur = curCur.substr(curCur.length-4,3);
			// now we set all other currency drop downs to be the same
			
			$(currentProperty).find(".currency").val(curCur);
			
			
			
			
			$(currentProperty).show();
			
			$(currentProperty).find(".remove").click(function() {
				$(currentProperty).remove();
				removeProperty();
				incrementIDs_and_Names(".propertyClone");
				$(".currency").trigger('change');
			    });
			$(currentProperty).find(".propAssVal").attr('className',"validate[required,custom[onlyNumber]]");
			$(".additionalProperty:last").find(".additionalPropertiesNo").trigger("click");
			
			$(currentProperty).find(".additionalPropertiesYes").click(function() {
				addProperty();
			});
			$(currentProperty).find("input, select, textarea").blur(function(){
				validateMe($(this));
				var totalErrors = showErrors();
			});
			setUpRows(".additionalProperty");
			
			addNumbersToHeaders();
			incrementIDs_and_Names(".propertyClone");
			
			
			
				$(currentProperty).find(".HOME_CAPITAL_OUTSTANDING input").blur(function(){
					
					var HLE = $(currentProperty).find(".HOME_LOAN_END select");
					var HLE_string = "#" + $(HLE).attr("id");
					
					var thisVal = $(this).val(); 
					if (thisVal.length < 1) {
						$(HLE).attr('className','');
						removeValidationErrors($(HLE));
						var totalErrors = showErrors();
						
					}
					else {
						$(HLE).attr('className','validate[required]');
					}
					
				});
			

			
			
	}
	
	
/*
 * 
 * self-employed conditional code
 * 
 */


$(function () {
	if ($(".selfEmployedYes").attr("checked") == "") {
		$("#selfEmployedInfo").hide();
		removeErrorsFromSection("#selfEmployedInfo");
		
	}
	
	$(".selfEmployedYes").click(function() {	
			$("#selfEmployedInfo").show(200);
		});
	$(".selfEmployedNo").click(function() {
		$("#selfEmployedInfo").hide();
		removeErrorsFromSection("#selfEmployedInfo");
		var totalErrors = showErrors();
		});
});



function removeErrorsFromSection(sectionName) {
	$(sectionName).find("input, select, textarea").each(function(){
		
		
		var thisID = "#" + $(this).attr('id');
		removeValidationErrors(thisID);
		
	});
}

/*
 * 
 * Project Info conditional code
 * 
 */


function changeProjectTab(currentProjectType){
	hideProjectSections();
	$("#projectInfo a").text(currentProjectType);
	$("#projectInfo").show();
}

function hideProjectSections() {
	$("#equityRelease").appendTo($('#projectInfoHolder'));
	$("#preApproval").appendTo($('#projectInfoHolder'));
	$("#buyToLet").appendTo($('#projectInfoHolder'));
	$("#Leaseback").appendTo($('#projectInfoHolder'));
}

function chooseProject() {
		hideProjectSections();
		
		var currentProjectType = $("#field1").find("option:selected").val();
		var currentProjectDivID = "#" + currentProjectType;
		
	switch(currentProjectType){
		case 'Unknown':
		changeProjectTab("Project Info");
		$("#currentProjectInfo").append($("#preApproval"));
		$("#preApproval").appendTo("tab-7");
		$("#preApproval").find(".fsSectionHeading").text("Project Info");
		break;
		case 'Buying your home':
		changeProjectTab(currentProjectType);
		$("#currentProjectInfo").append($("#buyToLet"));
		$("#buyToLet").find(".fsSectionHeading").text(currentProjectType);
		break;
		case 'Buy to let':
		changeProjectTab(currentProjectType);
		$("#currentProjectInfo").append($("#buyToLet"));
		$("#buyToLet").find(".fsSectionHeading").text(currentProjectType);
		break;
		case 'Leaseback':
		changeProjectTab(currentProjectType);
		$("#currentProjectInfo").append($("#Leaseback"));
		$("#Leaseback").find(".fsSectionHeading").text(currentProjectType);
		break;
		case 'Remortgage':
		changeProjectTab(currentProjectType);
		$("#currentProjectInfo").append($("#equityRelease"));
		$("#equityRelease").find(".fsSectionHeading").text(currentProjectType);
		break;
		case 'Remortgage with cash-out':
		changeProjectTab('Remortgage');
		$("#currentProjectInfo").append($("#equityRelease"));
		$("#equityRelease").find(".fsSectionHeading").text(currentProjectType);
		break;
		case 'Equity release':
		changeProjectTab(currentProjectType);
		$("#currentProjectInfo").append($("#equityRelease"));
		$("#equityRelease").find(".fsSectionHeading").text(currentProjectType);
		break;
		default:
		break;
		
	}
}

$(function (){
	var projectInfoHolder = $('<div id="projectInfoHolder" style="display: none"></div>');
	$('body').append(projectInfoHolder);
	
	
	hideProjectSections();
	chooseProject();

	
	$("#CE_ENQUIRY_TYPE").change(function() { 
	
	chooseProject();	
	});
});


/*
 * 
 * conditional code to add investments
 * 
 */
 
$(function () {
	
	$("#addInvestments").click(function(){
		var newAsset = $("#investmentTemplate").clone().removeAttr("id").addClass("investmentClone");
		$(newAsset).find(".currency").val($("#investmentTemplate").find(".currency").val());
		$("#investments").append(newAsset);
		incrementIDs_and_Names(".investmentClone");
		
			$(newAsset).find(".remove").click(function() { 
			$(this).parent().parent().parent().remove();
			incrementIDs_and_Names(".investmentClone");
			
			return false;
			
			});
		
		return false;
	});
	
	$(".investment .remove").click(function() { 
	$(this).parent().parent().parent().remove();
	incrementIDs_and_Names(".investmentClone");
	
	return false;
	
	
	});
	
});

/*
 * 
 * conditional code to add loans
 * 
 */
 
$(function () {
	
	$("#addLoan").click(function(){
		var newAsset = $("#loanTemplate").clone().removeAttr("id").addClass("loanClone");
		$(newAsset).find(".currency").val($("#loanTemplate").find(".currency").val());
		$("#loans").append(newAsset);
		incrementIDs_and_Names(".loanClone");
		
			$(newAsset).find(".remove").click(function() { 
			$(this).parent().parent().parent().remove();
			incrementIDs_and_Names(".loanClone");
			
			return false;
			
			});
			
			
			// connect home_loan_end validation to capital outstanding (see similar function below )
			$(newAsset).find(".col5 input").blur(function(){
				
				var HLE = $(newAsset).find(".col7 select");
				
				$(HLE).blur(function(){ 
					validateMe($(this)); 
					var totalErrors = showErrors();
				})
				
				var thisVal = $(this).val(); 
				if (thisVal.length < 1) {
					$(HLE).attr('className','');
					removeValidationErrors($(HLE));
					var totalErrors = showErrors();
					
				}
				else {
					$(HLE).attr('className','validate[required]');
				}
				
				
			});
			
			
		
		return false;
	});
	
	$(".loan .remove").click(function() { 
	$(this).parent().parent().parent().remove();
	incrementIDs_and_Names(".loanClone");
	
	return false;
	
	
	});
	
});

/*
 * 
 * code to handle relationship between capital outstand and end of loan for LOANS
 * 
 * NOTE: 
 *  since I'm toggling the classnames on and off, I'm not using classnames to locate the input and select, but rather context.  
 * It's a little hackish, but that's why.
 * 
 */



$(function(){
	
	$(".loan .col5 input").blur(function(){
		
		var HLE = $(this).parent().parent().find(".col7 select");
		
		
		var thisVal = $(this).val(); 
		if (thisVal.length < 1) {
			$(HLE).attr('className','');
			removeValidationErrors($(HLE));
			var totalErrors = showErrors();
			
		}
		else {
			$(HLE).attr('className','validate[required]');
		}
		
		
	});
	
});



/*
 * 
 * conditional code to add companies
 * 
 */
 
$(function () {
	
	$(".addCompany").click(function(){
		addCompany();
		
		return false;
	});
	
	
	
});

function addCompany() {
	var newAsset = $("#selfEmployedInfo").clone().removeAttr("id").addClass("companyClone");
		$(newAsset).find("input").each(function(){
			// clear the entries
			$(this).val('');
		});
		$(newAsset).find(".currency").val($("#selfEmployedInfo").find(".currency").val());
		$(newAsset).find(".fsSectionHeading").append('<a class="remove" href="#"><img alt="remove" src="/images/mortgageForm/remove.gif"/></a>');
		$("#companyClones").append(newAsset);
		incrementIDs_and_Names(".selfEmployedInfo");
		
			$(newAsset).find(".remove").click(function() { 
			$(this).parent().parent().remove();
			incrementIDs_and_Names(".companyClone");
			
			return false;
			
			});
			
			$(newAsset).find(".addCompany").click(function(){
				addCompany();
			});
}

/*
 * 
 * next button to move between tabs
 * 
 */
 
 $(function () {
 	
	
	
 	$(".nextButton").click(function(){
		$(".ui-tabs-selected").next().find("a").trigger("click");
	});
	
	$(".previousButton").click(function(){
		$(".ui-tabs-selected").prev().find("a").trigger("click");
	});
 });
 
 /*
  * 
  * conditional code for when DEFAULT_CURRENCY changes, change other currencies on the form
  * 
  */

$(function () {
	$("#DEFAULT_CURRENCY").change(function(){
		var curCur = $(this).val();
		// since the value of these options has the three character code in parenthesis, we'll reduce the string to just that code
		curCur = curCur.substr(curCur.length-4,3);
		// now we set all other currency drop downs to be the same
		$(".currency").val(curCur);
		$(".currency").trigger('change');
		
	});
});

/*
 * 
 * conditional code for properties tab drop down C_PRINCIPLE_RES_TYPE_1
 *  show or hides fields for the main home section of properties tab
 * 
 */
 function showHomeDivs() {
 			$("#homeValueEstimate").show();
			$("#mortgageLenderDiv").show();
			$("#capitalOutstandingDiv").show();
			$("#monthlyPaymentDiv").show();
			$("#endOfLoanDiv").show();
			$("#monthlyRentPaidDiv").hide();
 }
 
 function hideHomeDivs() {
 			$("#homeValueEstimate").hide(); 			
			$("#mortgageLenderDiv").hide();
			$("#capitalOutstandingDiv").hide();
			$("#monthlyPaymentDiv").hide();
			$("#endOfLoanDiv").hide();

			
 }
 
 $(function() {
 	$("#C_PRINCIPLE_RES_TYPE_1").change(function(){
 		
 	
		$("#HOME_VALUE_ESTIMATE_1").attr('className','');
		$("#C_MONTHLY_RENT_1").attr('className','');
		$("#mainHome input, #mainHome select").each(function(){
			if ($(this).attr('id') != "C_PRINCIPLE_RES_TYPE_1" && $(this).attr('className') != "currency") { 
				
				$(this).attr("value","");
				var myId = "#" + $(this).attr('id');
				removeValidationErrors(myId);
			};

		});
		var totalErrors = showErrors();
		
		var resType = $("#C_PRINCIPLE_RES_TYPE_1").find("option:selected").val();
 		
		

		switch(resType) {
			case 'residence_owner':
				showHomeDivs();
				$("#HOME_VALUE_ESTIMATE_1").attr('className','validate[required,custom[onlyNumber]]');
				

				
			break;
			case 'residence_renter':
				hideHomeDivs();
				$("#monthlyRentPaidDiv").show();
				$("#C_MONTHLY_RENT_1").attr('className','validate[required,custom[onlyNumber]]');
				
			
			break;
			case 'residence_emp':
				hideHomeDivs();
				$("#monthlyRentPaidDiv").hide();
			break;
			case 'residence_free':
				hideHomeDivs();
				$("#monthlyRentPaidDiv").hide();
			break;
			default:
			break;
		}
		
	});
	
	$("#C_PRINCIPLE_RES_TYPE_1").trigger('change');
 });

 
/*
 * 
 * conditional code for properties tab drop down C_PRINCIPLE_RES_TYPE_2
 * show or hides fields for the CO-BORROWER'S main home section of properties tab 
 * 
 * THE ACTUAL FUNCTION HAS BEEN MOVED, SO THAT IT'S BOUND WHEN THE COBORROWER HOME SECTION IS SHOWN
 * 
 * search for $("#C_PRINCIPLE_RES_TYPE_2").change(function(){
 */
 function showHomeDivs2() {
	 	    
 			$("#homeValueEstimate2").show();
			$("#mortgageLenderDiv2").show();
			$("#capitalOutstandingDiv2").show();
			$("#monthlyPaymentDiv2").show();
			$("#endOfLoanDiv2").show();
			$("#monthlyRentPaidDiv2").hide();
 }
 
 function hideHomeDivs2() {
 			$("#homeValueEstimate2").hide();
			$("#mortgageLenderDiv2").hide();
			$("#capitalOutstandingDiv2").hide();
			$("#monthlyPaymentDiv2").hide();
			$("#endOfLoanDiv2").hide();

			
 }
 

 

 /*
  * 
  *  marital status conditional code
  *  
  */
 
 
$(function() {
	$("#marriedDiv").hide();
	$("#divorcedDiv").hide();

	
	
	$("#marriedDiv2").hide();
	$("#divorcedDiv2").hide();
	
	
	$("#C_FAMILY_SITUATION_1").change(function(){
			$("#marriedDiv").hide();
			$("#divorcedDiv").hide();
		
		var famSit = $("#C_FAMILY_SITUATION_1").find("option:selected").val();

		
		switch(famSit) {
			case '':
			break;
			case 'Single':
			
			break;
			case 'Partnership':
			
			break;
			case 'Married':
			$("#marriedDiv").show();
			break;
			case 'Seperated':
			break;
			case 'Widower':
			break;
			case 'Divorced':
			$("#divorcedDiv").show();
			break;
			default:
			break;
		}
		
	});
	
	$("#C_FAMILY_SITUATION_2").change(function(){
			$("#marriedDiv2").hide();
			$("#divorcedDiv2").hide();
		
		var famSit = $("#C_FAMILY_SITUATION_2").find("option:selected").val();

		
		switch(famSit) {
			case '':
			break;
			case 'Single':
			
			break;
			case 'Partnership':
			
			break;
			case 'Married':
			$("#marriedDiv2").show();
			break;
			case 'Seperated':
			break;
			case 'Widower':
			break;
			case 'Divorced':
			$("#divorcedDiv2").show();
			break;
			default:
			break;
		}
		
		
	});
	
	$("#C_FAMILY_SITUATION_1").trigger('change');
	$("#C_FAMILY_SITUATION_2").trigger('change');
	$("#isSmokerNo").trigger('click');
});


/*
 * 
 * HOME_LOAN_END_DATE_YEAR_1 
 * 
 * is required if 
 * 
 * HOME_CAPITAL_OUTSTANDING_1 
 * 
 * is not blank
 * 
 */

$(function(){
	$("#HOME_CAPITAL_OUTSTANDING_1").blur(function(){
		var thisVal = $(this).val(); 
		if (thisVal.length < 1) {
			$("#HOME_LOAN_END_DATE_YEAR_1").attr('className','');
			removeValidationErrors("#HOME_LOAN_END_DATE_YEAR_1");
			var totalErrors = showErrors();
			
		}
		else {
			$("#HOME_LOAN_END_DATE_YEAR_1").attr('className','validate[required]');
		}
		
	})
});
