
function checkuncheckall(name, checkbox) {
	// used for parkingtypes[] checkboxes
	e = document.getElementsByName(name);
	
	status = checkbox.checked;
	
	if (status == null) return false;
	
	for (i = 0; i < e.length; i++) {
		if (e[i].type == "checkbox") e[i].checked = status;
	}
}


function setQuickSearchPrices(s) {
	// function for changing the price search parameters for the quicksearch
	f = document.forms['quicksearchprice'];
	if (!f) {
		alert("Unable to change values");
		return false;
	}
	
	prices = s.options[s.selectedIndex].id;
	prices = prices.split(",");
	
	f.pricefrom.value = prices[0];
	f.priceto.value = prices[1];
	
	return true;
}


// replaces the quicksearch td with a quick search for price.
function changeQuickSearch() {
	td = document.getElementById('quicksearchtd');
	if (!td) {
		alert("Unable to perform search");
		return false;
	}
	
	var text = '\
	<form name="quicksearchprice" method="get" action="/search.htm">\
		<select onchange="setQuickSearchPrices(this)">\
			<option id="0,200000">Valued below &euro;200,000</option>\
			<option id="200000,350000">&euro;200,000 to &euro;350,000</option>\
			<option id="350000,550000">&euro;350,000 to &euro;550,000</option>\
			<option id="550000,1000000">&euro;550,000 to &euro;1m</option>\
			<option id="1000000,2000000">&euro;1m to &euro;2m</option>\
			<option id="2000000,9999999">&euro;2m and above</option>\
		</select>\
		<input type="hidden" name="pricefrom" value="0" />\
		<input type="hidden" name="priceto" value="9999999" />\
		<input type="hidden" name="action" value="search" />\
		<br />\
		<br />\
		<input type="image" src="/images/but-go.gif" alt="Search" title="Search" />\
	</form>\
	';
	
	td.innerHTML = text;
	
	return true;
}


/*
function toggleLocationInputs(regionid) {
	// function to invert the choice for a region's location checkboxes
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		var id = inputs[i].id.split(",");
		if (id.length == 2) {
			if (id[0] == "r"+regionid) {
				if (inputs[i].checked) {
					inputs[i].checked = false;
				}
				else {
					inputs[i].checked = true;
				}
			}
		}
	}
}
*/


function toggleLocationInputs(regionid, cb) {
	// function to invert the choice for a region's location checkboxes
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		var id = inputs[i].id.split(",");
		if (id.length == 2) {
			if (id[0] == "r"+regionid) {
				if (cb.checked) {
					inputs[i].checked = true;
				}
				else {
					inputs[i].checked = false;
				}
			}
		}
	}
}


function toggleLocationDivs(iteration) {
	// performs show/hide function on the divs which contain the checkboxes for locations within regions
	var divs = document.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) {
		var id = divs[i].id.split(",");
		if (id.length == 2) {
			if (id[0] == "regiondiv") {
				if (id[1]==iteration) {
					if (divs[i].style.display=="none") {
						divs[i].style.display="block";
						l = document.getElementById('ldpm'+iteration);
						if (l)
						{
							l.src = "/images/icons/minus_s.gif";
						}
					}
					else {
						divs[i].style.display="none";
						l = document.getElementById('ldpm'+iteration);
						if (l) {
							l.src = "/images/icons/plus_s.gif";
						}
					}
				}
				else {
					divs[i].style.display="none";
					l2 = document.getElementById('ldpm'+id[1]);
					if (l2) {
						l2.src = "/images/icons/plus_s.gif";
					}
				}
			}
		}
	}
}


function toggleAllLocations(cb) {
	// all locations checkbox function.
	// takes the checkbox as an input and adjusts all (location) checkboxes based on the current status of the all locations checkbox.
	var inputs = document.getElementsByTagName("input");
	var toggle = cb.checked;
	
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "checkbox") {
			if (inputs[i].id.match(/^r[0-9]*,l[0-9]*$/) ) {
				inputs[i].checked = toggle;
			}
		}
	}
}


function cancelAllLocations(r) {
	// change the alllocations checkbox
	al = document.getElementById("alllocations");
	if (al) {
		al.checked = false;
	}
	
	// change the 'select all' box for the region
	e = document.getElementById('all_r'+r);
	if (e) e.checked = false;
}


// toggles the google map div on the edit property page
function toggleGoogleMapDiv() {
	d = document.getElementById("googlemapdiv");
	if (!d) {
		alert("Unable to get map DIV");
		return false;
	}
	
	if (d.style.display == "block") {
		d.style.display = "none";
		return true;
	}
	else {
		d.style.display = "block";
		return true;
	}
}


// doubles or halves the input/textarea size
function changeSize(elementname, increase) {
	e = document.getElementById(elementname);
	if (!e) {
		alert("Unable to find element '"+ elementname + "'");
	}
	else {
		function calc(num, up) // calculates the change required
		{
			if (up) {
				return num*2;
			}
			else {
				if (num/2 < 1) {
					return 1;
				}
				else {
					return Math.ceil(num/2);
				}
			}
		}
		
		switch(e.type) {
			case "textarea":
				e.rows = calc(e.rows, increase);
				break;
			case "select-one":
				e.size = calc(e.size, increase);
				break;
			case "select-multiple":
				e.size = calc(e.size, increase);
				break;
			default:
				alert("Unknown type: " + e.type);
		}
	}
}


function openPopup(url) {
	window.open(url, 'aapopup');
}


function uncheckPropertyTypes(checkbox) {
	if (!checkbox.checked) return; // box isn't ticked, nothing to do
	var inputs = document.getElementsByTagName('input');
	for (i=0; i < inputs.length; i++)
	{
		if (inputs[i].type=='checkbox'  &&  inputs[i].name=='propertytypes[]')
		{
			inputs[i].checked=false;
		}
	}
}



// 3 functions found at http://www.thescripts.com/forum/thread520214.html
function hasClassName(str, className) {
	var strPadded = " " + str + " ";
	var classNamePadded = " " + className + " ";
	return strPadded.indexOf(classNamePadded) != -1;
}


function removeClassName(element, className) {
	var strPadded = " " + element.className + " ";
	var classNamePadded = " " + className + " ";
	var result = strPadded.replace(classNamePadded, "");
	result = result.substring(1, result.length - 1);
	element.className = result;
}


function addClassName(element, className) {
	var str = element.className;
	if (!hasClassName(str, className))
	{
		str += " ";
		str += className;
		element.className = str;
	}
}


function setAsHomePage(btn, title, addr) {
	if (addr == undefined) { addr = window.location.href; }
	if (title == undefined) { title = 'Alpine Angels - Properties in the French and Swiss Alps'; }
	
	if ($.browser.msie) { // this is tested with v6 and v8
		btn.style.behavior='url(#default#homepage)'; 
		btn.setHomePage(addr);
	}
	else if ($.browser.mozilla) {
		window.sidebar.addPanel(title, addr, '');
	}
	else if ($.browser.opera) {
		alert("Sorry, Opera doesn't support setting the home page.\r\n\r\nWhy not press Ctrl + D to bookmark this page instead!");
	}
	else {
		alert("Sorry, it's not possible to set the home page for your browser.\r\n\r\nWhy not try pressing Ctrl + D to bookmark this page instead!");
	}
}






/** mortgage calculator functions **/
function poundsPence(i) {
	i = new String(i);
	var pos = i.lastIndexOf('.');
	if (pos == -1) { return (i + '.00'); }
	if (pos == i.length-2) { return (i + '0'); }
	return i;
}


function calculateMortgage() {
	var price = jQuery('#purchase-price').val();
	var deposit_percentage = jQuery('#deposit-percentage').val();
	var deposit_amount = jQuery('#deposit-amount').val();
	var loan_amount = jQuery('#loan-amount').val();
	var loan_period = jQuery('#loan-period').val();
	var interest_rate = jQuery('#interest-rate').val();
	
	var rate = interest_rate / 100;
	var monthly_payment = ((loan_amount*rate)/12) * (1/(1-(Math.pow(1/(1+rate),loan_period))));
	monthly_payment = Math.round(monthly_payment*100)/100;
	monthly_payment = poundsPence(monthly_payment);
	var monthly_interest_only = (loan_amount*rate)/12;
	monthly_interest_only = Math.round(monthly_interest_only*100)/100;
	monthly_interest_only = poundsPence(monthly_interest_only);
	
	jQuery('#h_purchase_price').val(price);
	jQuery('#h_deposit_percentage').val(deposit_percentage);
	jQuery('#h_deposit_amount').val(deposit_amount);
	jQuery('#h_loan_amount').val(loan_amount);
	jQuery('#h_loan_period').val(loan_period);
	jQuery('#h_interest_rate').val(interest_rate);
	jQuery('#h_monthly_payment').val(monthly_payment);
	jQuery('#h_monthly_interest_payment').val(monthly_interest_only);
	
	jQuery('#mortgage-repayment').html('&euro;' + monthly_payment + ' pcm');
	jQuery('#mortgate-interest-repayment').html('&euro;' + monthly_interest_only + ' pcm');
	
	//return false;
}


function makeNumeric(i) {
	i = new String(i);
	i = i.replace(/[^0-9]/,'');
	if (i=='') { i=0; }
	return parseInt(i);
}


function makeFloat(i) {
	i = new String(i);
	i = i.replace(/[^0-9\.]/,'');
	if (i=='') { i=0; }
	return parseFloat(i);
}


function getInterestRate(percentage) {
	if (typeof(interest_rates) == 'undefined') {
		return false;
	}
	
	var rate = false;
	var key = false;
	for (key in interest_rates) {
		if (parseInt(key) <= percentage) { // percentage is within the boundary
			rate = interest_rates[key];
		}
	}
	
	if (rate != false) { // rate found, return
		return rate;
	}
	
	// rate not found (higher than maximum)
	alert('Sorry, the maximum loan amount is ' + key + '%');
	return false;
}


function MortgageCalculator(rates) {
	this.interest_rates = rates;
	
	this.max_rate_percent = 0;
	for (var r in rates) {
		this.max_loan_percentage = r;
	}
	
	this.setPurchasePrice = function(price) {
		price = makeNumeric(price);
		jQuery('#purchase-price').val(price);
		
		var percent = makeFloat(jQuery('#deposit-percentage').val());
		
		// update deposit amount
		var deposit = price * (percent / 100);
		jQuery('#deposit-amount').val(deposit);
		
		// update loan amount
		var loan = price - deposit;
		jQuery('#loan-amount').val(loan);
	}
	
	this.setDepositPercentage = function(percent) {
		//alert(percent);
		percent = makeFloat(percent);
		//alert(percent);
		
		// check whether a valid percentage exists
		if (percent < (100-this.max_loan_percentage)) {
			percent = (100-this.max_loan_percentage);
			alert('The minimum deposit allowed is ' + percent + '%');
		}
		jQuery('#deposit-percentage').val(percent);
		
		// set the interest rate for the percentage
		this.setInterestRate(percent);
		
		// update deposit amount
		var price = makeNumeric(jQuery('#purchase-price').val());
		var amount = price * (percent / 100);
		jQuery('#deposit-amount').val(Math.round(amount));
		
		// update loan amount
		var loan = price - amount;
		jQuery('#loan-amount').val(Math.round(loan));
	}
	
	this.setDepositAmount = function(deposit) {
		deposit = makeFloat(deposit);
		jQuery('#deposit-amount').val(deposit);
		
		var price = jQuery('#purchase-price').val();
		
		// update loan amount
		var loan = price - deposit;
		jQuery('#loan-amount').val(makeNumeric(loan));
		
		// update deposit percentage
		var percent = (deposit / price) * 100;
		percent = Math.round(percent*100) / 100;
		
		this.setDepositPercentage(percent);
		// this.setInterestRate(percent); // done in setDepositPercentage()
	}
	
	this.setLoanAmount = function(loan) {
		loan = makeNumeric(loan);
		jQuery('#loan-amount').val(loan);
		
		// update deposit
		var price = jQuery('#purchase-price').val();
		var deposit = price - loan;
		jQuery('#deposit-amount').val(makeNumeric(deposit));
		
		// percentage
		var percent = (deposit / price) * 100;
		percent = Math.round(percent*100) / 100;
		//alert(percent);
		this.setDepositPercentage(percent);
		//jQuery('#deposit-percentage').val(percent);
		//this.setInterestRate(percent); // done in setDepositPercentage() 
	}
	
	this.setLoanPeriod = function(period) {
		jQuery('#loan-period').val(makeNumeric(preiod));
	}
	
	this.setInterestRate = function(deposit_percent) {
		var ltv = 100 - deposit_percent;
		//alert(ltv);
		
		var rate = 0;
		var max_rate = 0;
		
		// LTV percent from DB goes from small to high
		for (var i in this.interest_rates) {
			//alert(i + ' | ' + this.interest_rates[i]);
			if (ltv <= i) {
				rate = this.interest_rates[i];
				break; // found the right bracket, break out of the for loop
			}
			else {
				max_rate = this.interest_rates[i];
			}
			//alert('rate is: ' + rate);
		}
		
		// no rate found :(
		if (rate == 0) {
			rate = max_rate;
		}
		
		//alert('final rate: ' + rate);
		jQuery('#interest-rate').val(rate);
	}
	
	this.calculateMortgage = function() {
		var price = jQuery('#purchase-price').val();
		var deposit_percentage = jQuery('#deposit-percentage').val();
		var deposit_amount = jQuery('#deposit-amount').val();
		var loan_amount = jQuery('#loan-amount').val();
		var loan_period = jQuery('#loan-period').val();
		
		this.setInterestRate(deposit_percentage);
		var interest_rate = jQuery('#interest-rate').val();
		
		var rate = interest_rate / 100;
		var monthly_payment = ((loan_amount*rate)/12) * (1/(1-(Math.pow(1/(1+rate),loan_period))));
		monthly_payment = Math.round(monthly_payment*100)/100;
		monthly_payment = poundsPence(monthly_payment);
		var monthly_interest_only = (loan_amount*rate)/12;
		monthly_interest_only = Math.round(monthly_interest_only*100)/100;
		monthly_interest_only = poundsPence(monthly_interest_only);
		
		jQuery('#h_purchase_price').val(price);
		jQuery('#h_deposit_percentage').val(deposit_percentage);
		jQuery('#h_deposit_amount').val(deposit_amount);
		jQuery('#h_loan_amount').val(loan_amount);
		jQuery('#h_loan_period').val(loan_period);
		jQuery('#h_interest_rate').val(interest_rate);
		jQuery('#h_monthly_payment').val(monthly_payment);
		jQuery('#h_monthly_interest_payment').val(monthly_interest_only);
		
		jQuery('#mortgage-repayment').html('&euro;' + monthly_payment + ' pcm');
		jQuery('#mortgate-interest-repayment').html('&euro;' + monthly_interest_only + ' pcm');
		
		// done!
	}
}
/** end mortgage calculator functions **/
