var agt=navigator.userAgent.toLowerCase();
var iemac = ((agt.indexOf('msie')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;


//Target DOM capable browsers (excluding IE mac)
if (document.getElementById && document.getElementsByTagName && document.createTextNode && !iemac) {
	var ccount=0;

	//Hide toggle-able fields
	document.write('<style type="text/css">#searchwrap div#advcontent, #searchwrap fieldset#emailcontent, #asearch #search, .nonjs {display:none;} #optiontabs { display:block; } '
//					+ '#bascontent .multi select { height: 1.8em; }'
					+ '#bascontent ul li.multi { height: 3.5em; } '
					+ '</style>'
				   );

	//Do once page is loaded
	window.onload=function(){
	
		//Do on SEARCH FORM found (replaced by inline js)
//		if (document.search) { onSearchFound(); }

		//Do on search RESULTS TABLE found
		if (document.getElementById('asearch') && document.getElementById('search-results')) { forSearchResults() }
		
		//Do on VIEW LISTING found
		if (document.getElementById('view')) { onListingFound(); }
		
		//Do on CALCULATOR found
		if (document.getElementById('estimatecalc')) { onCalcFound(); }
		
		if (document.getElementById('noresults')) {	showSearch(); }
	}
} 

//Do these when the search form is found
function onSearchFound() {

	if (!iemac) {
	
		//Set Basic/Advanced form
		showAdvanced();
	
		//Change links to JS-powered
		document.getElementById('advlink').setAttribute('href',"javascript:toggleSearch('advanced')");
		document.getElementById('baslink').setAttribute('href',"javascript:toggleSearch('basic')");
		
		//Change submitting functionality 
		document.getElementById('advsearchsubmit').onclick=function() { hideEmpties(); }
//		document.getElementById('advsearchsubmit').setAttribute('onclick', 'hideEmpties()');
		
		//Change reset button functionality
		resetFields();
	}

}

function onListingFound() {
	if (document.getElementById('estimatecalc')) { onCalcFound(); }
	
	//Look for plan links
	var links = document.getElementById('listing-column').getElementsByTagName('a');	
	for (var i=0, l;l = links[i];i++) {
		if (l.innerHTML == 'show plan' || l.title == 'show plan') {
			l.onclick = function() { return show_plan(this); }
		}
	}
	
	//Do for main photo (removed for now)
	// var mlink = document.getElementById('mainphoto').getElementsByTagName('a')[0];	
	// mlink.onclick = function() { return bigphoto(this) }
	
	//Do for thumbnails
	var tlinks = document.getElementById('thumbnails').getElementsByTagName('a');
	for (var i=0, tl;tl = tlinks[i];i++) {
		tl.onclick = function() { return show_photo(this); }
	}
	
	//Do for save button
	var sb = document.getElementById('savelink');
	var url = sb.getAttribute('href');
	var id = url.substr(url.lastIndexOf('=')+1);
	
	sb.setAttribute('href','#');
	
	sb.onclick = function() { saveNow(id) }
}

function onCalcFound() {
	//Change submit effect of form
	document.calc.onsubmit = function() { showpay();return false; };
	var opts = document.calc;
	for (i=0;i<opts.length;i++) {
		opts[i].onchange = function() { reShow(); };
	}
}

function resetFields() {

	rbut = document.getElementById('advreset');
	
	//rbut.type = 'button'; //won't work in IE

	//Stupid IE workaround
	var replace = rbut;
	var val = replace.value;
	var rid = replace.id;
	var parent = replace.parentNode;
	var sibling = replace.nextSibling;
	var rbut = document.createElement('input');
	rbut.setAttribute('type', 'button');
	rbut.setAttribute('value', val);
	rbut.setAttribute('id', rid);
	parent.removeChild(replace);
	parent.insertBefore(rbut, sibling);
	//End stupid IE workaround
	
	rbut.onclick = function() { clearAll(this); };

}

var	cleared = false;

function clearAll(rbut) {

	fields = document.search;
	if (!cleared) {
		for(var i=0, fields;field = fields[i];i++) {
			if (field.type == 'select-one') {
				field.selectedIndex = 0;
			} else if (field.type == 'text') {
				field.value = '';
			} else if (field.type == 'checkbox') {
				field.checked = '';
			}
		}
		cleared = true;
		rbut.value = 'Reset';
	} else {
		cleared = false;
		document.search.reset();
		rbut.value = 'Clear';
	}

}

function showAdvanced() {
	
	//Open advanced search if needed
	var url = document.location+'';
	if (url.search('advsearch') != -1) {
		document.getElementById('optiontabs').style.display = 'none';
		toggleSearch('advanced');
	} else {
		//Check all inputs
		inputs = document.getElementById('advcontent').getElementsByTagName('input');
			
		var count = 0;
		var showadv = false;
			
		for(var i=0, inp;inp = inputs[i];i++) {
			if (inp.type == "text") {
				if (inp.value != "") {
					showadv = true;
					break;
				} else {
					showadv = false;
				}
			} else if (inp.type == "checkbox") {
				if (inp.checked == true) {
					showadv = true;
					break;
				}
				else {
					showadv = false;
				}
			}
			count++;
		}
		
		if (showadv == false) {
			selects = document.getElementById('advcontent').getElementsByTagName('select');
		
			for(var i=0, sel;sel = selects[i];i++) {
				if (sel.selectedIndex != 0) {
					// showadv = true;
					break;
				} else {
					showadv = false;
				}
				count++;
			}
		}
		
		if(showadv) {
			toggleSearch('advanced');
		} else {
		//Remove multiple
		/*
			document.search["make[]"].removeAttribute('multiple');
			document.search["make[]"].setAttribute('size',1);
			document.search["make[]"].style.display = 'none';
			document.search["make[]"].style.display = 'block';
		
			document.search["model[]"].removeAttribute('multiple');
			document.search["model[]"].setAttribute('size',1);
			
			document.search["type[]"].removeAttribute('multiple');
			document.search["type[]"].setAttribute('size',1);	
			document.search["type[]"].style.display = 'none';
			document.search["type[]"].style.display = 'block';
		*/	
		}
	}
}

function setModel() {
	//Set onchange event
	document.search["make[]"].onchange= function() { showModel(this); };
	
	//Remove multiple
	document.search["make[]"].removeAttribute('multiple');
	document.search["make[]"].setAttribute('size',1);
	
	document.search["type[]"].removeAttribute('multiple');
	document.search["type[]"].setAttribute('size',1);	
	
	
	//make array of items
	var url = document.location+'';
	var modelno = url.indexOf('model%5B%5D=');
	var modelno2 = url.lastIndexOf('model%5B%5D=');
	var multisize = '6';
	
	if (modelno!=-1) {		 //start	//length
		var mdlength = url.indexOf('&',modelno2) - modelno;
		modeldata = url.substr(modelno+12,mdlength-12);
		modelarr = modeldata.replace(/\+/g,' ').split('&model%5B%5D=');
		origval = modelarr;
	} else {
		origval = new Array('');
	}
	
	mod = document.search["model[]"];
	moddiv = mod.parentNode;
	
	mod.parentNode.removeChild(mod);
	
	model = document.createElement('select');
	model.name = 'model[]'; //maybe not needed?
	model.id = 'model[]';

	model.setAttribute('multiple','multiple');
	model.setAttribute('size',multisize);
	
	moddiv.appendChild(model);

	//Another Way
	showModel(document.search["make[]"]); selModel(origval);
}

function showSearch(item) {
	if (item) {
		item.parentNode.style.display='none';
	}
	document.getElementById('search').style.display='block';
}

//toggle search options
function toggleSearch(type) {
	var advcontent = document.getElementById('advcontent').style;
	var advlink = document.getElementById('advlink');
	var baslink = document.getElementById('baslink');
	var moreopts = document.getElementById('moreopts');
	var make = document.search["make[]"];
	var bascontent = document.getElementById('bascontent');
	var multis = new Array('make[]','model[]','type[]','color[]','agent[]');
//	var tip = bascontent.getElementsByTagName('p')[0].style;
	
	if (type == 'advanced') {
		//Change "make" type
		for (var i=0, multi; multi = document.search[multis[i]];i++) {
		
//			multi.style.visibility = 'hidden';
			multi.setAttribute('multiple','multiple');
			multi.setAttribute('size','6');
//			multi.style.visibility = 'visible';
			
		}
		
		bascontent.className = 'adv';
		advlink.parentNode.className = 'otcur';
		baslink.parentNode.className = '';
		advcontent.display = 'block';
		moreopts.style.display = 'none';

		
		/*
		//Reorganize
		var litems = document.getElementById('bascontent').getElementsByTagName('li');
//		var count = 0;
		for (var i=0, item;item = litems[i];i++) {
			if(item.className == 'multi') {
				item.parentNode.insertBefore(item, item.parentNode.firstChild);
			} else {
				document.getElementById('advcontent').getElementsByTagName('ul')[0].appendChild(item);
			}
		}
		*/
		
	} else {
		for (var i=0, multi; multi = document.search[multis[i]];i++) {
			multi.style.visibility = 'hidden';
			multi.removeAttribute('multiple');
			multi.removeAttribute('size');
			multi.style.visibility = 'visible';
		}
		

		bascontent.className = '';
		advlink.parentNode.className = '';
		baslink.parentNode.className = 'otcur';
		advcontent.display = 'none';
		moreopts.style.display = 'block';
		//Clear all contents
		
		rbut = document.getElementById('advreset');
		clearAll(rbut);
	}
}

//remove unneeded fields from URL
function hideEmpties() {
/*
	fields = document.search;
	for (i=0;i<fields.length;i++) {
		if (fields[i].value == "" || fields[i].value == 0 || fields[i].name == "critaction" && fields[i].value == "Search") {
			fields[i].removeAttribute('name');
			fields[i].removeAttribute('id');
		}
	}
*/	
}
//Get model list based on selected option
function showModel(item) {


	//Clear current options
	while (document.search["model[]"].hasChildNodes()) {
		document.search["model[]"].removeChild(document.search["model[]"].firstChild)
	}
	
	//not needed?
	document.search["model[]"].innerHTML = ""; 
	
	//Create "Any" option
	opt = document.createElement('option');
	opt.innerHTML = "Any";
	opt.value = "";
	document.search["model[]"].appendChild(opt);
	
	//Get models associated with make, populate list
	if (item.value != "") {
	
		//Look for selected options
		var mk = document.search["make[]"];
		var mks = [];
		
		for( var oO = mk.options, k = 0; oO[k]; k++ ) {
			//Do only for selected makes
			if (oO[k].selected) {
				var makesval = oO[k].value;
				
				models = eval(makesval.replace(/ |-/,""))
				for (i=0;i<models.length;i++) {
					for (j=0;j<Modelsindb.length;j++) {
						if (models[i] == Modelsindb[j]) {
							opt = document.createElement('option')
							opt.innerHTML = models[i];
							opt.value = models[i];
							document.search["model[]"].appendChild(opt); 
						}
					}
				}
			}
		}
	} else { 
		//"Any" is selected, display all models
		for (i=0;i<Modelsindb.length;i++) {
			opt = document.createElement('option')
			opt.innerHTML = Modelsindb[i];
			opt.value = Modelsindb[i];
			document.search["model[]"].appendChild(opt); 
		}
	}
}

//Select Model if searched for
function selModel(gmodel) {
	//Clear current options
	opts = document.search["model[]"].options;
	var string= '';
			
	for (i=0;i<opts.length;i++) {
		string += opts[i].value + '|';
		for (j=0;j<gmodel.length;j++) {
			if (opts[i].value == gmodel[j]) {
				opts[i].selected = true;
			}	
		}
	}
}

function setCookie(cName,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = cName+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=")
	  if (c_start!=-1) { 
		c_start=c_start + c_name.length+1 
		c_end=document.cookie.indexOf(";",c_start)
		if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
		} 
	  }
	return ""
}

Array.prototype.find = function (s)
{
	for(var i=0;i<this.length;i++)
	if(this[i] == s) return true; 
	return false;
};

//Save listing to cookie w/javascript
function saveNow(id, button) {

	if (document.getElementById('savelink')) {
		var listing = document.getElementById('savelink');
	}

	var curCookie = getCookie('faves');

	cArray = curCookie.split('|');
	
	if (button) {
	
		//note span
		note = button.parentNode.nextSibling;
	
		//star img
		star = button.parentNode.parentNode.parentNode.getElementsByTagName('img')[0];
	}
	if(!cArray.find(id)) {
		//add to cookie
		curCookie += (curCookie=="")?'':'|';
		setCookie('faves',curCookie + id,60);
		
		if (button) {
			button.value = 'Un-Save';
			
			note.innerHTML = 'Saved! <a href="index.php?option=com_hotproperty&task=viewsaved">(View all)</a>';
			//show star
			star.style.display = 'inline';
		} else {
			//Change text to "Remove"
			listing.innerHTML = listing.innerHTML.replace(/Save/g,'Remove');
		}
	
	} else {
		//already found, remove
		for(var i=0;i<cArray.length;i++) {
			if (cArray[i] == id) {
				cArray.splice(i,1);
				break;
			}
		}
		setCookie('faves',cArray.join('|'),60);
		
		if (button) {
			note.innerHTML = '';
			button.value = 'Save';
	
			//hide star
			star.style.display = 'none';
		} else {
			//Change text to "Save"
			listing.innerHTML = listing.innerHTML.replace(/Remove/g,'Save');
		}
	}
}

function forSearchResults() {
	//Set compare button effect
	document.proclistings.onsubmit = function() { return checkComp(); };


	//Check for saved listings
	var curCookie = getCookie('faves');
	cArray = curCookie.split('|');

	var rows = document.getElementById('search-results').getElementsByTagName('tr');

	//Remove last row

	//Add buttons + note area	
	for (var i=1, row;row = rows[i];i++) {
	
		var datalist = row.getElementsByTagName('ul')[1];
		var id = row.getElementsByTagName('input')[0].getAttribute('value');
//		alert(id); break;
		var item = document.createElement('li'); //'var' needed for IE
		var note = document.createElement('span');
		note.className = 'note';
		
		//add star
		var star = document.createElement('img');
		star.src = "images/star.gif";
		star.setAttribute('style','vertical-align:middle;');
		star.style.display = 'none';
		strng = row.getElementsByTagName('strong')[0];

		if(!cArray.find(id)) {
			//not saved yet
			var buttontext = "Save";
		} else {
			// already saved
			var buttontext = "Un-Save";
			star.style.display = 'inline';
		}
		
		strng.parentNode.insertBefore(star,strng);
		item.innerHTML = '<input type="button" onclick="saveNow(\''+ id +'\',this)" value="'+buttontext+'" />';

		datalist.appendChild(item);
		item.parentNode.appendChild(note);
		
//		alert(i + '/' + rows.length);
		
		if (i == rows.length-2) {
			i = rows.length;
		}
	}
}

function checkComp() {
	//Check if it is okay to compare
	var items = document.proclistings["listing[]"];
	var counter = 0;
	for (var i=0, item;item=items[i];i++) {
		if (item.checked) {
			counter++;
		}
	}
	if (counter <= 1) {
		alert('Please select more than one listings to compare');
		return false;
	} else if (counter > 4) {
		alert('Please select less than four listings to compare');
		return false;
	}
	

}

/* Mortgage calculator */
function showpay() {
	var c = document.calc;
	
	if ((c.vprice.value == null || c.vprice.value.length == 0) ||
	 	(c.term.value == null || c.term.value.length == 0) ||
		(c.intrate.value == null || c.intrate.value.length == 0)) { 
		c.pay.value = "Incomplete data";
	 } else {
	 	var vprice = c.vprice.value.replace(/\,/g,'');
		var princ = vprice - c.payment.value - c.tradein.value;
//		var payment = c.payment.value;
//		var tradein = c.tradein.value;
		var salestax = c.salestax.value;
		princ = vprice * (salestax/100) + princ;
		var intr   = c.intrate.value / 1200;
		var term  = c.term.value;

		var rawvalue = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
		c.pay.value = addCommas(Math.round(rawvalue*100)/100);
		c.vprice.value = addCommas(c.vprice.value);
	}

// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))

}

function reShow() {
	if (document.calc.pay.value != null && document.calc.pay.value.length != 0) {
		showpay();
	}
}

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;
}

function bigphoto(item) {
	var file = item.getAttribute('href');

	// Get height of area to center vertically
	var imgheight = 480;	
	var h;
	if (self.innerHeight) {
		h = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		h = document.documentElement.clientHeight;
	} else if (document.body) {
		h = document.body.clientHeight;
	}
	h = (h / 2) - (imgheight / 2);
	
	// Create elements
	var d = document.createElement('div');
	d.className = 'bigphoto';
	d.setAttribute('title','Click to close image');
	d.onclick = function() { this.parentNode.removeChild(this) }
	
	var img = document.createElement('img');
	img.style.margin = h + 'px';
	img.setAttribute('src',file);
	
	// Display elements
	d.appendChild(img);
	item.parentNode.parentNode.parentNode.appendChild(d);
	
	return false;
}

function show_plan(what) {
	var space = document.getElementById('planspace');
	
	space.style.display = 'block';
	var img = document.createElement('img');
	img.src = what.href;
	
	floortxt = what.parentNode.innerHTML;
	floortxt = floortxt.replace(/<(.*?)>/g,'');
	floortxt = floortxt.replace(/show plan/g,'');

	var pdfname = img.src.replace(/.gif|.png/i,'.pdf');
	var haspdf = (pdfname.indexOf('.pdf') != -1)?true:false;
	
	var pdflink = document.createElement('a');
	pdflink.href = pdfname;
	pdflink.target = '_blank';
	
	var pdftxtlink = pdflink.cloneNode(false);

	if(haspdf) {

		var icon = document.createElement('img');
		icon.src = 'graphics/pdficon.gif';
	
		pdftxtlink.appendChild(icon);
		pdftxtlink.appendChild(document.createTextNode(" Show PDF "));
	} 
	
	pdflink.appendChild(img);

	var a = document.createElement('a');
	a.onclick = function() { 
		space.innerHTML = '';
		space.style.display = 'none';
		return false;
	};
	a.href = '#';
	a.appendChild(document.createTextNode("close"));

	var h3 = document.createElement('h3');
	h3.innerHTML = floortxt + ' - ';
	if(haspdf) {
		h3.appendChild(pdftxtlink);
	}
	h3.appendChild(a);
		
	space.innerHTML = '';
	space.appendChild(h3);
	space.appendChild(pdflink);



	return false;
}


function show_photo(what) {
//	var img = what.childNodes[0];
	var img = what.getElementsByTagName('img')[0];
	var fname = img.src.replace('/thb/','/std/');
	var title = img.alt?img.alt:'';
	var desc = img.getAttribute('longdesc')?img.getAttribute('longdesc'):'';
	
	document.standard_photo.src = fname;
	var pt = document.getElementById('phototitle');
	var pd = document.getElementById('photodesc');
	
	// var mainlink = document.getElementById('mainphoto').getElementsByTagName('a')[0];
	// mainlink.href = img.src.replace('/thb/','/ori/');
	
	pt.innerHTML = title?title:'';
	pd.innerHTML = desc?desc:'';
	
	//set link url
	
	
	return false;
}
	


