$(document).ready(function()
{
	// these are the array messages we will loop through in the lightbox
	var arrHDMessages = new Array();

	arrHDMessages[0]="Checking for form errors";
	arrHDMessages[1]="Contact Details";
	arrHDMessages[2]="Address Information";
	arrHDMessages[3]="Employment Status";
	arrHDMessages[4]="Loading your personal results...";

	// stolen from alexs functionality in v2/www/js/cards.js
	var i = 0;
	var strArrayLength = arrHDMessages.length;	
	
	function showHDMessageCycle()
	{
		$("#mx-cycleHDMessage").html(arrHDMessages[i]);
		if ( i <= strArrayLength )
		{
			t = setTimeout(showHDMessageCycle, 500);
		}
		else
		{
			// the last loading message has been displayed but don't close down the box, let the page do this automagically //
			//$("#mx-loadingLoansResults").fadeOut("300");
		}
		i++;	
	}

	// when we click submit, show an ajax loading image until the results come back
	$("#submit-loanForm").click(
	function ()
	{
		// Show the loading image //
		$("#mx-loadingLoansResults").show();
		showHDMessageCycle();

		$("#mx-loadingLoansResults").mxlightbox();
		$("#mx-loanResultsContainer").html('<img src="/images/ajax-loader.gif" width="42px" height="42px" /><p>Searching....</p>');
		
	}
	);


	// in case there have been errors we need to check that joint application hasn't been set to yes, if it has we need to show the extra fields
	isJointApplication ();
	previousAddressRequired ();
	isHomeOwner ();
		
	function isJointApplication ()
	{
		// if it says yes then we need to show the fields for the second applicant
		if ( $("#JointApplication").val() == 'TRUE' )
		{
			$("#mx-loansSecondApplicantDetails").css("display", "block");
		}
		// if it says no then we should hide the fields for the second applicant
		else
		{
			$("#mx-loansSecondApplicantDetails").css("display", "none");
		}
	}
	
	// show the previous address box
	function previousAddressRequired ()
	{
		// if the time at address is less than 3 years then show the previous address box
		if ( $("#TimeAtAddress").val() <= 3 && $("#TimeAtAddress").val() != '' )
		{
			//$("#mx-loansPreviousAddressBox").css("display", "block");
			$("#mx-loansPreviousAddressBox").css("display", "block");
		}
		else
		{
			$("#mx-loansPreviousAddressBox").css("display", "none");
			// clear all the previous address boxes to avoid any confusion in sending a prev address if time at address is over 3 years
			$("#PreviousHouse, #PreviousAddress1, #PreviousAddress2, #PreviousAddress3, #PreviousPostCode").val("");
		}
	}

	function showLargeForm()
	{
		$('#mx-LoanLeadFormWrapper').slideDown(300,
		function()
		{
			$.scrollTo( '#mx-LoanLeadFormWrapper', 800 );
		}
		);

		// when we change the joint application dropdown we need to check if it says yes or no
		$("#JointApplication").bind("change",
		function()
		{
			isJointApplication ();
		}
		);
	}
	
	$("#JointApplication").bind("change",
	function()
	{
		isJointApplication ();
	}
	);
	
	$("#ResidentialStatus").bind("change",
	function ()
	{
		//alert('YOU CHANGED ME! :(');
		isHomeOwner ();
	}
	);
	
	function isHomeOwner ()
	{
		//console.log( $("#ResidentialStatus").val() );
		if ( $("#ResidentialStatus").val() == 'Homeowner - Mortgage' )
		{
			//console.log("CONGRATULATIONS! ITS A HOMO");
			$("#mx-loansMortgageBalance").css("display", "block");
		}
		else
		{
			//console.log("SORRY, NO HOMO HERE");
			$("#mx-loansMortgageBalance").css("display", "none");		
		}		
	}
	
	$('#CompareLoansSubmit').click(
	function ()
		{
			// Add the LoanAmount from the short form to the main form /
			$("#LoanAmount").val( $("#LoanAmount_PrevForm").val() );
			
			$('.mx-formError').html('');
			$('#CompareLoansForm th').css('color', '#000');
			var objFormInputs = {};
			objFormInputs['IsJS'] = true;
			objFormInputs['_IsSubmit_CompareLoansForm'] = 1;
			$("#CompareLoansForm input[type='text'], #CompareLoansForm input:radio:checked, #CompareLoansForm select").each(
				function(i, val)
				{
					objFormInputs[$(this).attr('name')] = $(this).val();
				}
			);
			
			$.post('loans_test.php', objFormInputs,
				function(objReturnedData)
				{
				
					if (objReturnedData['Errors'] == '')
					{
							$('#CompareLoansSubmit').css('opacity', '0.4');
							$('#CompareLoansForm select, #CompareLoansForm input').attr('disabled', 'disabled');
							
							$('#LoanPurpose').val(objReturnedData['Inputs']['LoanPurpose_PrevForm']);
							$('#LoanTerm').val(objReturnedData['Inputs']['LoanTerm_PrevForm']);
							$('#LoanAmount').val(objReturnedData['Inputs']['LoanAmount_PrevForm']);
							$('#ResidentialStatus').val(objReturnedData['Inputs']['ResidentialStatus_PrevForm']);
							
							// if there is no residential status then we should show the residential status field,
							// else it should be hidden
							if ( objReturnedData['Inputs']['LoanPurpose_PrevForm'] != '' )
							{
								$('#LoanPurpose').css("display", "none");
								$('.mx-LoanPurpose').css("display", "none");
							}
							if ( objReturnedData['Inputs']['LoanTerm_PrevForm'] != '' )
							{
								$('#LoanTerm').css("display", "none");
								$('.mx-LoanTerm').css("display", "none");
							}
							if ( objReturnedData['Inputs']['LoanAmount_PrevForm'] != '' )
							{
								$('#LoanAmount').css("display", "none");
								$('.mx-LoanAmount').css("display", "none");
							}
							if ( objReturnedData['Inputs']['ResidentialStatus_PrevForm'] != '' )
							{
								$('#ResidentialStatus').css("display", "none");
								$('.mx-residentialStatus').css("display", "none");
							}

							showLargeForm ();
					}
					else
					{
						var strErrors = '';
						var boolPreviousPostcodeError = 'FALSE';
						jQuery.each(objReturnedData['Errors'],
							function(id, ErrorMessage)
							{
								if (id == 'Homeowner')
								{
									$('.' + id).parent().prev('th').css('color', 'red');
								}
								else
								{
									$('#' + id).parent().prev('th').css('color', 'red');
								}
								//console.log(ErrorMessage);
								$('.mx-formError').html('<p>' + ErrorMessage + '</p>');
							}
						);
					}
					// if the customer enters more than 25k and is NOT a homeowner make them aware that they won't get an exact match
					if (  objReturnedData['Inputs']['LoanAmount_PrevForm'] >= 25000 && objReturnedData['Inputs']['ResidentialStatus_PrevForm'] != 'Homeowner - No Mortgage' && objReturnedData['Inputs']['ResidentialStatus_PrevForm'] != 'Homeowner - Mortgage'  )
					{
						$('#mx-homeOwnerWarning').html('<p>Please be aware that as you are not a homeowner, it is very unlikely that you will get a loan for £25000.<br/> However by entering your details below, we may be able to help you find another loan which closely matches your requirements.</p>');
					}
				},
				'json'
			)
	
		}
	);
	
	$('.mx-CloseLoanForm').click(
		function()
		{
			$('#CompareLoansSubmit').css('opacity', '1');
			$('#CompareLoansForm select, #CompareLoansForm input').attr('disabled', '');
			$('#mx-LoanLeadFormWrapper').slideUp(300);
		}
	);

	$('.mx-fauxlink').click(
		function()
		{
			var DefinitionID = '#' + $(this).attr('id').replace('Trigger', '') + 'Def';
			//alert(DefinitionID);
			/*
				quick fix.
				on the loans page we only load the results table when somebody has applied through the form, therefore
				we create the id of the element we are clicking on AFTER the initial page and JS has loaded, so in the
				MergeHDProductsWithMXProducts class I have created some javascript which will open the lightbox to show
				the help for APR, however, the code would open two lightboxes because this code still runs so putting
				this if statement in makes sure we never open the lightbox using this JS if it's APR help we are after
			*/
			if (DefinitionID != '#APRDef' && DefinitionID != '#LoanTypeDef')
			{
				$(DefinitionID).mxlightbox();
			}
		}
	);

	$('.mx-definition').click(
		function()
		{
			$(this).mxlightbox('destroy');
		}
	);
		
	$('#mx-LoanSearchGadget').hover(
		function()
		{
			if ($('#mx-LoanLeadFormWrapper').css('display') == 'block' && $('#mx-edit-form-help').css('display') != 'block')
			{
				$('#mx-edit-form-help').fadeIn().css('zIndex', 2000);
			}
		},
		function()
		{
			t = setTimeout(
				function()
				{
					if (!$('#mx-edit-form-help').hasClass('showPopup'))
					{
						$('#mx-edit-form-help').fadeOut();
					}
				},
				1000
				);
		}
	);
	
	$('#mx-edit-form-help').hover(
		function()
		{
			$(this).addClass('showPopup');
		},
		function()
		{
			$(this).removeClass('showPopup');
		}
	);
	
	$('.mx-close-and-delete').click(
		function()
		{
			$(this).parent().slideUp(300).remove();
		}
	);
	
	$("#TimeAtAddress").change(
	function()
	{
		// call the function which opens or closes the previous address div
		previousAddressRequired ();
	}
	);
	
	$("#mx-percentagePeople").hover(
	function()
	{
		$("#mx-fullMarketResults").children().children().children("h2").effect("highlight", {}, 1000);
	}
	);

	
});

