


var timeout= 500;

function lnk(type,id,db)
{
	if(type=="print")
	{
		document.write("<a href=\"javascript:;\" onclick=\"openpopup('http://www.morfittpropertiestenerife.com/engine/res/print.php?lng=en&id="+id+"&db="+db+"');\">Print this Listing</a>"); 
	}

}


function openpopup(popupurl){
	win = window.open(popupurl,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=840,height=600,top=60,left=60');

}

function delay(val)
{

	if(val=='complex')
	{
		window.setTimeout('complex_suggest()', timeout);
		window.setTimeout('searchResult()', timeout);
	}else if(val=='loc4')
	{
		window.setTimeout('loc4_suggest()', timeout);
		window.setTimeout('searchResult()', timeout);
	}
	else if(val=='reference')
		window.setTimeout('reference_suggest()', timeout);
	else if(val=='reference_r')
		window.setTimeout('reference_suggest_r()', timeout);
	else if(val=='complex_s_r')
	{
		window.setTimeout('complex_suggest_r()', timeout);
		window.setTimeout('searchResult_r()', timeout);
	}else if(val=='simple_search')
	{
		window.setTimeout("ini('simple_search')", timeout);
	}
}

//shortlist

var shortReq = getXmlHttpRequestObject();
var shortReq_ss = getXmlHttpRequestObject();
var shortReq_sr = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function shortlist(act,lng,id,db) {
	if (shortReq.readyState == 4 || shortReq.readyState == 0) {
		shortReq.open("GET", 'http://www.morfittpropertiestenerife.com/engine/template/suggest/shortlist.php?id=' + id + '&act=' + act + '&lng=' + lng + '&db=' + db, true);
		if((act=='show' || act=='rmv') && db == 's')
			shortReq.onreadystatechange = handleshortlist_ss; 
		else if((act=='show' || act=='rmv') && db == 'r')
			shortReq.onreadystatechange = handleshortlist_sr; 
		else
			shortReq.onreadystatechange = handleshortlist; 
		shortReq.send(null);
	}		
}
function handleshortlist() {
	if (shortReq.readyState == 4) {
		var ss = document.getElementById('p_cont')
		ss.innerHTML = '';
		var str = shortReq.responseText.split("\n");
		for(i=0; i < str.length - 1; i++) {
			ss.innerHTML += str[i];
		}
	}
}

function shortlist_ss(act,lng,id,db) {
	if (shortReq_ss.readyState == 4 || shortReq_ss.readyState == 0) {
		shortReq_ss.open("GET", 'http://www.morfittpropertiestenerife.com/engine/template/suggest/shortlist.php?id=' + id + '&act=' + act + '&lng=' + lng + '&db=' + db, true);
		shortReq_ss.onreadystatechange = handleshortlist_ss; 
		shortReq_ss.send(null);
	}		
}
function handleshortlist_ss() {
	if (shortReq_ss.readyState == 4) {
		var ss = document.getElementById('shortlist_ss')
		ss.innerHTML = '';
		var str = shortReq_ss.responseText.split("\n");
		for(i=0; i < str.length - 1; i++) {
			ss.innerHTML += str[i];
		}
	}
}

function shortlist_sr(act,lng,id,db) {
	if (shortReq_sr.readyState == 4 || shortReq_sr.readyState == 0) {
		shortReq_sr.open("GET", 'http://www.morfittpropertiestenerife.com/engine/template/suggest/shortlist.php?id=' + id + '&act=' + act + '&lng=' + lng + '&db=' + db, true);
		shortReq_sr.onreadystatechange = handleshortlist_sr; 
		shortReq_sr.send(null);
	}		
}

function handleshortlist_sr() {
	if (shortReq_sr.readyState == 4) {
		var ss = document.getElementById('shortlist_sr')
		ss.innerHTML = '';
		var str = shortReq_sr.responseText.split("\n");
		for(i=0; i < str.length - 1; i++) {
			ss.innerHTML += str[i];
		}
	}
}


//end shortlist
function noFollow(n) {
        window.open(n);
	n;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	  window.open(theURL,winName,features);
}

function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
	}
}


var reference_sReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function reference_suggest() {
	if (reference_sReq.readyState == 4 || reference_sReq.readyState == 0) {
		var reference_s = escape(document.getElementById('ref').value);
		reference_sReq.open("GET", 'http://www.morfittpropertiestenerife.com/engine/template/suggest/reference.php?reference=' + reference_s +'&db=s', true);
		reference_sReq.onreadystatechange = handlereference; 
		reference_sReq.send(null);
	}		
}
//Called when the AJAX response is returned.
function handlereference() {
	if (reference_sReq.readyState == 4) {
		document.getElementById("reference_suggest").style.visibility="visible";
		var ss = document.getElementById('reference_suggest')
		ss.innerHTML = '';
		var str = reference_sReq.responseText.split("\n");
		for(i=0; i < str.length - 1; i++) {
			var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
			suggest += 'onmouseout="javascript:suggestOut(this);"';
			suggest += 'onclick="javascript:setSearch_reference(this.innerHTML);"';
			suggest += 'class="suggest_link">' + str[i] + '</div>';

			ss.innerHTML += suggest;
		}
	}
}
//Click function
function setSearch_reference(value) {
	document.getElementById('ref').value = value;
	document.getElementById('reference_suggest').innerHTML = '';
	hideSuggestions();
}

//reference

function displayrefsearch(){
var o = testForObject('property_reference_search');
if(o)
{
var ss = document.getElementById('property_reference_search');
ss.innerHTML = '';
var print ="";
print += "<table id=\"refsearch\" style=\"border-collapse: collapse;\" width=\"100%\"><tr><td align=\"center\" width=\"100%\"><form action=\"http://www.morfittpropertiestenerife.com/ref.php\" method=\"get\" id=\"ref_search\" style=\"margin:0px;\" onclick=\"hideSuggestions();\"><table style=\"border-collapse: collapse;\" HTML CELLPADDING=0 CELLSPACING=0>";
print += " <tr><td align=\"center\" valign=\"top\"><div style=\"margin:0px;padding-left:1px;\"><input id=\"ref\" name=\"ref\" onkeyup=\"delay('reference');\" autocomplete=\"off\" style=\"width:95px;\"> </div></td><td valign=\"top\"><div style=\"padding-left:3px;\" class=\"sbutton\"><input type=\"submit\" value=\"Submit!\" style=\"height:18px;width:60px;padding-top:0px;\" onMouseover=\"this.style.color='#000000'\" onMouseout=\"this.style.color='#526296'\"></div></td></tr>";
print += "</table><div align=\"left\" style=\"padding-left:25px; padding-bottom:1px;\"><div id=\"reference_suggest\"></div></div></form></td></tr></table>";
ss.innerHTML = print;
}
}

function displayrefsearch_r(){
var o = testForObject('rental_reference_search');
if(o)
{
var ss = document.getElementById('rental_reference_search');
ss.innerHTML = '';
var print ="";
print += "<table id=\"refsearch_r\" style=\"border-collapse: collapse;\" width=\"100%\"><tr><td align=\"center\" width=\"100%\"><form action=\"http://www.morfittpropertiestenerife.com/rentals/ref.php\" method=\"get\" id=\"ref_search_r\" style=\"margin:0px;\" onclick=\"hideSuggestions();\"><table style=\"border-collapse: collapse;\" HTML CELLPADDING=0 CELLSPACING=0>";
print += "<tr><td align=\"center\"><div style=\"margin:0px;padding-left:1px;\"><input id=\"ref_r\" name=\"ref_r\" onkeyup=\"delay('reference_r');\" autocomplete=\"off\" style=\"width:95px;\"></div></td><td><div style=\"padding-left:3px;\" class=\"sbutton\"><input type=\"submit\" value=\"Submit!\" style=\"height:18px;width:60px;padding-top:0px;\" onMouseover=\"this.style.color='#000000'\" onMouseout=\"this.style.color='#526296'\"></div></td></tr>";
print += "</table><div align=\"left\" style=\"padding-left:25px; padding-bottom:1px;\"><div id=\"reference_suggest_r\"></div></div></form></td></tr></table>";
ss.innerHTML = print;

}
}

var reference_sReq_r = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function reference_suggest_r() {
	if (reference_sReq_r.readyState == 4 || reference_sReq_r.readyState == 0) {
		var reference_s = escape(document.getElementById('ref_r').value);
		reference_sReq_r.open("GET", 'http://www.morfittpropertiestenerife.com/engine/template/suggest/reference.php?reference=' + reference_s +'&db=r', true);
		reference_sReq_r.onreadystatechange = handlereference_r; 
		reference_sReq_r.send(null);
	}		
}
//Called when the AJAX response is returned.
function handlereference_r() {
	if (reference_sReq_r.readyState == 4) {
		document.getElementById("reference_suggest_r").style.visibility="visible";
		var ss = document.getElementById('reference_suggest_r')
		ss.innerHTML = '';
		var str = reference_sReq_r.responseText.split("\n");
		for(i=0; i < str.length - 1; i++) {
			var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
			suggest += 'onmouseout="javascript:suggestOut(this);"';
			suggest += 'onclick="javascript:setSearch_reference_r(this.innerHTML);"';
			suggest += 'class="suggest_link">' + str[i] + '</div>';

			ss.innerHTML += suggest;
		}
	}
}
//Click function
function setSearch_reference_r(value) {
	document.getElementById('ref_r').value = value;
	document.getElementById('reference_suggest_r').innerHTML = '';
	hideSuggestions();
}


//end reference
//Mouse over function
function suggestOver(div_value) {
	div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
	div_value.className = 'suggest_link';
}

function hideSuggestions()
{
	var ls = testForObject("loc4_suggest");
	var cs = testForObject("complex_suggest");
	var rs = testForObject("reference_suggest");
	var r = testForObject("complex_suggest_r");
	if (cs)
	{
		 document.getElementById("complex_suggest").style.visibility="hidden";
	}
	if (ls)
	{
		 document.getElementById("loc4_suggest").style.visibility="hidden";
		 document.getElementById("loc4_iframe").style.visibility="hidden";
	}
	if (rs)
	{
		 document.getElementById("reference_suggest").style.visibility="hidden";
	}
	
	if(r)
	{
		 document.getElementById("complex_suggest_r").style.visibility="hidden";
		 document.getElementById("reference_suggest_r").style.visibility="hidden";

	}
}
var state = 'none';

function showhide(layer_ref)
{
	if (state == 'block') 
	{
		state = 'none';
	}
	else 
	{
		state = 'block';
	}
	if (document.all) 
	{ //IS IE 4 or 5 (or 6 beta)
		eval( "document.all." + layer_ref + ".style.display = state");
	}
	if (document.layers) 
	{ //IS NETSCAPE 4 or below
		document.layers[layer_ref].display = state;
	}
	if (document.getElementById &&!document.all) 
	{
		hza = document.getElementById(layer_ref);
		hza.style.display = state;
	}
}

function showhideh(layer_ref) 
{

	if (state == 'none') 
	{
		state = 'block';
	}
	else 
	{
		state = 'none';
	}
	if (document.all) 	
	{ //IS IE 4 or 5 (or 6 beta)
		eval( "document.all." + layer_ref + ".style.display = state");
	}
	if (document.layers) 
	{ //IS NETSCAPE 4 or below
		document.layers[layer_ref].display = state;
	}
	if (document.getElementById &&!document.all) 
	{
		hza = document.getElementById(layer_ref);
		hza.style.display = state;
	}
}
function testForObject(Id, Tag)
{
  var o = document.getElementById(Id);
  if (o)
  {
      return o;
  }
  return null;
}


ns4 = document.layers;
ie4 = document.all;
nn6 = document.getElementById && !document.all;

//mortgage

    function checkForZero(field) {
        if (field.value == 0 || field.value.length == 0) {
            alert ("This field can't be 0!");
            field.focus(); }
        else
	    calculatePayment(field.form);
    }

    function cmdCalc_Click(form) {
        if (form.price.value == 0 || form.price.value.length == 0) {
            alert ("The Price field can't be 0!");
            form.price.focus(); }
        else if (form.ir.value == 0 || form.ir.value.length == 0) {
            alert ("The Interest Rate field can't be 0!");
            form.ir.focus(); }
        else if (form.term.value == 0 || form.term.value.length == 0) {
            alert ("The Term field can't be 0!");
            form.term.focus(); }
        else
            calculatePayment(form);
    }

    function calculatePayment(form) {
        princ = form.price.value - form.dp.value;
        intRate = (form.ir.value/100) / 12;
        months = form.term.value * 12;
        form.pmt.value = Math.floor((princ*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100;
  	form.principle.value = princ;
	form.payments.value = months;
    }
//mortgage


var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?

////NO NEED TO EDIT BELOW THIS LINE////////////

var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''

function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}

function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("marqueecontainer").offsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",50)', delayb4scroll)
}

function marq()
{
	var o = testForObject("vmarquee");
	if (o)
	{
		initializemarquee();


	}
}


function removeAllOptions(selectbox)
{
	var i;
	for(i=selectbox.options.length-1;i>=0;i--)
	{
		//selectbox.options.remove(i);
		selectbox.remove(i);
	}
}


function addOption(selectbox, value, text )
{
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;

	selectbox.options.add(optn);
}

//==============popup
var state_overlay = 'hide';

window.onscroll = scroll;
window.onresize = scroll;
function scroll()
{

	if(state_overlay=='show')
	{
	  myPopupRelocate();
	}
}


function center_popup(id)
{
  var msgbox = document.getElementById(id);
   
  
     var y = Math.round((document.documentElement.clientHeight/2)-(msgbox.style.height/2)+document.documentElement.scrollTop)+'px';
     var x = Math.round((document.documentElement.clientWidth/2)-(msgbox.style.width/2))+"px";
     msgbox.style.top = y;
     msgbox.style.left = x;

}
function hideoverlay() {
state_overlay='hide';
  if (ns4) {
     document.overlay.visibility = "hide";

  }
  else if (ie4) {
     document.all['overlay'].style.visibility = "hidden";

  }
  else if (nn6) {
     document.getElementById('overlay').style.visibility = "hidden";

  }
}

function showoverlay() {
state_overlay='show';
var arrayPageSize = getPageSize();
var objOverlay = document.getElementById('overlay');
objOverlay.style.height = (arrayPageSize[1] + 'px');
objOverlay.style.display = 'block';

   //center('overlay');
  if (ns4) {
     document.overlay.visibility = "show";
  }
  else if (ie4) {
     document.all['overlay'].style.visibility = "visible";
  }
  else if (nn6) {
     document.getElementById('overlay').style.visibility = "visible";
  }
}



ns4 = document.layers;
ie4 = document.all;
nn6 = document.getElementById && !document.all;

function hidepopup() {
hideoverlay();
var up = testForObject("upload_process");
  if (ns4) {
     document.popup.visibility = "hide";
	if(up)
	{
	     document.upload_process.visibility = "hide";
	     document.upload_form.visibility = "hide";
	}
  }
  else if (ie4) {
	if(up)
	{
	     document.all['upload_process'].style.visibility = 'hidden';
	     document.all['upload_form'].style.visibility = 'hidden';
	}
     document.all['popup'].style.visibility = "hidden";
  }
  else if (nn6) {
	if(up)
	{
	     document.getElementById('upload_process').style.visibility = 'hidden';
	     document.getElementById('upload_form').style.visibility = 'hidden';
	}
     document.getElementById('popup').style.visibility = "hidden";
  }
}
function popup(act,lng,id,extra) {
showoverlay();
document.getElementById('p_cont').innerHTML="<center><div style=\"padding-top:10px;background-color:#ffffff;\"><img src=\"http://www.morfittpropertiestenerife.com/images/ajax-loading.gif\"></div></center>";
h = document.documentElement.clientHeight;
w = document.documentElement.clientWidth;
if(act=='addrmv')
{
	shortlist(act,lng,id,extra);
        document.getElementById('p_cont').style.height = "60px";
	document.getElementById('p_cont').style.width = "360px";

}else if(act=='calc')
{
	ajaxpage(rootdomain+'/engine/res/mortgage.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');
	document.getElementById('p_cont').style.height = "520px";
	document.getElementById('p_cont').style.width = "450px";
}else if(act=='pdf')
{
	ajaxpage(rootdomain+'/engine/res/pdf.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');
	document.getElementById('p_cont').style.height = "400px";
	document.getElementById('p_cont').style.width = "450px";
}else if(act=='contact')
{
	ajaxpage(rootdomain+'/engine/res/form.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');
	document.getElementById('p_cont').style.height = "520px";
	document.getElementById('p_cont').style.width = "500px";
}else if(act=='gallery')
{
	ajaxpage(rootdomain+'/engine/res/gallery.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');

	document.getElementById('p_cont').style.height = "500px";
	document.getElementById('p_cont').style.width = "540px";

}else if(act=='article')
{
	ajaxpage(rootdomain+'/engine/res/article.php?id='+ id, 'p_cont','');
	//document.getElementById('p_cont').style.height = h - 50 + "px";
	document.getElementById('p_cont').style.height = "600px";
	document.getElementById('p_cont').style.width = "700px";
}else if(act=='maps')
{
	ajaxpage(rootdomain+'/engine/res/maps.php?lng='+lng, 'p_cont','');
	document.getElementById('p_cont').style.height = "500px";
	document.getElementById('p_cont').style.width = "700px";
}else if(act=='c_us')
{

	ajaxpage(rootdomain+'/engine/res/form.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');
	document.getElementById('p_cont').style.height = "500px";
	document.getElementById('p_cont').style.width = "500px";
}else if(act=='finder')
{
	ajaxpage(rootdomain+'/engine/res/form_det.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');
	document.getElementById('p_cont').style.height = "600px";
	document.getElementById('p_cont').style.width = "620px";
	window.setTimeout("ini_finder('formid')", 1000);
}else if(act=='sell')
{
	ajaxpage(rootdomain+'/engine/res/sell.php?lng='+lng+'&id='+ id+'&db='+ extra, 'p_cont','');
	document.getElementById('p_cont').style.height = "600px";
	document.getElementById('p_cont').style.width = "780px";

}
  if (ns4) {
     document.popup.visibility = "show";

  }
  else if (ie4) {
     document.all['popup'].style.visibility = "visible";

  }
  else if (nn6) {
     document.getElementById('popup').style.visibility = "visible";
  }
myPopupRelocate();
}

//iframe

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function ajaxpage(url, containerid,formid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()

if(formid!="")
{
	page_request.open('POST', url, true);
	page_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	var pineapple = document.getElementById(formid).elements; // formID needs to be the ID of your form
	var str="";
	for(var fl = 0;fl < pineapple.length; fl++)
	{ 
		str += pineapple[fl].name + "=" + pineapple[fl].value +"&";
	}
	page_request.send(str);
}
else
{
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
}
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}


function myPopupRelocate() {
 var scrolledX, scrolledY;
 if( self.pageYOffset ) {
   scrolledX = self.pageXOffset;
   scrolledY = self.pageYOffset;
 } else if( document.documentElement && document.documentElement.scrollTop ) {
   scrolledX = document.documentElement.scrollLeft;
   scrolledY = document.documentElement.scrollTop;
 } else if( document.body ) {
   scrolledX = document.body.scrollLeft;
   scrolledY = document.body.scrollTop;
 }

 var centerX, centerY;
 if( self.innerHeight ) {
   centerX = self.innerWidth;
   centerY = self.innerHeight;
 } else if( document.documentElement && document.documentElement.clientHeight ) {
   centerX = document.documentElement.clientWidth;
   centerY = document.documentElement.clientHeight;
 } else if( document.body ) {
   centerX = document.body.clientWidth;
   centerY = document.body.clientHeight;
 }

 var p_height = document.getElementById('p_cont').style.height;
 var p_height = p_height.replace("px", "");
 var p_width = document.getElementById('p_cont').style.width;
 var p_width = p_width.replace("px", "");
 var dy = (centerY - p_height) / 2;
 var dx = (centerX - p_width) / 2;

 if(dy<0)
    dy=10;

 if(dx<0)
    dx=10;

 var topOffset = scrolledY + dy;
 var leftOffset = scrolledX + dx;

 document.getElementById("popup").style.top = topOffset + "px";
 //document.getElementById("popup").style.top = t + "px";
 document.getElementById("popup").style.left = leftOffset + "px";
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
//popup

//error

/* FILE HEADER **************************************************
** JS Validate
** Author: Karl Seguin, Timo Haberkern
** Homepage: http://jsval.berlios.de/
** Version: 1.3.3
** Copyright 2003, 2005 Timo Haberkern, Karl Seguin

    This file is part of JS Validate.

    JS Validate is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    JS Validate is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with JS Validate; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
**
** END HEADER ***************************************************/

function validateCompleteForm (objForm, strErrorClass) {
    return _validateInternal(objForm, strErrorClass, 0);
};

function validateStandard (objForm, strErrorClass) {
    return _validateInternal(objForm, strErrorClass, 1);
};

/***************************************************************
** Internal functions
*****************************************************************/
function _validateInternal(form, strErrorClass, nErrorThrowType){
   var strErrorMessage = ""; var objFirstError = null;
   if (nErrorThrowType == 0){
    strErrorMessage = (form.err) ? form.err : _getLanguageText("err_form");
   };

   var fields = _GenerateFormFields(form);
   for (var i = 0; i < fields.length; ++i){
      var field = fields[i];
      if (!field.IsValid(fields)){
        field.SetClass(strErrorClass);
        if (nErrorThrowType == 1) {
            _throwError(field);
            return false;
        }else{
            if (objFirstError == null){
               objFirstError = field;
            }
            strErrorMessage = _handleError (field, strErrorMessage);
            bError = true;
        }
      } else {
      	field.ResetClass();
      }
   };
   if (objFirstError != null) {
      alert(strErrorMessage);
      objFirstError.element.focus();
      return false;
  };
  return true;
 };

 function _getLanguageText(id){
    objTextsInternal = new _jsVal_Language();
    objTexts = null;
    try {
        objTexts = new jsVal_Language();
    } catch (ignored){};
    switch (id) {
        case "err_form": strResult = (!objTexts || !objTexts.err_form) ? objTextsInternal.err_form : objTexts.err_form; break;
        case "err_enter": strResult = (!objTexts || !objTexts.err_enter) ? objTextsInternal.err_enter : objTexts.err_enter; break;
        case "err_select": strResult = (!objTexts || !objTexts.err_select) ? objTextsInternal.err_select : objTexts.err_select; break;
    };
    return strResult;
 };

 function _GenerateFormFields(form){
   var arr = new Array();
   for (var i = 0; i < form.length; ++i){
      var element = form.elements[i];
      
      
      var index = _getElementIndex(arr,element);
      //if it doesn't already exist, add it to our array, else merge the change
      if (index == -1){
         arr[arr.length] = new Field(element, form);
      }else{
         arr[index].Merge(element)
      };
   };
   return arr;
};

function _getElementIndex(arr, element){
   if (element.name) {
       var elementName = element.name.toLowerCase();
       for (var i = 0; i < arr.length; ++i){
       	  if (arr[i].element.name) { 
			   if (arr[i].element.name.toLowerCase() == elementName){
               	  return i;
               }
          };
       };
   }
   return -1;
};

/***************************************************************
** Standard translation
*****************************************************************/
function _jsVal_Language() {
    this.err_form = "Please enter/select values for the following fields:\n\n";
    this.err_select = "Please select a valid \"%FIELDNAME%\"";
    this.err_enter = "Please enter a valid \"%FIELDNAME%\"";
};

/***************************************************************
** Field Class
*****************************************************************/
function Field(element, form){
   this.type = element.type;
   this.element = element;
   this.exclude = element.exclude || element.getAttribute('exclude');
   this.err = element.err || element.getAttribute('err');
   this.required = _parseBoolean(element.required || element.getAttribute('required'));
   this.realname = element.realname || element.getAttribute('realname');
   this.elements = new Array();
   
   switch (this.type){
      case "textarea":
      case "password":
      case "text":
      case "file":
         this.value = element.value;
         this.minLength = element.minlength || element.getAttribute('minlength');
         this.maxLength = element.maxlength || element.getAttribute('maxlength');
         this.regexp = this._getRegEx(element);
         this.minValue = element.minvalue || element.getAttribute('minvalue');
         this.maxValue = element.maxvalue || element.getAttribute('maxvalue');
         this.equals = element.equals || element.getAttribute('equals');
         this.callback = element.callback || element.getAttribute('callback');
         break;
      case "select-one":
      case "select-multiple":
         this.values = new Array();
         for (var i = 0; i < element.options.length; ++i){
            if (element.options[i].selected && (!this.exclude || element.options[i].value != this.exclude)){
               this.values[this.values.length] = element.options[i].value;
            }
         }
         this.min = element.min || element.getAttribute('min');
         this.max = element.max || element.getAttribute('max');
         this.equals = element.equals || element.getAttribute('equals');
         break;
      case "checkbox":
         this.min = element.min || element.getAttribute('min');
         this.max = element.max || element.getAttribute('max');
         //no break, let it fall through to radio
      case "radio":
          this.required = _parseBoolean(this.required || element.getAttribute('required'));
          this.values = new Array();
          if (element.checked){
             this.values[0] = element.value;
          }
   		         
          this.elements[0] = element;
          break;
   };
};
Field.prototype.Merge = function(element){
   //never negate a require field
   var required = _parseBoolean(element.getAttribute('required'));
   if (required){
      this.required = true;
   };
   //all other cases (except required) we only add if there isn't already a value (first come first served)
   if (!this.err){
      this.err = element.getAttribute('err');
   };
   if (!this.equals){
   	  this.equals = element.getAttribute('equals');
   };
   if (!this.callback){
   	  this.callback = element.getAttribute('callback');
   };
   if (!this.realname){
      this.realname = element.getAttribute('realname');
   };
   if (!this.max){
      this.max = element.getAttribute('max');
   };
   if (!this.min){
      this.min = element.getAttribute('min');
   };
   if (!this.regexp){
      this.regexp = this._getRegEx(element);
   };
   if (element.checked){
      this.values[this.values.length] = element.value;
   };
   this.elements[this.elements.length] = element;
};
Field.prototype.IsValid = function(arrFields){
   switch (this.type){
      case "textarea":
      case "password":
      case "text":
      case "file":
         return this._ValidateText(arrFields);
      case "select-one":
      case "select-multiple":
      case "radio":
      case "checkbox":
         return this._ValidateGroup(arrFields);
      default:
         return true;
   };
};
Field.prototype.SetClass = function(newClassName){
   if ( (newClassName) && (newClassName != "") ) {
       if ( (this.elements) && (this.elements.length > 0)) {
          for (var i = 0; i < this.elements.length; ++i){
          	  if(this.elements[i].className != newClassName){
                this.elements[i].oldClassName = this.elements[i].className;
                this.elements[i].className = newClassName;
              }
          }
       }else{
       	  if(this.element.className != newClassName){
            this.element.oldClassName = this.element.className;
            this.element.className = newClassName;
          }
       };
   }
};
Field.prototype.ResetClass = function(){
	if ( (this.type != "button") && (this.type != "submit") && (this.type != "reset") ) {
   		if ( (this.elements) && (this.elements.length > 0)) {
      		for (var i = 0; i < this.elements.length; ++i){
      			if(this.elements[i].oldClassName){
         	 	  this.elements[i].className = this.elements[i].oldClassName;
         	 	}
         	 	else {
    	  	 	  this.element.className = "";
    	  		}
      		}
   		}else{
   			if(this.elements.oldClassName){
    	  	  this.element.className = this.element.oldClassName;
    	  	}
    	  	else {
    	  	  this.element.className = "";
    	  	}
   		};
	};
};
Field.prototype._getRegEx = function(element){
   regex = element.regexp || element.getAttribute('regexp')
   if (regex == null) return null;
   retype = typeof(regex);
   if (retype.toUpperCase() == "FUNCTION")
       return regex;
   else if ( (retype.toUpperCase() == "STRING") && !(regex == "JSVAL_RX_EMAIL") && !(regex == "JSVAL_RX_TEL")
   				&& !(regex == "JSVAL_RX_PC") && !(regex == "JSVAL_RX_ZIP") && !(regex == "JSVAL_RX_MONEY") 
				&& !(regex == "JSVAL_RX_CREDITCARD") && !(regex == "JSVAL_RX_POSTALZIP"))
   {
       nBegin = 0; nEnd = regex.length-1;
       if (regex.charAt(0) == "/") nBegin=1;
       if (regex.charAt(regex.length-1) == "/") nEnd=regex.length-2;
	   
       return new RegExp(regex.slice(nBegin, nEnd));
   }
   else {
       return regex;
   };
};
Field.prototype._ValidateText = function(arrFields){
   if ( (this.required) && (this.callback) ) {
   	  nCurId = this.element.id ? this.element.id : "";
   	  nCurName = this.element.name ? this.element.name : "";
   	  
   	  eval("bResult = "+this.callback+"('"+nCurId+"', '"+nCurName+"', '"+this.value+"');"); 
   	  if (bResult == false) {
   	  	 return false;
   	  };
   } else {	
	   //required value is empty
	   if (this.required && !this.value){
	      return false;
	   };
	   //value less than minlength
	   if (this.value && (this.minLength && this.value.length < this.minLength)){
	      return false;
	   };
	   //value is more than maxlength
	   if (this.value && (this.maxLength && this.value.length > this.maxLength)){
	      return false;
	   };
	   //value fails regular expression
	   if (this.regexp){
	   	  if (!_checkRegExp(this.regexp, this.value))
	   	  {
	   	  	  //the field isn't required, but there is a value
		      if (!this.required && this.value){
		         return false;
		      }
		      if (this.required){
		         return false;
		      }
	   	  }
	   	  else
	   	  {
	   	  	return true;
	   	  };
	   };
	   
	   
	   
	   //check equality
	   if (this.equals){
	   	   for (var i = 0; i < arrFields.length; ++i){
	       	   var field = arrFields[i];
	       	   if ( (field.element.name == this.equals) || (field.element.id == this.equals) ) {
	       	   	  if (field.element.value != this.value) {
	       	   	  	 return false;
	       	   	  };
	       	   	  break;
	       	   };
	       };
	   };
	   
	   //check against minvalue and maxvalue
	   if (this.required){
	      var fValue = parseFloat(this.value);
	      if ((this.minValue || this.maxValue) && isNaN(fValue)){
	         return false;
	      };
	      if ( (this.minValue) && (fValue < this.minValue) ) {
	         return false;
	      };
	      if ( (this.maxValue) && (fValue > this.maxValue) ) {
	         return false
	      };
	   };
   }
   return true;
};
Field.prototype._ValidateGroup = function(arrFields){
   if (this.required && this.values.length == 0){
      return false;
   };
   if (this.required && this.min && this.min > this.values.length){
      return false;
   };
   if (this.required && this.max && this.max < this.values.length){
      return false;
   };
   return true;
};

function _handleError (field, strErrorMessage) {
   var obj = field.element;
   strNewMessage = strErrorMessage + ( (field.realname)? field.realname : ((obj.id) ? obj.id : obj.name) ) + "\n";
   return strNewMessage;
};

function _throwError(field){
   var obj = field.element;
   switch (field.type){
      case "text":
      case "password":
      case "textarea":
      case "file":
         alert(_getError(field, "err_enter"));
         try {
         	obj.focus();
         }
         catch (ignore) {}
         break;
      case "select-one":
      case "select-multiple":
      case "radio":
      case "checkbox":
         alert(_getError(field, "err_select"));
         break;
      };
};

function _getError(field, str){
   var obj = field.element;
   strErrorTemp = (field.err) ? field.err : _getLanguageText(str);
   
   idx = strErrorTemp.indexOf( "\\n" );
   while ( idx > -1 ) {
   	strErrorTemp = strErrorTemp.replace( "\\n", "\n" );
    idx = strErrorTemp.indexOf( "\\n" );
   };
   
   return strErrorTemp.replace("%FIELDNAME%", (field.realname)? field.realname : ((obj.id) ? obj.id : obj.name));
};

function _parseBoolean(value){
   return !(!value || value == 0 || value == "0" || value == "false");
};

function _checkRegExp(regx, value){
  switch (regx){
//  case "JSVAL_RX_EMAIL":
 //   return ((/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,5})+$/).test(value));
  case "JSVAL_RX_TEL":
    return ((/^1?[\- ]?\(?\d{3}\)?[\- ]?\d{3}[\- ]?\d{4}$/).test(value));
  case "JSVAL_RX_PC":
    return ((/^[a-z]\d[a-z] ?\d[a-z]\d$/i).test(value));
  case "JSVAL_RX_ZIP":
    return ((/^\d{5}$/).test(value));
  case "JSVAL_RX_MONEY":
    return ((/^\d+([\.]\d\d)?$/).test(value));
  case "JSVAL_RX_CREDITCARD":
    return (!isNaN(value));
  case "JSVAL_RX_POSTALZIP":
    if(value.length == 6 || value.length == 7)
      return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
    if(value.length == 5 || value.length == 10)
      return((/^\d{5}(\-\d{4})?$/).test(value));
    break;
  default:
    return (regx.test(value));

  };
};

function startUpload(){
      document.getElementById('upload_process').style.visibility = 'visible';
      document.getElementById('upload_form').style.visibility = 'hidden';
      return true;
}

function stopUpload(success){
      var result = '';
      if (success == 1){
         result = '<span>The email has been sent successfully!<\/span><br/><br/>';
      }else if (success == 2){
         result = '<span>The email has been sent, please check your mailbox!<\/span><br/><br/>';
      }
      else {
         result = '<span>There was an error, please try again!<\/span><br/><br/>';
      }
      document.getElementById('upload_process').style.visibility = 'hidden';
      document.getElementById('upload_form').innerHTML = result + '<center><b><a href="javascript:hidepopup();">close this window</a></b></center>';
      document.getElementById('upload_form').style.visibility = 'visible';      
      return true;   
}


/***********************************************
* DD Tab Menu II script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

//Set tab to intially be selected when page loads:
//[which tab (1=first tab), ID of tab content to display (or "" if no corresponding tab content)]:
var initialtab=[1, "sc1"]

//Turn menu into single level image tabs (completely hides 2nd level)?
var turntosingle=0 //0 for no (default), 1 for yes

//Disable hyperlinks in 1st level tab images?
var disabletablinks=0 //0 for no (default), 1 for yes


////////Stop editting////////////////

var previoustab=""

if (turntosingle==1)
document.write('<style type="text/css">\n#tabcontentcontainer{display: none;}\n</style>')

function expandcontent(cid, aobject){
if (disabletablinks==1)
aobject.onclick=new Function("return false")
if (document.getElementById && turntosingle==0){
highlighttab(aobject)
if (previoustab!="")
document.getElementById(previoustab).style.display="none"
if (cid!=""){
document.getElementById(cid).style.display="block"
previoustab=cid
}

if(cid=="sc3")
{
	loadmap();
}else if(cid=="sc5")
{
	marq();
}


}
}

function highlighttab(aobject){
if (typeof tabobjlinks=="undefined")
collectddimagetabs()
for (i=0; i<tabobjlinks.length; i++)
tabobjlinks[i].className=""
aobject.className="current"
}

function collectddimagetabs(){

var tabobj=document.getElementById("ddimagetabs")
tabobjlinks=tabobj.getElementsByTagName("A")

	
}

function do_onload(){
var dd = testForObject("ddimagetabs");

if(dd)
{
		collectddimagetabs()
	expandcontent(initialtab[1], tabobjlinks[initialtab[0]-1])
}
}

	if (window.addEventListener)
		window.addEventListener("load", do_onload, false)
	else if (window.attachEvent)
		window.attachEvent("onload", do_onload)
	else if (document.getElementById)
	window.onload=do_onload


function tree()
{
document.write("<ul id='ddsubmenuside1' class='ddsubmenustyle'><li><a href='http://www.morfittpropertiestenerife.com/rentals/longtermrentals.php' style='font-style: italic;'> Long term rentals</a></li><li><a href='http://www.morfittpropertiestenerife.com/rentals/latest.php' style='font-style: italic;'>Latest Rentals</a></li></ul>");
document.write("<ul id='ddsubmenuside3' class='ddsubmenustyle'><li><a href='http://www.morfittpropertiestenerife.com/areas/adeje_golf.htm' style='font-style: italic;'>Adeje golf properties</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/golf_del_sur.htm' style='font-style: italic;'>Golf Del Sur Properties</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/callao_salvaje.htm' style='font-style: italic;'>Properties in Callao Salvaje</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/chayofa.htm' style='font-style: italic;'>Properties in Chayofa</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/costa_del_silencio.htm' style='font-style: italic;'>Properties in Costa del Silencio</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/el_madronal.htm' style='font-style: italic;'>Properties in El Madronal</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/el_veril_del_duque.htm' style='font-style: italic;'>Properties in El Veril del Duque</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/fanabe.htm' style='font-style: italic;'>Properties in Fanabe</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/la_caleta.htm' style='font-style: italic;'>Properties in La Caleta</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/las_galletas.htm' style='font-style: italic;'>Properties in Las Galletas</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/los_cristianos.htm' style='font-style: italic;'>Properties in Los Cristianos</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/los_gigantes.htm' style='font-style: italic;'>Properties in Los Gigantes</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/los_menores.htm' style='font-style: italic;'>Properties in Los Menores</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/palm_mar.htm' style='font-style: italic;'>Properties in Palm Mar</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/playa_de_la_arena.htm' style='font-style: italic;'>Properties in Playa de la Arena</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/playa_de_las_americas.htm' style='font-style: italic;'>Properties in Playa de Las Americas</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/playa_del_duque.htm' style='font-style: italic;'>Properties in Playa del Duque</a></li><li><a href='http://www.morfittpropertiestenerife.com/areas/san_eugenio_alto.htm' style='font-style: italic;'>Properties in San Eugenio Alto</a></li></ul>");
document.write("<ul id='ddsubmenuside2' class='ddsubmenustyle'><li><a href='http://www.morfittpropertiestenerife.com/about/abigthankstoourclients.php' style='font-style: italic;'>A big thanks to our clients</a></li></ul>");

}


//** All Levels Navigational Menu- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Usage Terms: http://www.dynamicdrive.com/notice.htm

//** July 7th, 08'- Creation Date

//** July 16th, 08'- Updated to v 1.3:
	//1) Adds "Side Bar" orientation option. 
	//2) Drop Down Menus now auto adjust their positioning if too close to either right or bottom window edges.
	//3) Enhanced IFRAME shim "coverage" on the page.

//** July 19th, 08'- Updated to v 1.31: Drop down menu now positions at top of window edge if there's neither room downwards or upwards to settle.
//** Aug 13th, 08'- v1.32: Moved "rel" attribute from menu's <li> elements to inner <a>, for validation reasons

//** Sept 10th, 08'- Updated to v 1.4:
	//1) Added optional "sliding" animation when sub menus are revealed.
	//2) Arrow images now dynamically positioned, instead of relying on CSS's "right" property

var ddlevelsmenu={

downarrowpointer: ["http://www.morfittpropertiestenerife.com/images/arrow-down.gif", 11,7], //path to "down arrow" image that gets added to main menu items (last 2 parameters should be width/height of img)
rightarrowpointer: ["http://www.morfittpropertiestenerife.com/images/arrow-right.gif", 12,12], //path to "right arrow" image that gets added to LI elements within drop down menu containing additional menus
hideinterval: 200, //delay in milliseconds before sub menu(s) disappears onmouseout.
revealanimate: true, //enable sliding animation when revealing sub menus? (true/false)
httpsiframesrc: "blank.htm", //If menu is run on a secure (https) page, the IFRAME shim feature used by the script should point to an *blank* page *within* the secure area to prevent an IE security prompt. Specify full URL to that page on your server (leave as is if not applicable).

///No need to edit beyond here////////////////////

topmenuids: [], //array containing ids of all the primary menus on the page
topitems: {}, //object array containing all top menu item links
subuls: {}, //object array containing all ULs
topitemsindex: -1,
ulindex: -1,
hidetimers: {}, //object array timer
shimadded: false,
isff3orabove: /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent) && RegExp.$1>=3, //detect FF3 or above

getoffset:function(what, offsettype){
	return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
},

getoffsetof:function(el){
	el._offsets={left:this.getoffset(el, "offsetLeft"), top:this.getoffset(el, "offsetTop")}
},

getwindowsize:function(){
	this.docwidth=window.innerWidth? window.innerWidth-10 : this.standardbody.clientWidth-10
	this.docheight=window.innerHeight? window.innerHeight-15 : this.standardbody.clientHeight-18
},

gettopitemsdimensions:function(){
	for (var m=0; m<this.topmenuids.length; m++){
		var topmenuid=this.topmenuids[m]
		for (var i=0; i<this.topitems[topmenuid].length; i++){
			var header=this.topitems[topmenuid][i]
			var submenu=document.getElementById(header.getAttribute('rel'))
			header._dimensions={w:header.offsetWidth, h:header.offsetHeight, submenuw:submenu.offsetWidth, submenuh:submenu.offsetHeight}
		}
	}
},

isContained:function(m, e){
	var e=window.event || e
	var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement)
	while (c && c!=m)try {c=c.parentNode} catch(e){c=m}
	if (c==m)
		return true
	else
		return false
},

addpointer:function(target, imgclass, imginfo){
	var pointer=document.createElement("img")
	pointer.src=imginfo[0]
	pointer.style.width=imginfo[1]+"px"
	pointer.style.height=imginfo[2]+"px"
	pointer.style.left=target.offsetWidth-imginfo[2]-2+"px"
	pointer.className=imgclass
	target.appendChild(pointer)
},

css:function(el, targetclass, action){
	var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig")
	if (action=="check")
		return needle.test(el.className)
	else if (action=="remove")
		el.className=el.className.replace(needle, "")
	else if (action=="add" && !needle.test(el.className))
		el.className+=" "+targetclass
},

addshimmy:function(target){
	var shim=(!window.opera)? document.createElement("iframe") : document.createElement("div") //Opera 9.24 doesnt seem to support transparent IFRAMEs
	shim.className="ddiframeshim"
	shim.setAttribute("src", location.protocol=="https:"? this.httpsiframesrc : "about:blank")
	shim.setAttribute("frameborder", "0")
	target.appendChild(shim)
	try{
		shim.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
	}
	catch(e){}
	return shim
},

positionshim:function(header, submenu, dir, scrollX, scrollY){
	if (header._istoplevel){
		var scrollY=window.pageYOffset? window.pageYOffset : this.standardbody.scrollTop
		var topgap=header._offsets.top-scrollY
		var bottomgap=scrollY+this.docheight-header._offsets.top-header._dimensions.h
		if (topgap>0){
			this.shimmy.topshim.style.left=scrollX+"px"
			this.shimmy.topshim.style.top=scrollY+"px"
			this.shimmy.topshim.style.width="99%"
			this.shimmy.topshim.style.height=topgap+"px" //distance from top window edge to top of menu item
		}
		if (bottomgap>0){
			this.shimmy.bottomshim.style.left=scrollX+"px"
			this.shimmy.bottomshim.style.top=header._offsets.top + header._dimensions.h +"px"
			this.shimmy.bottomshim.style.width="99%"
			this.shimmy.bottomshim.style.height=bottomgap+"px" //distance from bottom of menu item to bottom window edge
		}
	}
},

hideshim:function(){
	this.shimmy.topshim.style.width=this.shimmy.bottomshim.style.width=0
	this.shimmy.topshim.style.height=this.shimmy.bottomshim.style.height=0
},


buildmenu:function(mainmenuid, header, submenu, submenupos, istoplevel, dir){
	header._master=mainmenuid //Indicate which top menu this header is associated with
	header._pos=submenupos //Indicate pos of sub menu this header is associated with
	header._istoplevel=istoplevel
	if (istoplevel){
		this.addEvent(header, function(e){
		ddlevelsmenu.hidemenu(ddlevelsmenu.subuls[this._master][parseInt(this._pos)])
		}, "click")
	}
	this.subuls[mainmenuid][submenupos]=submenu
	header._dimensions={w:header.offsetWidth, h:header.offsetHeight, submenuw:submenu.offsetWidth, submenuh:submenu.offsetHeight}
	this.getoffsetof(header)
	submenu.style.left=0
	submenu.style.top=0
	submenu.style.visibility="hidden"
	this.addEvent(header, function(e){ //mouseover event
		if (!ddlevelsmenu.isContained(this, e)){
			if (typeof ddlevelsmenu.hidetimers[this._master][parseInt(this._pos)]!="undefined")
				clearTimeout(ddlevelsmenu.hidetimers[this._master][parseInt(this._pos)])
			if (this._istoplevel)
				ddlevelsmenu.css(this, "selected", "add")
			var submenu=ddlevelsmenu.subuls[this._master][parseInt(this._pos)]
			ddlevelsmenu.getoffsetof(header)
			var scrollX=window.pageXOffset? window.pageXOffset : ddlevelsmenu.standardbody.scrollLeft
			var scrollY=window.pageYOffset? window.pageYOffset : ddlevelsmenu.standardbody.scrollTop
			var submenurightedge=this._offsets.left + this._dimensions.submenuw + (this._istoplevel && dir=="topbar"? 0 : this._dimensions.w)
			var submenubottomedge=this._offsets.top + this._dimensions.submenuh
			//Sub menu starting left position
			var menuleft=(this._istoplevel? this._offsets.left + (dir=="sidebar"? this._dimensions.w : 0) : this._dimensions.w)
			if (submenurightedge-scrollX>ddlevelsmenu.docwidth){
				menuleft+= -this._dimensions.submenuw + (this._istoplevel && dir=="topbar" ? this._dimensions.w : -this._dimensions.w)
			}
			submenu.style.left=menuleft+"px"
			//Sub menu starting top position
			var menutop=(this._istoplevel? this._offsets.top + (dir=="sidebar"? 0 : this._dimensions.h) : this.offsetTop)
			if (submenubottomedge-scrollY>ddlevelsmenu.docheight){ //no room downwards?
				if (this._dimensions.submenuh<this._offsets.top+(dir=="sidebar"? this._dimensions.h : 0)-scrollY){ //move up?
					menutop+= - this._dimensions.submenuh + (this._istoplevel && dir=="topbar"? -this._dimensions.h : this._dimensions.h)
				}
				else{ //top of window edge
					menutop+= -(this._offsets.top-scrollY) + (this._istoplevel && dir=="topbar"? -this._dimensions.h : 0)
				}
			}
			submenu.style.top=menutop+"px"
			if (ddlevelsmenu.revealanimate==false || ddlevelsmenu.isff3orabove){ //apply shim immediately only if animation is turned off, or if on, in non FF2.x browsers
				ddlevelsmenu.positionshim(header, submenu, dir, scrollX, scrollY)
			}
			else{
				submenu.ff2scrollInfo={x:scrollX, y:scrollY}
			}
			ddlevelsmenu.showmenu(header, submenu, dir)
		}
	}, "mouseover")
	this.addEvent(header, function(e){ //mouseout event
		if (this._istoplevel){
			var submenu=ddlevelsmenu.subuls[this._master][parseInt(this._pos)]
			if (!ddlevelsmenu.isContained(this, e) && !ddlevelsmenu.isContained(submenu, e)) //hide drop down ul if mouse moves out of menu bar item but not into drop down ul itself
				ddlevelsmenu.hidemenu(submenu)
		}
		else if (!this._istoplevel && !ddlevelsmenu.isContained(this, e)){
			var headerlist=this
			ddlevelsmenu.hidetimers[this._master][parseInt(this._pos)]=setTimeout(function(){
				var submenu=ddlevelsmenu.subuls[headerlist._master][parseInt(headerlist._pos)]
				ddlevelsmenu.hidemenu(submenu)
			}, ddlevelsmenu.hideinterval)
		}
	}, "mouseout")
},

showmenu:function(header, submenu, dir){
	if (this.revealanimate){
		submenu._curanimatepoint=0
		var endpoint=(header._istoplevel && dir=="topbar")? submenu.offsetHeight : submenu.offsetWidth
		submenu.style.width=submenu.style.height=0
		submenu.style.overflow="hidden"
		submenu.style.visibility="visible"
		clearTimeout(submenu._animatetimer)
		submenu._animatetimer=setInterval(function(){ddlevelsmenu.revealmenu(header, submenu, endpoint, dir)}, 10)
	}
	else{
		submenu.style.visibility="visible"
	}
},

revealmenu:function(header, submenu, endpoint, dir){
	if (submenu._curanimatepoint<endpoint){
		if (submenu._curanimatepoint==0) //reset either width or height of sub menu to "auto" when animation begins
			submenu.style[header._istoplevel && dir=="topbar"? "width" : "height"]="auto"
		submenu._curanimatepoint= submenu._curanimatepoint + 5 + (submenu._curanimatepoint/10)
		submenu.style[header._istoplevel && dir=="topbar"? "height" : "width"]=submenu._curanimatepoint+"px"
	}
	else{
		if (submenu.ff2scrollInfo) //if this is FF2 or below (meaning shim hasn't been applied yet
			this.positionshim(header, submenu, dir, submenu.ff2scrollInfo.x, submenu.ff2scrollInfo.y)
		submenu.style[header._istoplevel && dir=="topbar"? "height" : "width"]="auto"
		submenu.style.overflow="visible"
		clearInterval(submenu._animatetimer)
	}
},


hidemenu:function(submenu){
	if (typeof submenu._pos!="undefined"){ //if submenu is outermost UL drop down menu
		this.css(this.topitems[submenu._master][parseInt(submenu._pos)], "selected", "remove")
		this.hideshim()
	}
	clearTimeout(submenu._animatetimer)
	submenu.style.left=0
	submenu.style.top="-1000px"
	submenu.style.visibility="hidden"
},


addEvent:function(target, functionref, tasktype) {
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false);
	else if (target.attachEvent)
		target.attachEvent('on'+tasktype, function(){return functionref.call(target, window.event)});
},

init:function(mainmenuid, dir){
	this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body
	this.topitemsindex=-1
	this.ulindex=-1
	this.topmenuids.push(mainmenuid)
	this.topitems[mainmenuid]=[] //declare array on object
	this.subuls[mainmenuid]=[] //declare array on object
	this.hidetimers[mainmenuid]=[] //declare array on object
	if (!this.shimadded){
		this.shimmy={}
		this.shimmy.topshim=this.addshimmy(document.body) //create top iframe shim obj
		this.shimmy.bottomshim=this.addshimmy(document.body) //create bottom iframe shim obj
		this.shimadded=true
	}
	var menubar=document.getElementById(mainmenuid)
	var alllinks=menubar.getElementsByTagName("a")
	this.getwindowsize()
	for (var i=0; i<alllinks.length; i++){
		if (alllinks[i].getAttribute('rel')){
			this.topitemsindex++
			this.ulindex++
			var menuitem=alllinks[i]
			this.topitems[mainmenuid][this.topitemsindex]=menuitem //store ref to main menu links
			var dropul=document.getElementById(menuitem.getAttribute('rel'))

			dropul.style.zIndex=2000 //give drop down menus a high z-index
			dropul._master=mainmenuid  //Indicate which main menu this main UL is associated with
			dropul._pos=this.topitemsindex //Indicate which main menu item this main UL is associated with
			this.addEvent(dropul, function(){ddlevelsmenu.hidemenu(this)}, "click")
			var arrowpointer=(dir=="sidebar")? "rightarrowpointer" : "downarrowpointer"

			this.addpointer(menuitem, arrowpointer, this[arrowpointer])
			this.buildmenu(mainmenuid, menuitem, dropul, this.ulindex, true, dir) //build top level menu
			//dropul.onmouseover=function(){
				//do nothing
			//}
			this.addEvent(dropul, function(e){ //hide menu if mouse moves out of main UL element into open space
				if (!ddlevelsmenu.isContained(this, e) && !ddlevelsmenu.isContained(ddlevelsmenu.topitems[this._master][parseInt(this._pos)], e)){
					var dropul=this
					ddlevelsmenu.hidetimers[this._master][parseInt(this._pos)]=setTimeout(function(){
						ddlevelsmenu.hidemenu(dropul)
					}, ddlevelsmenu.hideinterval)
				}
			}, "mouseout")
			var subuls=dropul.getElementsByTagName("ul")
			for (var c=0; c<subuls.length; c++){
				this.ulindex++
				var parentli=subuls[c].parentNode
				this.addpointer(parentli.getElementsByTagName("a")[0], "rightarrowpointer", this.rightarrowpointer)
				this.buildmenu(mainmenuid, parentli, subuls[c], this.ulindex, false, dir) //build sub level menus
			}
		}
	} //end for loop
	this.addEvent(window, function(){ddlevelsmenu.getwindowsize(); ddlevelsmenu.gettopitemsdimensions()}, "resize")
},

setup:function(mainmenuid, dir){
	this.addEvent(window, function(){ddlevelsmenu.init(mainmenuid, dir)}, "load")
}

}

