//Init 'Unobtrusive' JavaScript
addEvent(window, 'load', function() {

	//If have form
	if ($("formquote") != null) {

		//If form is being shown on the right hand side
		if ($("formtype").value == "main") {

			//Init how long property has been on market
			showhide_on_market_time();

			//Init how many viewings
			showhide_no_viewings();

			//Init what is the minimum price
			showhide_min_price();

			//Init how old is the boiler
			showhide_boiler_age();

			//On "on market" change
			//handled on the option itself

			//On cash offer change
			//handled on the option itself

			//On estimated market value change
			$("quote_market_value").onkeyup = function() {
				cashofferlabeladdin();
			};

			//Default label for "Would you consider a cash offer" label
			cashofferlabeladdin();

		} else {

			//Init which floor
			showhide_floor();

			//On property type change
			$("quote_property_type").onchange = function() {
				showhide_floor();
				showhide_ownership();
			};

			//Init ownership
			showhide_ownership();

		}

		//If form is being shown on the right hand side
		if ($("formtype").value == "main") {

			//Default to first form section showing only
			formsection(2);

		} else {

			//Default to showing second form section (user can click through to 3rd)
			//formsection(1);

			//Do nothing, the first part will always be shown if type main

		}

		$("formquote").onsubmit = function() {

			var validateupto;
			if (("formtype").value == "main") {
				validateupto = 3;
			} else {
				validateupto = 1;
			}

			//Validate form
			var status = validateform(validateupto);

			return status;

		};

		//Init form autosave
		autosave_setup();

	}

	//If have email field
	if ($("quote_email") != null) {

		//On email blur (ie email entered)
		$("quote_email").onblur = function() {

			//If email specified
			if ($("quote_email").value.length != 0) {

				//Set aweber form target to the iframe
				$("aweberfrm").target = "aweberiframe";

				//Pass the aweber form the email address
				$("aweber_from").value = $("quote_email").value;

				//Pass the aweber form the name
				$("aweber_name").value = $("quote_name").value;

				//Post data to the iframe
				$("aweberfrm").submit();

			}

		}

	}

});

//Cash offer label percentage
function cashofferlabeladdin() {

	//Find out if market value is valid
	var market_value_valid = false;
	if ($("quote_market_value").value != "") {
		if (isCurreny($("quote_market_value").value)) {
			market_value_valid = true;
		}
	}

	//If estimated market value valid
	if (market_value_valid == true) {

		if ($("quote_market_value").value < 9999999) {

			//Work out 75%
			var offer_value = ($("quote_market_value").value / 100) * offer_percent;
			offer_value = Math.round(offer_value);
			offer_value = addcommas(offer_value);

			$("consider_cash_offer_addin").innerHTML = "(i.e. &pound;" + offer_value + ") ";

		} else {
			$("consider_cash_offer_addin").innerHTML = "";
		}

	} else {
		$("consider_cash_offer_addin").innerHTML = "";
	}

}

function addcommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//Setup form autosave
function autosave_setup() {

	clearautosave();

	timeout = window.setTimeout("formautosave();", autosave_interval_sec * 1000);

}

//Clear auto save
function clearautosave() {

	if (timeout) {
		window.clearTimeout(timeout);
	}

}

//Try form auto save
var timeout
function formautosave() {

	var radio_fields = ["quote_ownership", "quote_ex_council", "quote_on_market", "quote_cash_offer", "quote_rent_back", "quote_garage", "quote_off_road_parking", "quote_kitchen_replace", "quote_bathroom_replace", "quote_gas_central_heating", "quote_electronics_uptodate", "quote_double_glazing", "quote_need_decorating", "quote_new_carpets"];

	//If there is at least a name filled in
	if ($("quote_name").value.length > 0) {

		//Compile data to autosave
		var autosavedata = "";
		for (field in fields) {

			var value;

			//If field is available (on this page)
			if ($(fields[field])) {

				//If radio
				if (in_array(fields[field], radio_fields)) {

					value = radiogetselected(fields[field]);

					if (value === false) {
						value = "";
					}

				} else {
					value = $(fields[field]).value;
				}

			} else {
				value = "";
			}

			autosavedata += "&" + fields[field] + "=" + encodeURIComponent(value);

		}

		var autosave_compiled = autosave_url + autosavedata;

		//alert(autosave_compiled);

		var pic1 = new Image(1,1);
		pic1.src = autosave_compiled + "&ts=" + new Date().getTime();

	}

	//Init form autosave
	autosave_setup();

}

//Check currency
function isCurreny(TestObj) {
	CurrenyPattern = /^([0-9]*|\d*\.\d{1}?\d*)$/;
	if( !CurrenyPattern.test(TestObj)) {return false;}
	return true;
}

//Handle form sections
var currformsection = null
function formsection(formsection_no) {

	var status;

	if ( (currformsection != null) && (formsection_no > currformsection) ) {

		//Validate form upto specified number
		status = validateform(formsection_no-1);

	} else {
		status = true;

	}

	//If ok to change
	if (status == true) {

		//Go through all form sections
		for (i=2; i <= 3; i++) {

			var section_id = "form_section_" + i;

			//If this is the selected section
			if (formsection_no == i) {

				//Show section
				$(section_id).style.display = "block";

			} else {

				//Otherwise hide section
				$(section_id).style.display = "none";

			}

		}

		currformsection = formsection_no;

		//Jump back to top of page
		document.location.href = "#headerimg";

	}

}

//Validate form
function validateform(uptosection) {

	var errormsgs = [];

	//Section 1
	if (uptosection >= 1) {

		if ($("quote_sale_reason").value == "") {
			errormsgs[errormsgs.length] = "Please select 'Reason for Sale'";
		}

		if ($("quote_name").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Name'";
		}

		if ($("quote_telephone").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Contact Number'";
		}

		if ($("quote_address").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Property Address'";
		}

		if ($("quote_postcode").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Postcode'";
		}

		if ($("quote_property_type").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Type of Property'";
		}

		if ($("quote_beds").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Number of Bedrooms'";
		}

	}

	//Section 2
	if (uptosection >= 2) {

		if ($("quote_market_value").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Estimated Market Value'";
		} else {
			if (!isCurreny($("quote_market_value").value)) {
				errormsgs[errormsgs.length] = "Please enter numbers only for 'Estimated Market Value'";
			}
		}

		var quote_cash_offer = radiogetselected("quote_cash_offer");
		if (quote_cash_offer == false) {
			errormsgs[errormsgs.length] = "Please choose if you 'Would you consider a Cash Offer'";
		} else {

			if (quote_cash_offer == 2) {

				if ($("quote_min_price").value == "") {
					errormsgs[errormsgs.length] = "Please enter 'What is the minimum price you will accept'";
				} else {
					if (!isCurreny($("quote_min_price").value)) {
						errormsgs[errormsgs.length] = "Please enter numbers only for 'What is the minimum price you will accept'";
					}
				}

			}

		}

		if ($("quote_secured_debt").value == "") {
			errormsgs[errormsgs.length] = "Please enter 'Total Secured Debt'";
		} else {
			if (!isCurreny($("quote_secured_debt").value)) {
				errormsgs[errormsgs.length] = "Please enter numbers only for 'Total Secured Debt'";
			}
		}

		if ($("quote_sell_period").value == "") {
			errormsgs[errormsgs.length] = "Please select 'How soon do you want to sell'";
		}

		//If cash offer yes or maybe
		var quote_cash_offer = radiogetselected("quote_cash_offer");
		if ( (quote_cash_offer == 1) || (quote_cash_offer == 3) ) {

			//If estimated market value valid, and total secured debt valid
			if ( (isCurreny($("quote_market_value").value)) && (isCurreny($("quote_secured_debt").value)) ) {

				//Work out 75%
				var offer_value = ($("quote_market_value").value / 100) * offer_percent;
				offer_value = Math.round(offer_value);

				//Check total debt not greater than 75% of offer value
				//if (parseInt($("quote_secured_debt").value, 10) > offer_value) {
				if ($("quote_secured_debt").value > offer_value) {
					errormsgs[errormsgs.length] = "Since your secured debt is higher than " + offer_percent + "% of the market value we will not be able to find you a cash buyer.";
				}

			} else {
				$("consider_cash_offer_addin").innerHTML = "";
			}

		}

	}

	//Section 3
	if (uptosection >= 3) {
		//None to validate
	}

	var errormsgs_all = "";
	for (i in errormsgs) {
		errormsgs_all += errormsgs[i] + "\n\n";
	}

	var status;

	if (errormsgs_all == "") {
		status = true;
	} else {
		alert(errormsgs_all);
		status = false;
	}

	return status;

}

//Hide show of form parts

function showhide_floor() {

	if ($("quote_property_type").value == 5) {
		$("floor_section").style.display = "block";
	} else {
		$("floor_section").style.display = "none";
		$("quote_floor").selectedIndex = 0;
	}

}

function showhide_ownership() {

	if ($("quote_property_type").value == 5) {
		$("ownership_section").style.display = "block";
	} else {
		$("ownership_section").style.display = "none";
		radioselect("quote_ownership", null);
	}

}

function showhide_on_market_time() {

	if (radiogetselected("quote_on_market") == 1) {
		$("on_market_time_section").style.display = "block";
	} else {
		$("on_market_time_section").style.display = "none";
		$("quote_on_market_time").selectedIndex = 0;
	}

}

function showhide_no_viewings() {

	if (radiogetselected("quote_on_market") == 1) {
		$("no_viewings_section").style.display = "block";
	} else {
		$("no_viewings_section").style.display = "none";
		$("quote_no_viewings").selectedIndex = 0;
	}

}

function showhide_min_price() {

	if (radiogetselected("quote_cash_offer") == 2) {
		$("min_price_section").style.display = "block";
	} else {
		$("min_price_section").style.display = "none";
		$("quote_min_price").value = "";
	}

}

function showhide_boiler_age() {

	if (radiogetselected("quote_gas_central_heating") == 1) {
		$("boiler_age_section").style.display = "block";
	} else {
		$("boiler_age_section").style.display = "none";
		$("quote_boiler_age").selectedIndex = 0;
	}

}

