//<!--
// Function Header?  waht does this function do?
var ie = document.all;
var ns = document.layers;
var ns6 = document.getElementById && !document.all; 

var debug = false;;

var dates = new Array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
var monthNames = new Array('January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

function gup( name )
{
	if (debug) alert("gup");
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// BetterInnerHTML v1.1 - by Craig Buckler, http://www.optimalworks.net/
function BetterInnerHTML(_1,_2,_3){function Load(_4){var _5;if(typeof DOMParser!="undefined"){_5=(new DOMParser()).parseFromString(_4,"application/xml");}else{var _6=["MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(var i=0;i<_6.length&&!_5;i++){try{_5=new ActiveXObject(_6[i]);_5.loadXML(_4);}catch(e){}}}return _5;}function Copy(_8,_9,_a){if(typeof _a=="undefined"){_a=1;}if(_a>1){if(_9.nodeType==1){var _b=document.createElement(_9.nodeName);for(var a=0,attr=_9.attributes.length;a<attr;a++){var _d=_9.attributes[a].name,aValue=_9.attributes[a].value,evt=(_d.substr(0,2)=="on");if(!evt){switch(_d){case "class":_b.className=aValue;break;case "for":_b.htmlFor=aValue;break;default:_b.setAttribute(_d,aValue);}}}_8=_8.appendChild(_b);if(evt){_8[_d]=function(){eval(aValue);};}}else{if(_9.nodeType==3){var _e=(_9.nodeValue?_9.nodeValue:"");var _f=_e.replace(/^\s*|\s*$/g,"");if(_f.indexOf("<!--")!=0&&_f.indexOf("-->")!=(_f.length-3)){_8.appendChild(document.createTextNode(_e));}}}}for(var i=0,j=_9.childNodes.length;i<j;i++){Copy(_8,_9.childNodes[i],_a+1);}}_2="<root>"+_2+"</root>";var _11=Load(_2);if(_1&&_11){if(_3!=false){while(_1.lastChild){_1.removeChild(_1.lastChild);}}Copy(_1,_11.documentElement);}}

function replaceHtml(el, html) {
	if (debug) alert("function replaceHtml(el, html)");
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

function IsNumeric(sText)

{
	if (debug) alert("function IsNumeric(sText)");
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

function validate() {
	if (debug) alert("function validate()");
	var pmin = findObject('price_min');
	var pmax = findObject('price_max');
	
	var err = '';
	if (!IsNumeric(pmin.value))	 err = err + 'Min Price is invalid \n';
	if (!IsNumeric(pmax.value))	 err = err + 'Max Price is invalid \n';

	if (err != '')alert(err);
	if (err != '') return false;
}

// Gets all checked boxes in province list
function resetChecked() {
	if (debug) alert("function resetChecked()");
	var t = findObject('properties');
	var len = t.elements.length;
	var s = '';
	for (i=0;i<len;i++) {
		if (t.elements[i].type == "select-one") t.elements[i].value= 0;
		if (t.elements[i].type == "text") t.elements[i].value= '';
	}
	
	var obj = findObject('province_ids[]');
	var cnt = 0;
	var len = obj.length;
	for (var i = 0; i < len; i++) {	
			obj[i].checked = false;
	}
	
	var obj = findObject('city_ids[]');
	var cnt = 0;
	var len = obj.length;
	for (var i = 0; i < len; i++) {	
			obj[i].checked = false;
	}
	
	if (obj = findObject('suburb_ids[]')) {
		var cnt = 0;
		var len = obj.length;
		for (var i = 0; i < len; i++) {	
				obj[i].checked = false;
		}
	}
	
}


// Gets all checked boxes in province list
function getCheckedProvinces(obj) {
	if (debug) alert("function getCheckedProvinces(obj)");
//	alert("Orig Obj: "+obj);
//	var obj = findObject(obj.name);
	var obj = findObject(obj);
//	alert("NewObj: "+obj);
	var cnt = 0;
	
	var len = obj.length;
	var t = "{";
	for (var i = 0; i < len; i++) {	
		if (obj[i].checked == 1) {
			t += "i:"+i+";i:"+obj[i].value+";";
			cnt++;
		}
	}
	t = "a:"+cnt+":"+t;
	t += "}";
//	alert("Provinces: "+t);
	return t;
}

// Gets all checked boxes in city list
function getCheckedCities(obj) {
	if (debug) alert("function getCheckedCities(obj)");
//	alert("Orig Obj: "+obj);
//	var obj = findObject(obj.name);
//	var obj = findObject(obj);
	var obj = findObject('city_ids[]');
//	alert("NewObj: "+obj);
	var cnt = 0;

	var len = obj.length;
	var t = "{";
	for (var i = 0; i < len; i++) {	
		if (obj[i].checked == 1) {
			t += "i:"+i+";i:"+obj[i].value+";";
			cnt++;
		}
	}
	t = "a:"+cnt+":"+t;
	t += "}";
//	alert("Cities: "+t);
	return t;
}


// Gets all checked boxes in city list
function getCheckedSuburbs(obj) {
	if (debug) alert("function getCheckedSuburbs(obj)");
//	alert("Orig Obj: "+obj);
//	var obj = findObject(obj.name);
//	var obj = findObject(obj);
	var obj = findObject('suburb_ids[]');
//	alert("NewObj: "+obj);
	var cnt = 0;

	var len = obj.length;
	var t = "{";
	for (var i = 0; i < len; i++) {	
		if (obj[i].checked == 1) {
			t += "i:"+i+";i:"+obj[i].value+";";
			cnt++;
		}
	}
	t = "a:"+cnt+":"+t;
	t += "}";
//	alert("Cities: "+t);
	return t;
}

// loadCities - load the cities into the select box contained with the div identified by obj.
// key is the province key for selecting which cities to show
// store the div name in cityObj for use in the later processCityChange function
var req1;
var cityObj;
var suburbObj;
function loadCities(key,obj,multi,def) {
	if (debug) alert("function loadCities(key,obj,multi,def)");
//alert("loadCities(key,obj,multi) \n loadCities("+key+", "+obj+", "+multi+","+def+")");
//Solves paths problem
var path = document.location.pathname;

var dir = path.substring(path.indexOf('/', 1)+1, path.lastIndexOf('/'));	
if (dir == '/') dir = '../'; else dir = '../'; 
if (obj == "cities") var cid = "city_id"
else var cid = "s_city_id";
//alert(cid);

	if (multi==1) {
		var url=dir+"php/ajax/cities.php?provinces="+key+"&fieldid=city_id&fieldname=city_ids&show_all=1&blanktext=All Cities&ajax=1&multi=1&default="+def;
//		alert(key);
	}
	else var url=dir+"php/ajax/cities.php?province_id="+key+"&fieldid="+cid+"&fieldname="+cid+"&show_all=1&blanktext=All Cities&ajax=1&multi=0&default="+def;

	cityObj=obj;
//	 alert(cityObj);
//   if (getObject("cities")) getObject("cities").innerHTML = '&nbsp;Please wait...';
//	 if (getObject("cities1")) getObject("cities1").innerHTML = '&nbsp;Please wait...';
	 if (getObject(obj)) replaceHtml(getObject(obj),'&nbsp;Please wait...');
   try { req1 = new ActiveXObject("Msxml2.XMLHTTP"); }
   catch(e) { 
      try { req1 = new ActiveXObject("Microsoft.XMLHTTP"); } 
      catch(oc) { req1 = null; } 
   } 
   if (!req1 && typeof XMLHttpRequest != "undefined") { req1 = new XMLHttpRequest(); } 
   if (req1 != null) {
      req1.onreadystatechange = processCityChange; 
      req1.open("GET", url, true); 
      req1.send(null); 
   }


	 loadSuburbs(0,key,multi);
//	 loadSuburbs(getCheckedCities("city_ids[]"),key,multi);
//	 loadSuburbs(key,0,multi);
} 

function processCityChange(obj) {
	if (debug) alert("function processCityChange(obj)");
//	alert("processCityChange()");
	if (req1.readyState == 4 && req1.status == 200) { 
//		if (getObject(cityObj)) getObject(cityObj).innerHTML = req1.responseText;		
		if (getObject(cityObj)) {
			replaceHtml(findObject(cityObj), req1.responseText);
		}
  }
}

var req2; 
function loadSuburbs(key,prov,multi,def) {
	if (debug) alert("function loadSuburbs(key,prov,multi,def) ");
//alert("loadSuburbs(key,prov,multi) \n loadSuburbs("+key+", "+prov+", "+multi+", "+def+")");
var path = document.location.pathname;
var dir = path.substring(path.indexOf('/', 1)+1, path.lastIndexOf('/'));	
if (dir == '/') dir = '../'; else dir = '../'; 
	if (multi==1) {
		 var url=dir+"php/ajax/suburbs.php?provinces="+prov+"&cities="+key+"&fieldid=suburb_id&fieldname=suburb_ids&show_all=0&blanktext=All Suburbs&multi=1&default="+def;
	}
	else var url=dir+"php/ajax/suburbs.php?province_id="+prov+"&city_id="+key+"&fieldid=suburb_id&fieldname=suburb_id&show_all=1&blanktext=All Suburbs&multi=0&default="+def;
	
		 if (getObject("suburbs")) replaceHtml(getObject("suburbs"),'&nbsp;Please wait...');
		 try { req2 = new ActiveXObject("Msxml2.XMLHTTP"); }
		 catch(e) { 
				try { req2 = new ActiveXObject("Microsoft.XMLHTTP"); } 
				catch(oc) { req2 = null; } 
		 } 

		 if (!req2 && typeof XMLHttpRequest != "undefined") { req2 = new XMLHttpRequest(); } 
		 if (req2 != null) {
				req2.onreadystatechange = processSuburbChange; 
				req2.open("GET", url, true); 
				req2.send(null); 
		 }
		 
}
function processSuburbChange() { 
if (debug) alert("function processSuburbChange()");
   if (req2.readyState == 4 && req2.status == 200) { 
      if (getObject('suburbs')) replaceHtml(getObject('suburbs'), req2.responseText);
			//getObject('suburbs').innerHTML = req2.responseText;
   }
}

function getObject(name) { 
if (debug) alert("function getObject(name)");
   var ns4 = (document.layers) ? true : false; 
   var w3c = (document.getElementById) ? true : false; 
   var ie4 = (document.all) ? true : false; 

   if (ns4) return eval('document.' + name); 
   if (w3c) return document.getElementById(name); 
   if (ie4) return eval('document.all.' + name); 
   return false; 
}

function findObject(theObj, theDoc) {
	if (debug) alert("function findObject(theObj, theDoc)");
  var p, i, foundObj;

  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length) {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }

  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  return foundObj;
}
function GeneratePassword(length, nopunc) {
	if (debug) alert("function GeneratePassword(length, nopunc)");

    if (parseInt(navigator.appVersion) <= 3) {
        alert("Sorry this only works in 4.0+ browsers");
        return true;
    }

    if (!length) var length=8;
    var sPassword = "";

    var noPunction = (nopunc);
    var randomLength = 0;

    if (randomLength) {
        length = Math.random();

        length = parseInt(length * 100);
        length = (length % 7) + 6
    }


    for (i=0; i < length; i++) {

        numI = getRandomNum();
        if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }

        sPassword = sPassword + String.fromCharCode(numI);
    }
//		alert(sPassword);
    return sPassword;
}

function getRandomNum() {
	if (debug) alert("function getRandomNum()");

    // between 0 - 1
    var rndNum = Math.random()

    // rndNum from 0 - 1000
    rndNum = parseInt(rndNum * 1000);

    // rndNum from 33 - 127
    rndNum = (rndNum % 94) + 33;

    return rndNum;
}

function checkPunc(num) {
	if (debug) alert("function checkPunc(num)");

    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }

    return false;
}

function removeSpaces(string) {
	if (debug) alert("function removeSpaces(string)");
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

// Change company/private fields based on selection
function checkIfCompany() {
	if (debug) alert("function checkIfCompany()");
var t = findObject('is_company'); 
var lbl1 = findObject('regid');         // ID Number / Registration ID
var inp1 = findObject('company_name');  // Company name
var co_name = findObject('company1');
var first_name = findObject('private1');
var last_name = findObject('private2');
var is_id = findObject('private3');
var t1 = findObject('is_company_hidden'); 
//alert("Here we Are"+t1);
var radioLength = t.length;
if(radioLength == undefined)
                if(radioObj.checked)
                        return radioObj.value;
                else
                        return "";

for (var i = 0; i < radioLength; i++) {
//								alert(t[i].name+" "+i+" "+t[i].checked);
                // Change text and disable company fields
                if(t[i].checked == 0) {
                        lbl1.innerHTML = "ID/Passport Number";
                        inp1.readOnly = true;
                        inp1.style.backgroundColor = '#c0c0c0';
						co_name.style.display = "none";
						if (ie) first_name.style.display = "block";
						else first_name.style.display = "table-row";
						if (ie) last_name.style.display = "block";
						else last_name.style.display = "table-row";
						if (ie) is_id.style.display = "block";
						else is_id.style.display = "table-row";
						t1.value = 0;
                }
                // Change text and enable company fields
                else {
                        lbl1.innerHTML = "Registration ID";
                        inp1.style.backgroundColor = 'white';
                        inp1.readOnly = false;
						if (ie) co_name.style.display = "block";
						else co_name.style.display = "table-row";
						is_id.style.display = "none";
						first_name.style.display = "none";
						last_name.style.display = "none";
						t1.value = 1;
                }
        }
}

function getIsCompany() {
	if (debug) alert("function getIsCompany()");
	var t = findObject('is_company'); 
	var t1 = findObject('is_company_hidden'); 
	t1.value = t.checkedValue; 
	alert('T: '+t+' \n T1: '+t1);
}

function getQueryVariable(variable) {
	if (debug) alert("function getQueryVariable(variable)");
  var query = window.location.search.substring(1);
  var vars = query.split("&");

  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
			var t = pair[1];
//			var t = t.replace('\%',":");
			var t = unescape(t);
			return(t);
    }
  } 
//alert('Query Variable ' + variable + ' not found');
}

function initIt() {
	if (debug) alert("function initIt()");
var province = getQueryVariable("province_id");
var city = getQueryVariable("city_id");
var suburb = getQueryVariable("suburb_id");
//if (province > 0) loadCities(province);
if (province > 0) loadCities(province,"cities");
if (city > 0) {
		var t = findObject('city_id');
		alert(t);
		t.selectedIndex = city;
		loadSuburbs(city); 
	}
}

function hideAnswers(button,state) {
	//alert("button pressed");
	if (debug) alert("function hideAnswers(button,state)");
		var tmpName = button.name;	
		//alert("button name: " + tmpName);
		var qID = tmpName.substr(tmpName.indexOf('Q')+1);
		var cnt = 1;
		var done = 0;
		//alert("tmpname: " + tmpName + "-----cnt: " + cnt);
		if (!state[qID]) 
			state[qID] = 0;
		//alert("question id: " + qID);
		while (!done) {
			var id = "q"+qID+"a"+cnt;
			var tmp = findObject(id);
			if (tmp) {
				if (state[qID] == 1) {
					tmp.style.visibility = 'hidden';
					tmp.style.display = 'none';
					eraseCookie(id);
//					alert("Erasin	g Cookie: "+id);					
				}
				else {
					tmp.style.visibility = 'visible';
					if (ie) tmp.style.display = 'block';
					else tmp.style.display = 'table-row';
					createCookie(id,1,1);
					//alert("Creating Cookie: "+id);
				}
			}
			else 
				done = true;
			cnt++;
			//alert ("Another one: "+cnt+" "+id);
		}

		if (button.value == 'Show Answers') button.value = 'Hide Answers';
		else button.value = 'Show Answers';

		if (state[qID] == 0) state[qID] = 1;
		else if (state[qID] == 1) state[qID] = 0;
		return state;
		//alert("state: " + state);
}

function createCookie(name,value,days) {
	if (debug) alert("function createCookie(name,value,days)");
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	if (debug) alert("function readCookie(name)");
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	if (debug) alert("function eraseCookie(name)");
	createCookie(name,"",-1);
}

// Change company/private fields based on selection
function checkQuestionType() {
	if (debug) alert("function checkQuestionType()");
var t = findObject('question_type'); 
var lbl1 = findObject('date_question');         // ID Number / Registration ID

var radioLength = t.length;
if(radioLength == undefined)
                if(radioObj.checked) return radioObj.value;
                else return "";

								for (var i = 0; i < radioLength; i++) {
                // Change text and disable company fields
                if(t[i].checked == 1) {
                        lbl1.style.display = 'table-row';
                }
                // Change text and enable company fields
                else {
                        lbl1.style.display = 'none';
                }
        }
}

function propertySearchMenu(menuItem) {
	if (debug) alert("function propertySearchMenu(menuItem)");
	var menuGeneral = findObject('searchGeneralMenuItem');
	var menuFeatures = findObject('searchFeaturesMenuItem');
	
	var menuGeneralTD = findObject('searchGeneralTD');
	var menuFeaturesTD = findObject('searchFeaturesTD');

	var searchGeneral = findObject('searchGeneral');
	var searchFeatures = findObject('searchFeatures');
	
	switch(menuItem) {
		case 'general': //alert('General Search Criteria');
			searchGeneral.style.display = 'block';
			searchFeatures.style.display = 'none';
			menuGeneral.style.color = '#009933';
			menuGeneral.style.fontWeight = 'bold';
			menuFeatures.style.fontWeight = 'normal';
			menuFeatures.style.color = '#000000';
			
			menuFeaturesTD.style.borderBottom = "1px solid #75B890";
			menuGeneralTD.style.borderRight = "1px solid #75B890";
			menuGeneralTD.style.borderLeft = "1px solid #75B890";
			menuFeaturesTD.style.borderRight = "none";
			menuFeaturesTD.style.borderLeft = "none";
			menuGeneralTD.style.borderBottom = "none";
			
			break;
		case 'features': //alert('Features Search Criteria');
			searchGeneral.style.display = 'none';
			searchFeatures.style.display = 'block';
			menuFeatures.style.color = '#009933';
			menuFeatures.style.fontWeight = 'bold';
			menuGeneral	.style.fontWeight = 'normal';
			menuGeneral.style.color = '#000000';
			
			menuGeneralTD.style.borderBottom = "1px solid #75B890";
			menuFeaturesTD.style.borderRight = "1px solid #75B890";
			menuFeaturesTD.style.borderLeft = "1px solid #75B890";
			menuGeneralTD.style.borderRight = "none";
			menuGeneralTD.style.borderLeft = "none";
			menuFeaturesTD.style.borderBottom = "none";
			break;
		default: alert('no selection');
			searchGeneral.style.display = 'block';
			searchFeatures.style.display = 'none';
			break;
	}
}

function commissionMenu(menuItem) {
	if (debug) alert("function commissionMenu(menuItem) ");
	var menuGeneral = findObject('searchGeneralMenuItem');
	var menuFeatures = findObject('searchFeaturesMenuItem');
	
	var menuGeneralTD = findObject('searchGeneralTD');
	var menuFeaturesTD = findObject('searchFeaturesTD');

	var searchGeneral = findObject('commissions_summary');
	var searchFeatures = findObject('commissions');

switch(menuItem) {
		case 'summary': //alert('General Search Criteria');
			searchGeneral.style.display = 'block';
			searchFeatures.style.display = 'none';
		if (menuGeneral) {
			menuGeneral.style.color = '#009933';
			menuGeneral.style.fontWeight = 'bold';
			menuFeatures.style.fontWeight = 'normal';
			menuFeatures.style.color = '#000000';
			
			menuFeaturesTD.style.borderBottom = "1px solid #75B890";
			menuGeneralTD.style.borderRight = "1px solid #75B890";
			menuGeneralTD.style.borderLeft = "1px solid #75B890";
			menuFeaturesTD.style.borderRight = "none";
			menuFeaturesTD.style.borderLeft = "none";
			menuGeneralTD.style.borderBottom = "none";
		}
			break;
		case 'commissions': //alert('Features Search Criteria');
			searchGeneral.style.display = 'none';
			searchFeatures.style.display = 'block';
		if (menuFeatures) {
			menuFeatures.style.color = '#009933';
			menuFeatures.style.fontWeight = 'bold';
			menuGeneral	.style.fontWeight = 'normal';
			menuGeneral.style.color = '#000000';
			
			menuGeneralTD.style.borderBottom = "1px solid #75B890";
			menuFeaturesTD.style.borderRight = "1px solid #75B890";
			menuFeaturesTD.style.borderLeft = "1px solid #75B890";
			menuGeneralTD.style.borderRight = "none";
			menuGeneralTD.style.borderLeft = "none";
			menuFeaturesTD.style.borderBottom = "none";
		}
			break;
		default: alert('no selection');
			searchGeneral.style.display = 'block';
			searchFeatures.style.display = 'none';
			break;
	}
}

function is_company_click() {
	if (debug) alert("function is_company_click()");
	var t = findObject('row_company_name');
	var is_id = findObject('is_id_row');
	var t1 = findObject('is_company');
	var lbl1 = findObject('regid');
	
	if (t1.checked == 0)
	{
		lbl1.innerHTML = "ID/Passport Number";
		t.style.display = 'none';
		if (ie) is_id.style.display = 'block';
		else is_id.style.display = 'table-row';
	}
	else
	{
		lbl1.innerHTML = "Registration Number";
		if (ie) t.style.display = 'block';
		else t.style.display = 'table-row';
		is_id.style.display = 'none';
	}
/*
if (t.style.display != 'none') t.style.display = 'none';
	else if (ie) t.style.display = 'block';
	else t.style.display = 'table-row';
*/	
}

function q1_choice_filter() {
	if (debug) alert("function q1_choice_filter()");
	q1 = findObject('q1_choice');
	q1 = q1.value;
	var t = findObject('q2_row');
	if (q1 != 2)
		t.style.display = 'none';
	else if (ie) t.style.display = 'block';
		else t.style.display = 'table-row';
/*
if (t.style.display != 'none') t.style.display = 'none';
	else if (ie) t.style.display = 'block';
	else t.style.display = 'table-row';
*/	
}

function q3_choice_filter() {
	if (debug) alert("function q3_choice_filter()");
	q1 = findObject('q3_choice');
	q1 = q1.value;
	var t = findObject('q3_radio');
	if (q1 != 1)
		t.style.display = 'none';
	else t.style.display = "block";
}

function show_reminder_date()
{
	if (debug) alert("function q3_choice_filter()");
	q1 = findObject('select_type');
	q1 = q1.value;
	var t = findObject('show_reminder_date_row');
	completed = findObject('add_enquiry_activityadd_activitycompleted');
	if (q1 == 5)
	{
		completed.value = 0;
		if (ie) 
			t.style.display = 'block';
		else 
			t.style.display = 'table-row';
	}
	else
	{
		t.style.display = 'none';
		completed.value = -1;
	}
}

function q22_choice_filter() {
	if (debug) alert("function q22_choice_filter()");
	q1 = findObject('q22_choice');
	q1 = q1.value;
	var t = findObject('notice');
	if (q1 == 1)
	t.style.display = 'none';
	else
		t.style.display = "block";
	
}

function payment_method_click(){
	//alert("123123");
	if (debug) alert("function payment_method_click()");
	var debit = findObject('debit_row');
	var credit = findObject('credit_row');
	var t1 = findObject('payment_method');
	alert(t1.checked);
	/*if (t1.checked == 0)*/
	/*t.style.display = 'none';
	if (ie)
	{
		t.style.display = 'block';
	}
	else 
	{	
		t.style.display = 'table-row';
	}*/
	debit.style.display = 'none';
}

function allProvinces() {
	if (debug) alert("function allProvinces()");
	var t = findObject('province_ids[]');
	var t1 = findObject('allProv');
//	t.checked = true;
//	alert (t.length);
	for (i=0;i<t.length;i++) {
		if (t1.checked) t[i].checked = 1;
		else t[i].checked = 0;
	}
}

function allCities() {
	if (debug) alert("function allCities()");
	var t = findObject('city_ids[]');
	var t1 = findObject('allCity');
//	t.checked = true;
//	alert (t.length);
	for (i=0;i<t.length;i++) {
		if (t1.checked) t[i].checked = 1;
		else t[i].checked = 0;
	}
}

function allSubs() {
	if (debug) alert("function allSubs()");
	var t = findObject('suburb_ids[]');
	var t1 = findObject('allSuburbs');
//	t.checked = true;
//	alert (t.length);
	for (i=0;i<t.length;i++) {
		if (t1.checked) t[i].checked = 1;
		else t[i].checked = 0;
	}
}

// Returns months between 2 date strings of the form mm/yyyy
function monthsBetween(date1, date2) {
	if (debug) alert("function monthsBetween(date1, date2)");
	var date1array = date1.split("/");
	var date2array = date2.split("/");

	// Assume Date 2 is later than Date 1
	
	var months_apart = (date2array[1] - date1array[1]) * 12;
	
	// Month is later in date 1 than in date 2
	// Find the difference of months
	if( date1array[0] > date2array[0] )
	{
		months_apart -= date1array[0] - date2array[0];
	}
	else
	{
	months_apart += date2array[0] - date1array[0];
	}
	
	// $months_apart should now contain months apart
	return months_apart;
	
}

// Calculate total amount between months
// d1 = start date object
// d2 = end date object
// amount = amount object
function rentalPeriod(start, end) {
	if (debug) alert("function rentalPeriod(start, end)");
	var months = monthsBetween(start, end);

	var resp = "";
	resp += "function rentalPeriod() \n";
	resp += "start: " + start + "\n";
	resp += "end: " + end + "\n"; 
	resp += "Months: " + months + "\n";
	
//	alert("d1Arr[0]: " + d1Arr[0] + "\n" + "d1Arr[1]: " + d1Arr[1] + "\n"  + "d2Arr[0]: " + d2Arr[0] + "\n"  + "d2Arr[1]: " + d2Arr[1] + "\n");
//	alert	(resp);
	return months;
}

function rentalAgreement() {
	if (debug) alert("function rentalAgreement()");
	var p_start1 = findObject('period_start1');
	var p_end1 = findObject('period_end1');
	var p_amount1 = findObject('period_amount1');
	var p_months1 = findObject('period_months1');
	
	var p_start2 = findObject('period_start2');
	var p_end2 = findObject('period_end2');
	var p_amount2 = findObject('period_amount2');
	var p_months2 = findObject('period_months2');	
	
	var p_start3 = findObject('period_start3');
	var p_end3 = findObject('period_end3');
	var p_amount3 = findObject('period_amount3');	
	var p_months3 = findObject('period_months3');	
	
	var p_start4 = findObject('period_start4');
	var p_end4 = findObject('period_end4');
	var p_amount4 = findObject('period_amount4');
	var p_months4 = findObject('period_months4');	
	
	var p1 = rentalPeriod(p_start1.value, p_end1.value);
	var p2 = rentalPeriod(p_start2.value, p_end2.value);
	var p3 = rentalPeriod(p_start3.value, p_end3.value);
	var p4 = rentalPeriod(p_start4.value, p_end4.value);	
	
	var p_amount_total1 = p1 * p_amount1.value;
	var p_amount_total2 = p2 * p_amount2.value;
	var p_amount_total3 = p3 * p_amount3.value;
	var p_amount_total4 = p4 * p_amount4.value;
	
	var period1 = findObject('period1');
	var period2 = findObject('period2');
	var period3 = findObject('period3');
	var period4 = findObject('period4');

	if (p1 < 0) period1.innerHTML = "Invalid dates";
	else if ((p_start1.value == '') || (p_end1.value == '')) period1.innerHTML = "&nbsp;";
	else period1.innerHTML = "R " + p_amount_total1 + " over " + p1 + " months";
	if (p2 < 0) period2.innerHTML = "Invalid dates";
	else if ((p_start2.value == '') || (p_end2.value == '')) period2.innerHTML = "&nbsp;"; 
	else period2.innerHTML = "R " + p_amount_total2 + " over " + p2 + " months";
	if (p3 < 0) period3.innerHTML = "Invalid dates";
	else if ((p_start3.value == '') || (p_end3.value == '')) period3.innerHTML = "&nbsp;";	
	else period3.innerHTML = "R " + p_amount_total3 + " over " + p3 + " months";
	if (p4 < 0) period4.innerHTML = "Invalid dates";
	else if ((p_start4.value == '') || (p_end4.value == '')) period4.innerHTML = "&nbsp;";	
	else period4.innerHTML = "R " + p_amount_total4 + " over " + p4 + " months";	
}

	function convert_date(str) {
		if (debug) alert("function convert_date(str)");
		var t = new String(str);
		var t1 = t.split("/");
		var y = t1[1];
		var m = 0;
		if (t1[0] > 0) m = t1[0]-1;
		var newDate = new Date(y,m,1);
		var ts = newDate.getTime();
//		alert(ts);		
		return ts;
	}
	
	function getNextMonth(month, drop) {
		if (debug) alert("function getNextMonth(month, drop)");
			var t = new Date(convert_date(month));
			var oldYear = t.getFullYear();
			t.setMonth(t.getMonth() + 1);
			var next_month = new String(dates[t.getMonth()] + "/" + t.getFullYear());
			var period_dropdowns = findObject(drop);						
if (period_dropdowns) {
			if (t.getMonth() == 11) {
				for (i=0;i<period_dropdowns.options.length;i++) {
//					if (period_dropdowns.options[i].value == t.getFullYear()+1) period_dropdowns.options[i].selected = true;	
				}
			}
			else {
				for (i=0;i<period_dropdowns.options.length;i++) {
//					if (period_dropdowns.options[i].value == t.getFullYear()) period_dropdowns.options[i].selected = true;	
				}
			}


			if ( (oldYear < t.getFullYear()) || (t.getFullYear() > period_dropdowns.options[period_dropdowns.selectedIndex].value) ) {
				for (i=0;i<period_dropdowns.options.length;i++) {
					if (period_dropdowns.options[i].value == t.getFullYear()) period_dropdowns.options[i].selected = true;	
				}
			}
			
}
			return next_month;
	}
	
	function dateString(d) {
		if (debug) alert("function dateString(d) ");
		var t = d.split("/");
		var month = parseInt(t[0]-1)
		var newStr = new String(monthNames[month] + ", " + t[1]);
		return newStr;
	}

	function check_rental_dates () {
		if (debug) alert("function check_rental_dates ()");
		var period_start1 = findObject("period_start1");
		var period_start2 = findObject("period_start2");
		var period_start3 = findObject("period_start3");
		var period_start4 = findObject("period_start4");
		var period_end1 = findObject("period_end1");
		var period_end2 = findObject("period_end2");
		var period_end3 = findObject("period_end3");
		var period_end4 = findObject("period_end4");
		var period_date_start2 = findObject("period_date_start2");
		var period_date_start3 = findObject("period_date_start3");
		var period_date_start4 = findObject("period_date_start4");		
		
//		alert(		period_dropdowns_yearstart1.options[2].value);
		var errMsg = "";
/*
		if ( (period_start1.value != '') && (period_start1.value > period_end1.value) ) errMsg += "1st Start date must be before 1st End Date \n";
		if ( (period_start2.value != '') && (period_start2.value > period_end1.value) ) errMsg += "2nd Start date must be after 1st End Date \n";
		if ( (period_start3.value != '') && (period_start3.value > period_end2.value) ) errMsg += "3rd Start date must be after 2nd End Date \n";		
		if ( (period_start4.value != '') && (period_start4.value > period_end3.value) ) errMsg += "4th Start date must be after 3rd End Date \n";
*/		

		// Make each start date the next month after previous end date 
		if ((period_end1) && (period_start2)) if (period_end1.value != '') {
			period_start2.value = getNextMonth(period_end1.value, 'period_dropdowns_yearend2');
			period_date_start2.innerHTML = dateString(period_start2.value);
		}
		if ((period_end2) && (period_start3)) if (period_end2.value != '') {
			period_start3.value = getNextMonth(period_end2.value, 'period_dropdowns_yearend3');		
			period_date_start3.innerHTML = dateString(period_start3.value);			
		}
		if ((period_end3) && (period_start4)) if (period_end3.value != '') {
			period_start4.value = getNextMonth(period_end3.value, 'period_dropdowns_yearend4');
			period_date_start4.innerHTML = dateString(period_start4.value);			
		}

		if (period_start2) if ( (period_start2.value != '') && (convert_date(period_start2.value) < convert_date(period_end1.value)) ) errMsg += "2nd Start date must be after 1st End Date \n";
		if (period_start3) if ( (period_start3.value != '') && (convert_date(period_start3.value) < convert_date(period_end2.value)) ) errMsg += "3rd Start date must be after 2nd End Date \n";		
		if (period_start4) if ( (period_start4.value != '') && (convert_date(period_start4.value) < convert_date(period_end3.value)) ) errMsg += "4th Start date must be after 3rd End Date \n";

		if (period_start1) if ( (period_start1.value != '') && (convert_date(period_start1.value) > convert_date(period_end1.value)) ) errMsg += "1st Start date must be before 1st End Date \n";
		if (period_start2) if ( (period_start2.value != '') && (convert_date(period_start2.value) > convert_date(period_end2.value)) ) errMsg += "2nd Start date must be before 2nd End Date \n";
		if (period_start3) if ( (period_start3.value != '') && (convert_date(period_start3.value) > convert_date(period_end3.value)) ) errMsg += "3rd Start date must be before 3rd End Date \n";
		if (period_start4) if ( (period_start4.value != '') && (convert_date(period_start4.value) > convert_date(period_end4.value)) ) errMsg += "4th Start date must be before 4th End Date \n";
		
		if (errMsg != "") {
			alert("Error: " + errMsg);
			return false;
		}

/*
	if ( (!period_start1) || (!period_start2) || (!period_start3) || (!period_start4) || (!period_end1) || (!period_end2) || (!period_end3) || (!period_end4) ) {
			if ( (period_start1.value == "") || (period_start2.value == "") || (period_start3.value == "") || (period_start4.value == "") 
				|| (period_end1.value == "") || (period_end2.value == "") || (period_end3.value == "") || (period_end4.value == "") ) {
				return false;
			}		
		}
*/		
	}

	function combine_dropdowns(m,y,h) {
		if (debug) alert("function combine_dropdowns(m,y,h)");
		var hidden = findObject(h); 
		var t = findObject(m);
		var t1 = findObject(y);
		
		var month = t.value;
		var year = t1.value;
		var combined = month + '/' + year;
		hidden.value = combined;;
		check_rental_dates();
//		alert("Month: " + month + " Year: " + year + "\n" + combined + "\n" + hidden);
	}
	
function ajaxRequest()
{
    if (debug) alert("function ajaxRequest()");
    var xmlHttp;
    
    try
    {
        xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
        var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                        'MSXML2.XMLHTTP.5.0',
                                        'MSXML2.XMLHTTP.4.0',
                                        'MSXML2.XMLHTTP.3.0',
                                        'MSXML2.XMLHTTP',
                                        'Microsoft.XMLHTTP');
        
        for (i = 0; i < XmlHttpVersions.length && !xmlHttp; i++)
        {
            try
            {
                xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
            }
            catch(e) {}
        }
    }
    
    if (!xmlHttp)
    {
        alert('Your browser may not support XML Requests');
    }
    else
    {
        return xmlHttp;
    }
}	

function termsAccepted() {
	if (debug) alert("function termsAccepted()");
	var t = findObject("termsaccept");
	if (t.checked == true) return true;
	else {
		alert("You must accept the terms and conditions");
		return false;
	}
}

function termsLLCompanyAccepted() {
	if (debug) alert("function termsAccepted()");
	var t = findObject("company_termsaccept");
	if (t.checked == true) return true;
	else {
		alert("You must accept the terms and conditions");
		return false;
	}
}

function getPreloadedText(selector) {
	if (debug) alert("function getPreloadedText(selector) {");
//	var t = getQueryVariable("preload_id");
	var t = selector.options[selector.selectedIndex].value;
	

		// The id of the div you want your images to be displayed in
    var imageDisplayDiv = 'sms_text';
		var textArea = findObject(imageDisplayDiv);

// Starts a new request
    var ajax = ajaxRequest();


    // Gets the out put of the image file by sending nothing and just getting its finished product
    ajax.open('GET', "../php/ajax/get_preloaded_text.php?preload_id="+t, true);
    ajax.send(null);    
    // displayes a loading text so user knows the script is working
    textArea.value = "<span style='font-weight:bold;'>Loading...</span>";    
    
    // Cycles through the ajax state change
    ajax.onreadystatechange = function()
    {
        // if the ajax request is ready
        if (ajax.readyState == 4)
        {
            // Checks if it really is ready by checking status number , 200 = done
            if (ajax.status == 200)
            {
            // writes the image files output to the div
//            document.getElementById(imageDisplayDiv).innerHTML = ajax.responseText;
							textArea.value = ajax.responseText;
            }
        }
    }

}

function getCellphone(selector, type) {
	if (debug) alert("function getCellphone(selector, type)");
//	var t = getQueryVariable("preload_id");
	var t = selector.options[selector.selectedIndex].value;
	

		// The id of the div you want your images to be displayed in
    var imageDisplayDiv = 'sms_recipient';
		var cellphone = findObject(imageDisplayDiv);
    // Starts a new request
    var ajax = ajaxRequest();


    // Gets the out put of the image file by sending nothing and just getting its finished product
    ajax.open('GET', "../php/ajax/get_cellphone.php?type="+type+"&type_id="+t, true);
    ajax.send(null);    
    // displayes a loading text so user knows the script is working
    cellphone.value = '<span style=\"font-weight:bold;\">Loading...</span>';    
    
    // Cycles through the ajax state change
    ajax.onreadystatechange = function()
    {
        // if the ajax request is ready
        if (ajax.readyState == 4)
        {
            // Checks if it really is ready by checking status number , 200 = done
            if (ajax.status == 200)
            {
            // writes the image files output to the div
//            document.getElementById(imageDisplayDiv).innerHTML = ajax.responseText;
							cellphone.value = ajax.responseText;
            }
        }
    }
		

}

function resetLandlords() {
	if (debug) alert("resetLandlords()");
	var t = findObject("s_landlord_id");
	t.selectedIndex = 0;
}

function resetAgency() {
	if (debug) alert("function resetAgency()");
	var t = findObject("s_agency_id");
	t.selectedIndex = 0;
	var t = findObject("s_agent_id");
	t.selectedIndex = 0;	
}
-->