	

	/* Input validation original and error colours */
	var origBorder = "1px solid #ccc";
	var origBorder2 = "1px solid #7F9DB9";
	var errorBorder = "1px solid red";
	var origBackground = "";
	var errorBackground = "#fdf3f3";
	
	/* Array of disabled sections */
	var disabled= new Array()
	
	/* For startTimer function - Sets timer for keystrokes in active search */ 
	var timerId;
	
	/* Timer for hiding comment*/
	var timerComment;
	
	/*
	 * G E N E R A L  F U N C T I O N S
	 */

	/* Set up the refresh page timer (ms) */
	//var intRefreshPeriod = 500000;
	//var timerRefresh = setTimeout('refreshPage()',intRefreshPeriod);

	/* Call a simple remote query to keep the connection alive */
	function refreshPage() {
		var fragment = "refresh.php?date=" + Date();
		loadFragment(fragment,  onPageRefreshed);
	}

	/* Call back function for the refresh page */
	function onPageRefreshed(namevaluepairs) {

		// clear the timeout and setup a new timer
		clearTimeout(timerRefresh);
		timerRefresh = setTimeout('refreshPage()',intRefreshPeriod);
		
		// make the remote query 
		var oQuery = validateCallBackData(namevaluepairs);
		if(!oQuery) return false;
		//else addComment("Refreshed page...");
	}
	 
	/* Generic function to replace getElementById */ 
	function element(id) { 
		var elem = document.getElementById(id);	
		if(!elem) { 
			alert("Error: form element '" + id + "' not found");	
			return false;
		}
		return elem;
	}
	 
	 
	/* Trim functions : Trim, LTrim, RTrim */

	function Trim(TRIM_VALUE) {
		if(TRIM_VALUE.length < 1){
			return "";
		}
		TRIM_VALUE = RTrim(TRIM_VALUE);
		TRIM_VALUE = LTrim(TRIM_VALUE);
		if(TRIM_VALUE==""){
			return "";
		} else {
			return TRIM_VALUE;
		}
	}
	
	function RTrim(VALUE) {
		var w_space = String.fromCharCode(32);
		var v_length = VALUE.length;
		var strTemp = "";
		
		if(v_length < 0){
			return "";
		}
		var iTemp = v_length -1;
	
		while(iTemp > -1){
			if(!(VALUE.charAt(iTemp) == w_space))
			{
				strTemp = VALUE.substring(0,iTemp +1);
				break;
			}
			iTemp = iTemp-1;
		}
		return strTemp;
	}
	
	function LTrim(VALUE) {
		var w_space = String.fromCharCode(32);
		if(v_length < 1){
			return"";
		}
		var v_length = VALUE.length;
		var strTemp = "";
		var iTemp = 0;
		
		while(iTemp < v_length){
			if(VALUE.charAt(iTemp) == w_space){
			}
			else{
				strTemp = VALUE.substring(iTemp,v_length);
				break;
			}
			iTemp = iTemp + 1;
		}
		return strTemp;
	}

	/* Text box validations 
	 * Note: These are now replacement functions, might be worth of considering e.g. match and highlight bg 
	 */

	/* Trims whitespace from left and right */
	function valTrim() {
		var elem = event.srcElement;		
		elem.value = Trim(elem.value);		
	}
	
	/* Applies for minutes and hours, allows two digits, only numbers*/
	function valHour() {
		var pattern = /[^0-9]/g ;
		var elem = event.srcElement;		
		elem.value = elem.value.replace(pattern,'');
	}

	/* Strips everything but number and dot */
	function valDecimal() {
		var pattern = /[^0-9.]+/g ;
		var elem = event.srcElement;
		//elem.style.background = errorBackground;			
		elem.value = elem.value.replace(pattern,'');
	}	
	
	/* Strips everything but numbers, and limit to x options */
	function valMaxDropdowns() {		
		var maxOptions = 100
		
		var pattern = /[^0-9]/g ;
		var elem = event.srcElement;
		elem.value = elem.value.replace(pattern,'');
			
		/* Limit */
		if(elem.value > maxOptions) {
			elem.value = maxOptions ;
			alert("Maximum " + maxOptions + " allowed");
		}
	
	}	

	/* Strips everything but numbers */
	function valInteger() {		
		var pattern = /[^0-9]/g ;
		var elem = event.srcElement;
		elem.value = elem.value.replace(pattern,'');
	}	

	/* Strips everything but numbers */
	function valYear() {		
		var pattern = /[^0-9]/g ;
		var elem = event.srcElement;
		elem.value = elem.value.replace(pattern,'');
	}	

	function valPhone() {		
		//var pattern = /[^0-9()\+\ #]/g ;
		//var elem = event.srcElement;
		//elem.value = elem.value.replace(pattern,'');
	}	

	/* Character counts */
	
	/* TODO: Note that event.srcElement is not cross browser compliant. Especially un next function when also a parameter need to be passed */
	function taLimit() {
		var taObj = event.srcElement;
		if (taObj.value.length == taObj.maxLength * 1) return false;
	}
	
	function taCount(visCnt) { 
		var taObj = event.srcElement;
		var lines = (taObj.value.length - taObj.value.length%57)/57;
	
		/* Grow the description box dynamically */
		taObj.style.height = 80 + (lines*15);
	
		if (taObj.value.length>taObj.maxLength*1) taObj.value = taObj.value.substring(0,taObj.maxLength * 1);
		if (visCnt) visCnt.innerText = taObj.maxLength-taObj.value.length;
	}

	/* Obsolete function : replaced by URLEncode */
	function URLencode(sStr) {
		alert("Called URLencode - rename to URLEncode")
		return URLEncode(sStr);
		//return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27');
	}


	/* Validates the URL */
	function isURL(urlStr){
		if (urlStr.indexOf(" ")!=-1){ return "Spaces are not allowed in a URL"; }
		if (urlStr==""||urlStr==null){ return "Please enter a link text"; }
		urlStr=urlStr.toLowerCase();
		var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
		var validChars="\[^\\s" + specialChars + "\]";
		var atom=validChars + '+';
		var urlPat=/^http:\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
		var matchArray=urlStr.match(urlPat);
		if (matchArray==null){ return "The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s"; }
		var user=matchArray[2];
		var domain=matchArray[3];
		for (i=0; i<user.length; i++) {if (user.charCodeAt(i)>127) { return "This domain contains invalid characters."; }}
		for (i=0; i<domain.length; i++) {if (domain.charCodeAt(i)>127) { return "This domain name contains invalid characters."; }}
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (i=0;i<len;i++) {if (domArr[i].search(atomPat)==-1) { return "The domain name does not seem to be valid."; }}
		//if (domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {alert("The address must end in a well-known domain or two letter " + "country.");return false;}
		return "";
		
		/* Rewritten because was too strict for suncoaster virtual tours */
		/*var v = new RegExp();
    	v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    	if (!v.test(urlStr)) {  return "The URL seems incorrect"; }
		return "";*/
	}
	
	/* Pauses for x amount of milliseconds*/ 
	function pause(Amount) {
		d = new Date() //today's date
		while (1)
		{
			mill=new Date() // Date Now
			diff = mill-d //difference in milliseconds
			if( diff > Amount ) {break;}
		}
	}
	
	function isFunction(a) {
		return typeof a == 'function';
	}
	
	function isObject(a) {
    	return (a && typeof a == 'object') || isFunction(a);
	}
	
	//chk if an object is an array or not.
	function isArray(a) {
		return isObject(a) && a.constructor == Array;
	}


	
	/* Gets a querystring format cookie - retuns array type object with all name value pairs*/
	function getCookieDetails(strNameValuePairs) {
		if(!strNameValuePairs) return;
		//try {
			var aURLQuery=strNameValuePairs.split(/[&]/), 
			re=/(.*)=(.*)/, 
			i=aURLQuery.length, 
			oURLQuery={}, 
			aTemp,
			strOldItem; 
			while(i-- > 0){ 
				aTemp=re.exec(aURLQuery[i]); 
				
				/* When the item already exists, recreate it as an array and add new item into it */
				if(oURLQuery[aTemp[1]]) {
					/* Check if array */
					if (!isArray(oURLQuery[aTemp[1]]) ) {
						/* Temp store the existing string item */
						strOldItem = oURLQuery[aTemp[1]];
						/* Replace it with a new array */
						oURLQuery[aTemp[1]] = Array();
						/* Append the old string into the array */
						oURLQuery[aTemp[1]].push(strOldItem)	
					}
					/* Append the new string into the array */
					oURLQuery[aTemp[1]].push(unescape(aTemp[2]));
				} else {
					/* For new items, just add it as string */
					oURLQuery[aTemp[1]]=unescape(aTemp[2]);			
				}
				
				// Debug - alert ( key : value )
				// alert(aTemp[1] + " : " + unescape(aTemp[2]));
			}
	//	} catch(er) {
	//		alert("Error calidating search history cookie. Please contact support@reedusdesign.com");	
	//	}
		/* Return object (associative array of name value pairs ) */
		return oURLQuery; 	
	}
	

	function makeQueryStringArrayFromSelect(strId, elemSelect) {
		var ret = "";
		var i;
		var count = 0;
		for (i=0; i<elemSelect.options.length; i++) {
			if (elemSelect.options[i].selected) {
				if(elemSelect.options[i].value == "-1") return ""; // If -1 included, means that "Choose.." is selected
				ret = ret + "&" + strId + "=" + elemSelect.options[i].value;
				
				count++;
			}
		}
					
		return ret;
	}
	 
	function clearSearchHistory() {	
		deleteCookie('ADVHistory.vendor_id');			
		deleteCookie('ADVHistory.buyer_id');			
		deleteCookie('ADVHistory.property_id');	
		deleteCookie('ADVHistory.search_details_advanced');
		deleteCookie('ADVHistory.search_details');
		deleteCookie('ADVHistory.contact_search_details');
		deleteCookie('ADVHistory.featured_description');	
	}
	
	function validateCallBackData(namevaluepairs) {

		if(namevaluepairs == null) {
			alert("Error: Cannot validate callback data, null parameter");
			return false;	
		}
		var oQuery = stripQuerystring(namevaluepairs); 
		if(!oQuery) { 
			namevaluepairs = namevaluepairs.split('\n');
			if(namevaluepairs.length > 5) {
				for(i=0; i < 5; i++) {
					namevaluepairs += namevaluepairs[i];	
				}
			}
			alert("ERROR: Failed to validate call back data :" + namevaluepairs );
			return null;
		}
	
		if(oQuery["errorno"] != 0 && oQuery["errorno"] != "" )  {
			if(oQuery["errlvl"] == "warning") {
				addComment("WARNING:<br/>" + URLDecode(oQuery["error"]));
			} else if (oQuery["errlvl"] == "debug") { 
				addComment("DEBUG:<br/>" + URLDecode(oQuery["error"]));	
			} else {
				//alert(oQuery["error"]);
				addComment( URLDecode(oQuery["error"]) );
			}

			//doError("Call back failed (validateCallBackData)",oQuery["errorno"],oQuery["error"]);
			return false;
		}	

		//if(document.getElementById("error")) document.getElementById("error").innerHTML = URLDecode(oQuery["error"]); else alert("Error: No div for displaying error");
		//if(document.getElementById("errorno")) document.getElementById("errorno").value= oQuery["errorno"]; else alert("Error: No div for displaying error number");
		return oQuery;
	}
		
	function addComment(str) {
	
		elem = document.body;
		
		var newP = document.createElement("P");
		var firstObject = document.getElementById("message_area") ;	
		//alert(firstObject);
		if( ! firstObject ) {
			alert("Error: addComment message_area missing : displaying message \n" + str);
			return false;	
		}
		
		newP.innerHTML = str;
		
		var newDIV = document.createElement("DIV");
		newDIV.id = "message";		
		newDIV.appendChild(newP);
	
		firstObject.appendChild(newDIV);
	
		clearTimeout(timerComment);
		timerId	 = setTimeout(hideComment,3000);
	}
	
	function hideComment() {
		if(document.getElementById("message")) document.getElementById("message").parentNode.removeChild(document.getElementById("message"));
	}
	
	function doError(msg,errorno,error) {
		addComment(error);
		alert(msg + " (Errorno:" + errorno + ")");
	}
	
	/* Checks that given string is valid as email address */
	function checkEmail(email){
	  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	  if (filter.test(email)) return true;
	  else return false;
	}
	
	/* Strips each name value pair in given string and returns object["name"] = value */ 
	function stripQuerystring(str) {
		try {
			var
				aURLQuery=str.split(/[&;]/), 
				re=/(.*)=(.*)/, 
				i=aURLQuery.length, 
				oURLQuery={}, 
				aTemp; 
			while(i-- > 0) { 
				aTemp=re.exec(aURLQuery[i]); 
				oURLQuery[aTemp[1]]=unescape(aTemp[2]); 
			}
			return oURLQuery; 
			
		} catch(er) {
			alert("Error parsing querystring: " + str);	 
		}	
	}
	
	function startTimer(execFunction) {
		clearTimeout(timerId);
		timerId = setTimeout(execFunction,1000); 
	}
	
	/*
	 * I N T E R F A C E   F U N C T I O N S
	 */
	
	function disableSection(id,disable) {
		var elem = document.getElementById(id);
		var hidelink = document.getElementById(id + "_hidelink");
		var showlink = document.getElementById(id + "_showlink");
		var hidelinktag = document.getElementById(id + "_hidelinktag");
		var showlinktag = document.getElementById(id + "_showlinktag");

		if(disable) {
			hideSection(id,true);
			hidelinktag.style.color = "#ccc";
			hidelinktag.style.color = "#ccc";
		} else {
			hidelinktag.style.color = "#000";
			hidelinktag.style.color = "#000";				
		}
		disabled[id] = disable;
		return false;
	}
	
	function hideSection(id,hide) {
		// Validate the required html elements 
		if(!document.getElementById(id)) { 
			doError("Cannot hide section", 101, "Element " + id + " is not found in this page. Please report to support@reedusdesign.com");
			return false;
		}
		if(!document.getElementById(id + "_hidelink")) { 
			doError("Cannot hide section", 101, "Element " + id + "_hidelink is not found in this page. Please report to support@reedusdesign.com");
			return false;
		}
		if(!document.getElementById(id + "_showlink")) { 
			doError("Cannot hide section", 101, "Element " + id + "_showlink is not found in this page. Please report to support@reedusdesign.com");
			return false;
		}
		if(disabled[id]) {
				return false;
		}
		
		var elem = document.getElementById(id);
		
		var hidelink = document.getElementById(id + "_hidelink");
		var showlink = document.getElementById(id + "_showlink");
		if(hide) {
			elem.style.display = "none";
			swapVisibility(showlink,hidelink)
			showlink.style.cssFloat = "right";				
				
		} else {
			//alert(id);
			elem.style.display = "block";				
			hidelink.style.cssFloat = "right";						
			swapVisibility(hidelink,showlink);								
		}
		return false;
	}
	
	function swapVisibility(showElem, hideElem) {
		hideElem.style.visibility = "hidden";
		hideElem.style.position = "absolute";	
		showElem.style.visibility = "visible";
		showElem.style.position = "relative";		
	}
	
	function swapDisplay(showElem, hideElem) {
		hideElem.style.display = "none";
		showElem.style.display = "block";		
	}
	
	function toggleDisplay(id) {
		elem = document.getElementById(id);
		//if(elem.style.display == "none" || elem.style.display == "") {
		if(elem.style.display == "none" ) {
			elem.style.display = "block";		
		} else {
			elem.style.display = "none";	
		}
		return false;
	}
	
	
	/* Selected radio button / select button group functions */
	
	function getSelectedRadio(buttonGroup) {
	   // returns the array number of the selected radio button or -1 if no button is selected
	   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
		  for (var i=0; i<buttonGroup.length; i++) {
			 if (buttonGroup[i].checked) {
				return i
			 }
		  }
	   } else {
		  if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
	   }
	   // if we get to this point, no radio button is selected
	   return -1;
	} // Ends the "getSelectedRadio" function
	
	function getSelectedRadioValue(buttonGroup) {
	   // returns the value of the selected radio button or "" if no button is selected
	   var i = getSelectedRadio(buttonGroup);
	   if (i == -1) {
		  return "";
	   } else {
		  if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
			 return buttonGroup[i].value;
		  } else { // The button group is just the one button, and it is checked
			 return buttonGroup.value;
		  }
	   }
	} // Ends the "getSelectedRadioValue" function
	
	function getSelectedCheckbox(buttonGroup) {
	   // Go through all the check boxes. return an array of all the ones
	   // that are selected (their position numbers). if no boxes were checked,
	   // returned array will be empty (length will be zero)
	   var retArr = new Array();
	   var lastElement = 0;
	   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
		  for (var i=0; i<buttonGroup.length; i++) {
			 if (buttonGroup[i].checked) {
				retArr.length = lastElement;
				retArr[lastElement] = i;
				lastElement++;
			 }
		  }
	   } else { // There is only one check box (it's not an array)
		  if (buttonGroup.checked) { // if the one check box is checked
			 retArr.length = lastElement;
			 retArr[lastElement] = 0; // return zero as the only array value
		  }
	   }
	   return retArr;
	} // Ends the "getSelectedCheckbox" function
	
	function getSelectedCheckboxValue(buttonGroup) {
	   // return an array of values selected in the check box group. if no boxes
	   // were checked, returned array will be empty (length will be zero)
	   var retArr = new Array(); // set up empty array for the return values
	   var selectedItems = getSelectedCheckbox(buttonGroup);
	   if (selectedItems.length != 0) { // if there was something selected
		  retArr.length = selectedItems.length;
		  for (var i=0; i<selectedItems.length; i++) {
			 if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
				retArr[i] = buttonGroup[selectedItems[i]].value;
			 } else { // It's not an array (there's just one check box and it's selected)
				retArr[i] = buttonGroup.value;// return that value
			 }
		  }
	   }
	   return retArr;
	} // Ends the "getSelectedCheckBoxValue" function
