var fieldSet = 0;
$(function(){

	// Inititlise the form field values with the title of the text field
	$("#form1 input[type='text']").each(function(){
		$(this).val($(this).attr("title"));															
	});
	
	// When focusing on a text field, clear the contents if it matches the title
	$("#form1 input[type='text']").focus(function(){
		if ($(this).val() == $(this).attr("title")){
			$(this).val('');
		}													 
	});
	
	// Repopulate field to title value if empty on leaving the field
	$("#form1 input[type='text']").blur(function(){
		if ($(this).val() == ''){
			$(this).val($(this).attr('title'));
		}													 
	});
	
	// Help Dropdown Change Funciton
	$("#form1 #Help").change(function(){
		
		var $this = $(this);
		// only change if the extra fields are different
		var fieldSet2 = getFieldSet($this.val());
		if (fieldSet2 != fieldSet) {
			fieldSet = fieldSet2;
			if ($(".dynamic-panel:visible").length > 0 )
			{
					// The callback function here defers the slide down till after the slide up has completed
					$(".dynamic-panel:visible").slideUp(function(){
						showFields(fieldSet);
					});
			}
			else
			{
				showFields(fieldSet);	
			}	
		}
	});
	
	// Form submit function
	$("#enquiry-form").submit(function(){
		// validate the fields
		
		var errors = validate();
		
		if (errors > 0) {
			$(this).addClass("dynamic-validation");
			return false;
		}
		else {
			return true;
		}
	});

	$(".dynamic-validation input").live('keyup',function(){
		var errors = validate();							  
	});
	
	$(".dynamic-validation select").live('change', function() {
		var errors = validate();
	});

});


function validate() {
	var errors = 0;
	
	var req = ["FirstName","SurName","ContactNumber","Email","Help"];
	
	if (fieldSet == 1) {
		req.push("ExistingMortgageBalance");
	}
	if (fieldSet == 1 || fieldSet == 2) {
		req.push("PropertyValue");	
	}
	if (fieldSet == 3) {
		req.push("NumberOfDebts");
	}
	if (fieldSet > 0 && fieldSet < 4) {
		req.push("LoanRequired");
	}
	
	var minlen = ["FirstName","SurName"];
	
	var settings = {
		form: $(this),
		requiredFields: req,
		validEmail: ["Email"],
		minLength: minlen
	};
	
	
	
	// clear errors initially
	$(".error-message").remove();
	$(".validation-error").removeClass("validation-error");
	
	// Validate required fields
	for( i=0; i < settings.requiredFields.length; i++) {
		var fieldId = "#" + settings.requiredFields[i];
		if ($(fieldId).val() == '' || $(fieldId).val() == $(fieldId).attr("title"))
		{
			showError($(fieldId), "Please enter " + $(fieldId).attr("title").toLowerCase());
			errors++;
		}
	}
	
	// Validate email field
	for( i=0; i < settings.validEmail.length; i++ ) {
		var fieldId = "#" + settings.validEmail[i];
		if (!validateEmail($(fieldId).val()))
		{
			// Check if error already applied to this field
			var nodeName = $(fieldId).prev().get(0).nodeName;
			if ( nodeName.toLowerCase() != "span") {
				showError($(fieldId), "Please enter a valid email");
			}
			errors++;
		}
	}
	
	// Validate Minimum Length Fields
	for( i=0; i < settings.minLength.length; i++ ) {
		var fieldId = "#" + settings.minLength[i];
		if ($(fieldId).val().length < 3 && $(fieldId).val().length > 0) {
			showError($(fieldId), "Please enter at least 3 chars");
			errors++;
		}
	}
	
	// Validate Contact Number
	var num = $("#ContactNumber").val();
	num = num.replace(/\s+/g,"");
	if (isNaN(num) || num.length < 10  || !validateUKPhoneNumber(num)) {
		var nodeName = $("#ContactNumber").prev().get(0).nodeName;
		if ( nodeName.toLowerCase() != "span") {
			showError($("#ContactNumber"), "Please enter a valid phone number");
		}
		errors++;	
	}
	
	return errors;
}

function showError(sender, msg) {
	sender.addClass("validation-error").before('<span class="error-message">'+ msg +'</span>');
}



// Function to show the appropriate extra form fields
function showFields(f) {
	switch(f)
	{
		case 1:
			$("#NumberOfDebts").hide().next().hide();
		
			$("#ExistingMortgageBalance").show().next().show();
			$("#PropertyValue").show().next().show();
			$("#LoanRequired").show().next().show();
			
			$("#extra-fields").slideDown();
			break;
		case 2:
			$("#ExistingMortgageBalance").hide().next().hide();
			$("#NumberOfDebts").hide().next().hide();
			
			$("#PropertyValue").show().next().show();
			$("#LoanRequired").show().next().show();
			
			$("#extra-fields").slideDown();
			break;
		case 3:
			$("#ExistingMortgageBalance").hide().next().hide();
			$("#PropertyValue").hide().next().hide();

			$("#NumberOfDebts").show().next().show();
			$("#LoanRequired").show().next().show();
			
			$("#extra-fields").slideDown();
			break;
	}
}
	
	function getFieldSet(val) {
		var f = 0;
		switch(val)
		{
				case "Remortgage":
					f = 1;
					break;
				case "Loan":
				case "Mortgage":
				case "Commercial":
				case "Buy to Let": 
					f = 2;
					break;
				case "Debt Consolidation":
					f = 3;
					break;
		}
		return f;
	}

