
function highlight_on(row,color){
  row.style.backgroundColor = color;
}
function highlight_off(row,color){
  row.style.backgroundColor = color;
}
function winpopopen(psrc,width,height){
winpop=window.open(basedir + "winpop.php?pic="+psrc+"&width="+width+"&height="+height,"ConsoleWindow","toolbar=no,,width="+(width+10)+",height="+(height+35)+",directories=no,status=no,scrollbars=no,resize=no,menubar=no");
winpop.focus();
}
function help(help_file){
winpop=window.open("help/"+help_file,"ConsoleWindow","toolbar=no,,width=400,height=250,directories=no,status=no,scrollbars=yes,resize=no,menubar=no");
winpop.focus();
}
function register(){
winpop=window.open("register.php","ConsoleWindow","toolbar=no,,width=400,height=450,directories=no,status=no,scrollbars=yes,resize=no,menubar=no");
winpop.focus();
}

var popUpWin=0; 
function popUpWindow(URLStr, left, top, width, height, scrollbar) { if(popUpWin) 
{ if(!popUpWin.closed) popUpWin.close(); } 
if (!scrollbar)
	scrollbar = 'no';
popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menub ar=no,scrollbars='+scrollbar+',resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+''); } 


function mouseon(cell){
  if(document.all){
  cell.style.background = '#0066CC';
  }
}
function mouseout(cell){
  if(document.all){
  cell.style.background = '';
  }  
}


function contact_display(show,hide){
	if (show)
		document.getElementById(show).style.display='block';
	if (hide)
		document.getElementById(hide).style.display='none';
	window.scrollTo(window.scrollLeft,parseInt(document.body.clientHeight));
}



function saveListDialog(){
	if (!this.rounded){
		Rounded("div#favouritesConfirmWrapper","transparent","#FFEFB8");
		this.rounded = 1;
	}
	d("favouritesConfirmWrapper").style.display='block';
	d("favouritesConfirmEmail").focus();
}
function saveListConfirm(data){
	var t;
	if (t = d("favouritesConfirmWrapper")) t.style.display='none';
	if (t = d("favouritesButton")){
		t.innerHTML = "Added to Favourites";
		t.href =  basedir + path_buy_property + 'favourites.php';
	}
	// setting cookies is done serverside
	//setCookie('members_id', data, 1000);
	//alert(data)
}
function requestEmailUpdate(stock_id){
	email = d("favouritesConfirmEmail").value;
	if (!is_email(email)){
		alert("Valid Email Address Required");
		return
	}
	saveList(stock_id, email, 1)
}
function saveList(stock_id, email, notify){
	if (!email)
		email = "";
	if (!notify)
		notify = 0;
	members_number = getCookie('members_number');
	json = new JsonRequest('json', new Function('data','saveListConfirm(data)')); // ajax/json request handler object
	json.makeRequest(basedir + "ajax/favourites.php?stock_id=" + stock_id + "&email=" + email + "&members_number=" + members_number + "&notify=" + notify);
}

function removeDuplicates(a){
  var seen = new Array();
  var new_array = new Array();
  b=0;
  for (var i = 0; i < a.length; ++i) {
    if (!seen[a[i]]) {
	  	seen[a[i]] = true;
		new_array[b] = a[i];
		b++;
	 }
  } 
	return new_array;
}


 function setCookie (name, value, days) {
	var expires = new Date(); 
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	//var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	expires.setTime(expires.getTime() + days*24*60*60); 
	cookiestr = name + "=" + escape (value) +
	  ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	  ((path == null) ? "" : ("; path=" + path)) +
	  ((domain == null) ? "" : ("; domain=" + domain)) +
	  ((secure == true) ? "; secure" : "");
	 document.cookie = cookiestr;
 }

function getCookie (name) {
var dc = document.cookie;
var cname = name + "=";
var clen = dc.length;
var cbegin = 0;

while (cbegin < clen) { 
    var vbegin = cbegin + cname.length;

    if (dc.substring(cbegin, vbegin) == cname) { 
    var vend = dc.indexOf (";", vbegin);
    if (vend == -1) vend = clen;

    return unescape(dc.substring(vbegin, vend));
    }

    cbegin = dc.indexOf(" ", cbegin) + 1;

    if (cbegin== 0) break;
    }
    return "";
}

function showlist(){
	alert (getCookie(cookieName));
}


function DeleteCookie (name) {  
var exp = new Date();  
exp.setTime (exp.getTime() - 1);  
var cval = getCookie (name);  
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

// end of cookie functions

function printable(stock_id){
	printWin = window.open(url_base+"real_estate/printable.php?stock_id="+stock_id,"PrintableVersion","toolbar=no,width=680,height=480,directories=no,status=no,scrollbars=yes,resize=no,menubar=no");
	printWin.focus();
}

function favourites_printable(stock_id){
	printWin = 	window.open("favourites_printable.php","PrintableVersion","toolbar=no,width=640,height=480,directories=no,status=no,scrollbars=yes,resize=no,menubar=no");
	printWin.focus();
}

function rental_printable(stock_id){
	printWin = window.open("rental_printable.php?stock_id="+stock_id,"PrintableVersion","toolbar=no,width=640,height=480,directories=no,status=no,scrollbars=yes,resize=no,menubar=no");
	printWin.focus();
}

function is_email(email_addr){
  var addressPattern = 
    /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,10}$/;
  return addressPattern.test(email_addr);	
}

function contains_numbers(string){
  var addressPattern = 
    /[0-9]+/;
  return addressPattern.test(string);	
}

function validate(frm){
	var form_validated = true;
	
	for (i=0; i < frm.elements.length; i++){
		validated = false;
		
		if (frm.elements[i]){
			if (validation = frm.elements[i].getAttribute("validate")){
			
				// validate using callback function
				val_elements = validation.split(":");
				// test to see if field validation is optional (ie only test if there is a value - it is OK to be blank)
				reg = /^optional_/;
				if (reg.test(val_elements[0])){
					if (frm.elements[i].value.length == 0)
						validated = true;
					else
						val_elements[0] = val_elements[0].replace(reg,"");
				}
				
				functionName = "validate_" + val_elements[0]

				// allow override if already validated above
				// run the function to validate
				if (!validated)
					validated = eval(functionName)(frm.elements[i],val_elements[1]);

				if (validated == false){
					form_validated = false;
					// create the response (only if not exists)
					if (!d(frm.elements[i].name + "_response")){
						r = document.createElement("div");
						r.innerHTML = frm.elements[i].getAttribute("validate_response");
						r.className = "validation_response";
						r.id = frm.elements[i].name + "_response";
						
						// see if there is a dedicated container for the response
						if(d("response_container:"+frm.elements[i].name))
							container = d("response_container:"+frm.elements[i].name)
						else
							container = frm.elements[i].parentNode
						container.appendChild(r);
					}
				}else{
					// remove the response if it exists
					if (response = document.getElementById(frm.elements[i].name + "_response")){
						// see if there is a dedicated container for the response
						if(d("response_container:"+frm.elements[i].name))
							container = d("response_container:"+frm.elements[i].name)
						else
							container = frm.elements[i].parentNode						
						container.removeChild(response);
					}
				}
			}
		}
	}
	if (form_validated == false){
		alert("There are some required fields that you need to complete before submitting this form. We have highlighted them for you  above. Please complete these fields before continuing");
		return false;
	}else{
		return true;
	}
}

function validate_min_length(form_element,required_length){
	required_length = parseInt(required_length);
	if (form_element.value.length >= required_length)
		return true;
	else
		return false;
}

function validate_max_length(form_element,required_length){
	required_length = parseInt(required_length);
	if (form_element.value.length > required_length)
		return false;
	else
		return true;
}

function validate_is_email(form_element){
	return is_email(form_element.value);
}

function validate_checked(form_element){
	return form_element.checked == true;
}

function validate_cc_number(form_element){
	// note the function referred to is in a different file
	return CheckCardNumber(form_element.value);
}

function validate_match_field(form_element,match_element_id){
	if (form_element.value == d(match_element_id).value)
		return true;
	else
		return false;
}

function validate_is_date(form_element){
	return is_date(form_element.value);
}

function is_date(string) {
  var datePattern = 
    /^[0-9]{1,2}\/[0-9]{1,2}\/([0-9]{2}|[0-9]{4})$/;
  return datePattern.test(string);
}

  function restoreStyles(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++)
      inputList[i].style.backgroundColor = "";
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++)
      selectList[i].style.backgroundColor = "";
  }


var val = Array();
var highlight = "#FFCC99";

function check_contact(theform){
	error = ""
	if (!theform.name.value) error += "Please enter your name\n";
	if (!theform.phone.value) error += "Please enter your phone number\n";
	if (!theform.email.value) error += "Please enter your email address\n";
	if (!theform.message.value) error += "Please enter a message\n";
	
	if (error){
		alert ("Error\n\n" + error);
		return false;
	}else{
		return true;
	}
}


function populate(parentSel,parentSelVal,childSel,arrChildren,selectedVal) {
	//alert(var_dump(selectedVal));
	// next two lines are specific - rest is generic
	if (parentSel){
		if (parentSel.id == "search_region_id")
			depopulate(d('search_realenz_suburb_no'))
	}
	
	if (parentSel)
		parentSelVal = parseInt(parentSel.options[parentSel.options.selectedIndex].value);
	
	if (parentSelVal) {
		childSel.disabled = false;
		childSelLength = arrChildren[parentSelVal].length;
		childSel.options.length = childSelLength + 1;
		childSel.options[0] = new Option("All","");
		arrChildrenElements = new Array();
		count = 0;
		x="";
		for (i=0; i < childSelLength; i++) {
			arrChildrenElements = arrChildren[parentSelVal][i].split("|");
			childSel.options[i+1] = new Option(arrChildrenElements[1],arrChildrenElements[0]);
			if (selectedVal){
				if (in_array(arrChildrenElements[0],selectedVal)){
					childSel.options[i+1].selected = true;
				}
			}
		}	
	} else {
		depopulate(childSel)
	}
	//alert(count);
}

// slightly different version of the above - needs tidying into one function
function populate_new_listing_general(parentSel,parentSelVal,childSel,arrChildren,selected) {
	if (!selected)
		selected = 0;
	// next two lines are specific - rest is generic
	if (parentSel.id == "realenz_district_no"){
		if (d('stock[stock_suburb_id]'))
			depopulate(d('stock[stock_suburb_id]'))
	}
	
	if (parentSel)
		parentSelVal = parseInt(parentSel.options[parentSel.options.selectedIndex].value);
	
	if (parentSelVal) {
		childSel.disabled = false;
		childSelLength = arrChildren[parentSelVal].length;
		childSel.options.length = childSelLength + 1;
		childSel.options[0] = new Option("Please Select","");
		arrChildrenElements = new Array();
		for (i=0; i < childSelLength; i++) {
		  arrChildrenElements = arrChildren[parentSelVal][i].split("|");
		  childSel.options[i+1] = new Option(arrChildrenElements[1],arrChildrenElements[0]);
		  if (selected == arrChildrenElements[0])
		  	childSel.options[i+1].selected = true;	
		}
	} else {
		depopulate(childSel)
	}
}

function depopulate(sel){
	sel.options.length = 1;
	sel.disabled = true;
}

function in_array(needle,haystack){
	var retVal = false;
	for (z in haystack){
		if (needle == haystack[z])
			retVal = true;
	}
	return retVal
}
	
function var_dump(arr){
	var out = "";
	if (!arr)
		return false;
	for (b in arr){
		out += b + " = " + arr[b] + "\n";
	}
	return out;
}

var popUpWin = 0;

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

// FUNCTIONS DEALING WITH OPENING AND CLOSING OF MAP ON THE SEARCH FORM

function toggle_map(){
	div = d("nz_map_container");
	div.style.display = "block";
	divHeight = parseInt(getStyle(div, "height")); // get the style from stylesheet
	div.style.height = divHeight + "px" // set the inline style
	if(divHeight == mapMinHeight){ // slide open
		d("a_toggle_map").style.display = 'none';
		slide_map_open(div,30);
	}else{
		slide_map_closed(div,30);
	}
}

function slide_map_open(div, increment){
	if (!div.style.height)
		div.style.height = getStyle(div, "height");
	divHeight = parseInt(div.style.height);
	mapHeight = 231;
	if ((divHeight + increment) > mapHeight)
		increment = mapHeight - divHeight; // make sure we don't overshoot
	if (divHeight >= mapHeight){
		div.style.height = mapHeight;
	}else{
		div.style.visibility = "visible"
		div.style.height = divHeight + increment + "px";
		window.setTimeout( function(){ slide_map_open(div,increment) },1);
	}
}

function slide_map_closed(div, increment){
	if (!div.style.height)
		div.style.height = parseInt(getStyle(div, "height"));
	divHeight = parseInt(div.style.height);
	if ((divHeight - increment) < mapMinHeight)
		increment = divHeight - mapMinHeight; // make sure we dont overshoot
	if (divHeight <= mapMinHeight){
		div.style.height = mapMinHeight + "px";
		div.style.visibility = "hidden"
		document.getElementById("a_toggle_map").style.display = 'block';
	}else{
		div.style.height = divHeight - increment + "px";
		window.setTimeout( function(){ slide_map_closed(div,increment) },1);
	}
}

var ghost_addEvent = function(o, t, f, l)
{
	var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
	if (o[d] && !l) return o[d](t, f, false);
	if (!o._evts) o._evts = {};
	if (!o._evts[t])
	{
	 o._evts[t] = o[n] ? { b: o[n] } : {};
	 o[n] = new Function('e',
		'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
		 'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
		 '} '+(t=='beforeunload'?'if(r)':'')+'return r');
	 if (t != 'unload') ghost_addEvent(window, 'unload', function() {
		ghost_removeEvent(rO, rT, rF, rL);
	 });
	}
	if (!f._i) f._i = ghost_addEvent._i++;
	o._evts[t][f._i] = f;
};

ghost_addEvent._i = 1;
var ghost_removeEvent = function(o, t, f, l)
{
var d = 'removeEventListener';
if (o[d] && !l) return o[d](t, f, false);
if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
};

function d(el){
	return document.getElementById(el);
}

function getRealLeft(el, topEl) { 
	xPos = el.offsetLeft; tempEl = el.offsetParent; 
	while (tempEl != null && tempEl != topEl) { 
		xPos += tempEl.offsetLeft; 
		tempEl = tempEl.offsetParent; 
	} 
	return xPos; 
} 

function getRealTop(el, topEl) { 
	yPos = el.offsetTop; tempEl = el.offsetParent; 
	while (tempEl != null && tempEl != topEl) { 
		yPos += tempEl.offsetTop; 
		tempEl = tempEl.offsetParent; 
	} 
	return yPos; 
} 

//Assign the returned values to variables in this way: 

function return_positions(el,topEl) {
	trueX = getRealLeft(el,topEl); 
	trueY = getRealTop(el,topEl); 
	pos = new Array();
	pos['x'] = trueX;
	pos['y'] = trueY;
	return pos;
}


// TOOL TIPS SETUP SECTION
function setupToolTips(){
	for (x=0;x < document.forms.length; x++){
		frm = document.forms[x];
		for (i=0;i < frm.elements.length; i++){
			if (frm.elements[i].getAttribute("tip"))
				initTip(frm.elements[i]);
		}
	}
	// container
	tip = document.createElement("DIV");
	tip.id = "overLayTip";
	tip.className = "overLayTip";
	document.body.appendChild(tip);
	// round the corners using nifty
	// inner div
	tipContents = document.createElement("DIV");
	tipContents.id = "overLayTipContents";
	tipContents.className = "overLayTipContents";
	tip.appendChild(tipContents);
	Rounded("div#overLayTip","transparent","#9BD1FA");
}

function initTip(el){
	ghost_addEvent(el,"focus",function(){showTip(el)});
	ghost_addEvent(el,"mouseover",function(){showTip(el)});
	ghost_addEvent(el,"blur",function(){hideTip(el)});
	ghost_addEvent(el,"mouseout",function(){hideTip(el)});
}

function showTip(el){
	tipTimer = window.setTimeout(function(){ displayTip(el) },300);
}

function displayTip(el){
	thisPos = return_positions(el);
	
	// try and figure out the width of the element
	if (contains_numbers(getStyle(el,"width")))
		width = parseInt(getStyle(el,"width"));
	else if(el.width)
		width = el.width;
	else
		width = 0;
	
	
	if (el.getAttribute("tip_offset"))
		offset = el.getAttribute("tip_offset").split(",");
	else
		offset = Array(0,0);
	
	offSetLeft = 0;
	if (el.getAttribute("tip_align")){
		if (el.getAttribute("tip_align") == "left"){
			d("overLayTip").className = "overLayTipLeft";
			offSetLeft = -(parseInt(getStyle(d("overLayTip"),"width")));
			width = -25;
		}else{
			d("overLayTip").className = "overLayTip";
		}
	}else{
		d("overLayTip").className = "overLayTip";
	}
	
	d("overLayTip").style.top = (thisPos['y'] + parseInt(offset[1])) + "px";
	d("overLayTip").style.left = (thisPos['x'] + width + parseInt(offset[0]) + 5) + offSetLeft + "px";
	d("overLayTipContents").innerHTML = el.getAttribute("tip");
	window.clearTimeout(tipTimer);
	fadeInTip(d("overLayTip"));
}


function hideTip(el){
	window.clearTimeout(tipTimer);
	fadeOutTip(d("overLayTip"), (d("overLayTip").style.opacity*100));
}
var tipTimer;
function fadeInTip(el, opacity){
	if (!el) return;
	intervals = 25;
	finalOpacity = 100;
	
	if (document.all){
		el.filters[0].Apply();
		el.style.visibility = "visible";
		el.filters[0].Play();
		return;
	}	
	
	if (!opacity){
		opacity = 0;
		el.style.visibility = "visible";
	}
	
	if (opacity < finalOpacity){
		newOpacity = opacity + intervals
		el.style.opacity = newOpacity/100;
		el.style.filter = 'alpha(opacity=' + newOpacity + ')';
		tipTimer = window.setTimeout(function (){ fadeInTip(el, newOpacity) }, 50);
	}else{
		window.clearTimeout(tipTimer);
	}
}
function fadeOutTip(el, opacity){
	if (!el) return;
	intervals = -25;
	finalOpacity = 0;
	
	if (document.all){
		el.filters[0].Apply();
		el.style.visibility = "hidden";
		el.filters[0].Play();
		return;
	}
	
	if (opacity == 0){
		el.style.visibility = "hidden";
	}
	if (opacity > finalOpacity){
		newOpacity = opacity + intervals
		el.style.opacity = newOpacity/100;
		el.style.filter = 'alpha(opacity=' + newOpacity + ')';
		tipTimer = window.setTimeout(function (){ fadeOutTip(el, newOpacity) }, 50);
	}else{
		window.clearTimeout(tipTimer);
	}
}

// create an onload event to set up the tooltips
ghost_addEvent(window,"load",function (){ setupToolTips();});


function check_search_form(frm){
	// clear the field if they have not entered anything (get rid of the tool tip)
	if (el = frm.elements['stock_number']){
		if (el.value == el.defaultValue)
			el.value = '';
	}
	if (el2 = frm.elements['keywords']){
		if (el2.value == el2.defaultValue)
			el2.value = '';
	}
}

function set_search_form(region_id){
	populate('',1,d('search_region_id'),arr_region);
	d("search_region_id").value = region_id;
	populate(d('search_region_id'),'',d('search_realenz_city_no'),arr_city);
	toggle_map();
}

function hide_side_bar(){
	if (sidebarBehavior == 'static_closed')
		return true;
	if (sidebarBehavior == 'static_open')
		return false;
	sb = document.getElementById("searchbox")
	c = document.getElementById("content")
	
	if (c.className == "content"){
		setCookie("wideScreen",1,user_cookie_expire, cookie_path );
		c.className = "contentWidescreen";
		sb.className = "searchboxWidescreen";
	}else{
		setCookie("wideScreen",0,user_cookie_expire, cookie_path);
		c.className = "content";
		sb.className = "searchbox";
	}	
	return false;
}

function check_email_exists(email_field){
// uses an ajax call to see if an email address exists in the database...
// returns 'email_exists' if there is a clash
	json = new JsonRequest('json', new Function('data','check_email_exists_response("'+email_field.id+'",data)')); // ajax/json request handler object
	json.makeRequest(basedir + "ajax/check_email_exists.php?email=" + email_field.value);
}

function check_email_exists_response(email_field,data){
	if (data == 'email_exists'){
		alert('Sorry to interrupt...\n\nWhile you were typing, we checked our database and noticed that the email address you just entered already exists. If you have an account with us, then you need to visit the login page. If you still want to create a new account, please choose a different email address.\n');
		d(email_field).value = "";
		d(email_field).focus();
	}
}

var calRegistered = Array();
function setup_calendar(field, _align){ 
	
	if (!in_array(field.id, calRegistered)){
		calRegistered[calRegistered.length] = field.id;
		if (!_align)
			_align = "Tr"
		Calendar.setup({
			inputField     :    field.id,       // id of the input field
			ifFormat       :    "%d/%m/%y",       // format of the input field
			singleClick    :    true,           // double-click mode
			step           :    1,                // show all years in drop-down boxes (instead of every other year as default)
			align		   :    _align,
			eventName      :    "focus",
			cache		   :	1
		});
	}
}

function stopEventPropagation(evt){
	try{
		evt.stopPropagation();
	}catch(err){
		evt.cancelBubble = true;
	}
}