// global namespace
var AH = new Object();
AH.Mortgage = new Object();

// set defaults
AH.Mortgage.loan_amount = "";
AH.Mortgage.interest_rate = 5;
AH.Mortgage.term = 25;

function popup(id){
	var dealWin = window.open("/mortgages/deals/"+id+".html",'','width=500,height=500,scrollbars=yes');
}

function trackURL(url){
	if(window.urchinTracker){
		urchinTracker(url);
	}else if(window._gaq){
		_gaq.push(['_trackPageview', url]);
		// to use event tracking instead:
		//_trackEvent(category, action, label)
		//_gaq.push(['_trackEvent','Valuation','Homepage','top_button']);
	}
}

function goTo(url){
	document.location.href = url;
}

function show_msg(msg){
	alert(msg);
}

function stripCurrency(n){
	if(!n){
		n = 0;
	}
	n = n.toString().replace(/\Â£|\£|\,|\s/g,'');
	n = parseFloat(n);
	return n;
}
function formatCurrency(n) {
	// remove sign and comma
	n = n.toString().replace(/\Â£|\,/g,'');
	if(isNaN(n)){n = "0";}
	sign = (n == (n = Math.abs(n)));
	// round up
	n = Math.floor(n*100+0.50000000001);
	n = Math.floor(n/100).toString();
	for (var i=0; i<Math.floor((n.length-(1+i))/3);i++){
		n = n.substring(0,n.length-(4*i+3))+','+ n.substring(n.length-(4*i+3));
	}
	return (((sign)?'':'-') + n);
}
	
function Set_Cookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

var today = new Date();
var expires = new Date(today.getTime() + (56 * 86400000));


function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}


function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getValues(){
	var mortgage_cookie = Get_Cookie('mortgage');
	if(mortgage_cookie != null){
		mortgage_cookie = eval('('+mortgage_cookie+')');
		// get variables from cookie
		var loanamt = mortgage_cookie["loan"] || mortgage_cookie["loan_amount"] || 0;
		
		if (loanamt != null) {
			if(document.getElementById('borrow_form_holder')){
				if(loanamt != 0){
					document.getElementById('borrow_question').style.display = "none";
					document.getElementById('borrow_form_holder').style.display = "inline";
				}
			}
			if(document.forms[0].loan_amount){
				document.forms[0].loan_amount.value = formatCurrency(loanamt);
			}
		}
	}
}

function sendValues(rate){
	var m = new Object();
	m.loan = stripCurrency(document.forms[0].loan_amount.value);
	mortgage_cookie_value = $.json.encode(m);
	Set_Cookie("mortgage",mortgage_cookie_value,expires,'/');
	
	var loc = "/mortgage-calculator?term=25&interest_rate="+rate+"&loan_amount="+ m.loan;
	
	if (m.loan) {
	    loc += '&calc=1';
    }

	document.location.href = loc;
}

/* used in contact forms */
var form_errors = new Array();

function validateForm(theform, fields_to_validate){
	var fields_to_validate = ["first_name","last_name"];
	// store error fields
	for(var i=0;i<fields_to_validate.length;i++){
  		if(theform[fields_to_validate[i]].value == ""){
    		form_errors.push(fields_to_validate[i]);
		}
	}
	if(form_errors.length){
		// highlight error fields
		for(var i=0;i<form_errors.length;i++){
			document.getElementById(form_errors[i]).className = "error_field";
		}
		document.getElementById('error_msg').className = "warning";
		document.getElementById('error_msg').innerHTML = "Please check you have entered the correct information";
		return false;
	}else{
		return true;
	}
}

function manageErrorFields(field_name){
	var f = document.getElementById(field_name);
	if(f.value.length > 0){
		f.className = "";
		// reduce errors
		form_errors.pop();
	}
	// hide error msg
	if(form_errors.length == 0){
		document.getElementById('error_msg').className = "";
		document.getElementById('error_msg').innerHTML = "";
	}
}

function setOther(){
	var f = document.contact_form;
	if (f.source.options[f.source.selectedIndex].value == "other_source"){
		//f.other_source.value = "Please specify";
		document.getElementById('other_source').style.visibility = "visible";
	}else{
		document.getElementById('other_source').style.visibility = "hidden";
	}
}
function removeText(){
	var f = document.contact_form;
	if (f.other_source.value == "Please specify"){
		f.other_source.value = "";
	}
}

// type         = mortgage/job/borrow/calculator
// include_link = boolean
function emailAFriend(type, include_link){
    var url = '/email_friend/'+type+'?';
	if(include_link){
	    url += "&link="+escape(document.location.href);
    }
	var emailWin = window.open(url,'emailWin','width=500,height=390,status=yes');
	if(emailWin){emailWin.focus();}
}

function monthlyRepayments(use_global_vars){
	var params = "";
	if(use_global_vars){
		params = "&calc=Y&term="+AH.Mortgage.term+"&interest_rate="+AH.Mortgage.interest_rate;
	}
	document.location.href = "/mortgage-calculator?loan_amount="+AH.Mortgage.loan_amount + params;
}

// handles hover sub menus in IE
startList = function() {
	if (document.all&&document.getElementById) {
		var navRoot = document.getElementById("nav_ul");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}

function addLoadListener(fn){ 
	if (typeof window.addEventListener != 'undefined') { 
		window.addEventListener('load', fn, false); 
	}else if (typeof document.addEventListener != 'undefined'){ 
		document.addEventListener('load', fn, false); 
 	}else if (typeof window.attachEvent != 'undefined'){ 
		window.attachEvent('onload', fn); 
	}else{ 
		var oldfn = window.onload; 
		if (typeof window.onload != 'function'){ 
			window.onload = fn; 
		}else{ 
			window.onload = function(){
				oldfn();
				fn();
			}; 
   		}
	}
}

addLoadListener(startList);

