//By: Chris Campbell
//Created: May 20, 2005
//Last Modified: June 27th, 2005
//www.particletree.com

window.onload = attachFormHandlers;

// path = /production/office/cybarco/www
path = location.pathname;
if (location.pathname.lastIndexOf("manager") != -1) {
	var path = location.pathname.substr(0,(location.pathname.lastIndexOf("manager"))); 
}
else if ( location.pathname.lastIndexOf("/") != -1) {
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("/")));
}
if (path.charAt(path.length - 1) != '/') {
	path = path + '/';	
}

/* initialisation for the validation */
var sUrl = 'http://' + location.host + path + 'assets/modules/realEstate/formvalidation.php?validationtype=ajax&val=';///xtenzio/url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
var gErrors = 0; //number of errors is set to none to begin with
var gShow; //variable holding the id where feedback will be sent to.

/* for the ajaxy stuff */
var isBusy = false;
var xmlHttp = getHTTPObject();
var xmlHttpCities = getHTTPObject();
var xmlHttpProject = getHTTPObject();


function getHTTPObject() {
	var xmlHttp = false;
	
	try {
		// Opera 8.0+, Firefox, Safari
		xmlHttp = new XMLHttpRequest();
		
	} catch (e){
		// Internet Explorer Browsers
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// Something went wrong
				alert("Your browser broke!");
				xmlHttp = false;
				//return false;
			}
		}
	}
	return xmlHttp;
} // end function getHTTPObject()

/* validation */
function attachFormHandlers() {
	var form = document.getElementById('form'); 
	
	if (document.getElementsByTagName) { //make sure were on a newer browser	
		var objInput = document.getElementsByTagName('input');

		for (var iCounter = 0; iCounter < objInput.length; iCounter++) {
			// iterate through the tags, checking if they are to be validated somehow
			if (objInput[iCounter].className.substr(0,8) == 'validate') {
				/*
				if (objInput[iCounter].addEventListener) {
				  objInput[iCounter].addEventListener('change', 'return validateMe(this)', false); 
				} 
				else if (objInput[iCounter].attachEvent) {
				  objInput[iCounter].attachEvent('onchange', 'return validateMe(this)');
				}*/
				objInput[iCounter].onblur = function() { return validateMe(this); } //attach the onchange to each input field
			}
		}
		
		// let's add the handler to the select tags as well
		var objInput = document.getElementsByTagName('select');

		for (var iCounter = 0; iCounter < objInput.length; iCounter++) {
			// iterate through the tags, checking if they are to be validated somehow
			if (objInput[iCounter].className.substr(0,8) == 'validate') {
				objInput[iCounter].onblur = function() { return validateMe(this); } //attach the onchange to each input field
			}
		}
		
		
	}
	//form.onsubmit = function() { return validate(); } attach validate() to the form
}


/*validateMe is the function called with onchange each time the user leaves the input box
passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
function validateMe(objInput) {

	sVal = objInput.value; //get value inside of input field
	sRules = objInput.className.split(' '); // get all the rules from the input box classname
	sRequired = sRules[1]; // determines if field is required or not
	sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
    gShow = sRules[3]; //gShow is the id where feedback is sent to.
		
	if (sTypeCheck == 'select') {
		sVal = 	objInput.selectedIndex;
	}
	if (sTypeCheck == 'radio') {
		sVal = objInput.checked;	
	}
	
	//sends the rules and value to the php page to be validated
	xmlHttp.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
  
	xmlHttp.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
	xmlHttp.send('');  
}


function handleHttpResponse() {
	//if the process is completed, decide to do with the returned data
	if (xmlHttp.readyState == 4) {
		
  		sResults = xmlHttp.responseText.split(","); //results is now whatever the feedback from the php page was

		//whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever  was returned by the asp page. 
    	if (document.getElementById(gShow).lastChild != null) {
    		// there is already an error message, is it the same as the result returned?
    		if (document.getElementById(gShow).lastChild.nodeValue == sResults[0]) {
    			// yes, set the error message to be null
    			document.getElementById(gShow).innerHTML = "";
    		}
    		if (sResults[0] == "") {
    			document.getElementById(gShow).removeChild(document.getElementById(gShow).lastChild);
    			document.getElementById(gShow).innerHTML = "";
    		}
    	}
    	document.getElementById(gShow).setAttribute("class","red");
    	document.getElementById(gShow).setAttribute("className","red"); // for ie
    	document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
  	}
}


function validate() { // note: this is done onsubmit
	var tables; 
    var gErrors = 0;
	var requiredElements = new Array;
	var inputFields = new Array;
	var checkedElements;
	var ruleElements;

	// get the span fields 
	tables = document.getElementsByTagName('span');
	// get the input fields that are required - added this part to take into account directly clicking on the Send button
	inputFields = document.getElementsByTagName('input');
	for (i=0; i < inputFields.length; i++) {
		if (inputFields[i].className.substr(0,8) == "validate") {
			requiredElements.push(inputFields[i].id);
		}	
	}
				
	for (i=0; i < tables.length; i++) { //loop through all the given elements 
	
		// if the class name of that td element is rules check to see if there are error warnings
		if (tables[i].className == "rules" || (tables[i].className == "red" && tables[i].id != "errormessage")) {
			
			//if there is a thank you or it's blank then it passes
			
			if (tables[i].innerHTML == 'Thank You' || tables[i].innerHTML == '' ) {
				tables[i].style.color = '#FF0000';//the color is changed to black or stays black
				
			}
			else {
				//tables[i].style.visibility = 'visible';
				gErrors = gErrors + 1; //the error count increases by 1
				//tables[i].style.color = '#ff0000';//error messages are changed to red
			}
		}
	}

	// loop through the requiredfields
	for (i=0; i < requiredElements.length; i++) {
		// check if the required element has a length - added this part to take into account directly clicking on the Send button
		if (gErrors > 0) {
			break;	
		}

		switch (document.getElementById(requiredElements[i]).type) {
			case 'checkbox':
				if (document.getElementById(requiredElements[i]).checked == false) {
					gErrors = gErrors + 1;
				}
				break;
			case 'radio':
				myOption = -1;
				if (checkedElements.indexOf(requiredElements[i]) == -1) {
					for (i=document.getElementById(requiredElements[i]).length-1; i > -1; i--) {
						if (document.getElementById(requiredElements[i]).checked) {
							myOption = i; i = -1;
						}
					}
					if (myOption == -1) {
						gErrors++;
						var error_id = document.getElementById('err_' + requiredElements[i]);
						error_id.style.visibility = 'visible';
					}
					
					checkedElements = checkedElements + requiredElements[i] + ',';
					
				}
				
				break;
				
			case 'text': 
				if (document.getElementById(requiredElements[i]).value.length == 0) {
					gErrors = gErrors + 1;
				}
				break;
		}
	}
	
	// now let's take care of select
	requiredElements = new Array;
	inputFields = document.getElementsByTagName('select');
	for (i=0; i < inputFields.length; i++) {
		if (inputFields[i].className.substr(0,8) == "validate") {
			requiredElements.push(inputFields[i].id);
		}	
	}

	// loop through the required select fields
	for (i=0; i < requiredElements.length; i++) {
		// check if the required element has a length - added this part to take into account directly clicking on the Send button
		if (document.getElementById(requiredElements[i]).selectedIndex == 0) {
			gErrors = gErrors + 1;
		}
	}
	
	
	if (document.getElementById('validate_me')) {
		if ((document.getElementById('validate_me').value.length == 0) || document.getElementById('validate_me').value != document.getElementById('hide').value) {
			var error_id = document.getElementById('validate_err');
			error_id.style.visibility = 'visible';
			gErrors++;
		}
		else {
			var error_id = document.getElementById('validate_err');
			error_id.style.visibility = 'hidden';
			gErrors--;
		}			
	} 

	if (gErrors > 0) {
		//if there are any errors give a message
		document.getElementById('errormessage').innerHTML = "<br />Please make sure all fields are properly completed. <br />";
		gErrors = 0; // reset errors to 0
		return false;
	}
	else {
		return true;
	}
}

function handleHttpResponseGetUser() {   
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var results = xmlHttp.responseText;
			document.getElementById('err_un').innerHTML = results;
			document.getElementById('err_un').style.visibility = 'visible';
			document.getElementById('err_un').className = 'red';
			if (results != '') {
				// set the value so the form doesn't submit
				document.getElementById('user_exists').value = '0';	
			}
			else {
				// make sure to reset user_exists
				document.getElementById('user_exists').value = '1';	
			}
      	}
    }
} // end function handleHttpResponse()

function handleHttpResponseCheckUnique() {   
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var results = xmlHttp.responseText;
			document.getElementById('err_name').innerHTML = results;
			document.getElementById('err_name').style.visibility = 'visible';
			document.getElementById('err_name').className = 'red';
      	}
    }
} // end function handleHttpResponse()

function changeLocation(baseURL, dropdown) {

    var myindex  = dropdown.selectedIndex;
    var selValue = dropdown.options[myindex].value;
    top.location.href = baseURL + selValue;
    
    return true;
}


function checkForUser() {    
	// Build the URL to connect to
	var url = "indexmodules?mod_id=1&username=";

    var sId = document.getElementById("username").value;
    xmlHttp.open("GET", url + escape(sId), true);
    xmlHttp.onreadystatechange = handleHttpResponseGetUser;
    xmlHttp.send('');
} 

function checkForArea() {    
	// Build the URL to connect to
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/formvalidation.php?validationtype=ajax&mode=gAreas&name=';///xtenzio/url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
	var name = document.getElementById("name").value;
	var city_id = document.getElementById("city_id").options[document.getElementById("city_id").selectedIndex].value;
    xmlHttp.open("GET", url + escape(name) + '&city_id=' + escape(city_id), true);
    xmlHttp.onreadystatechange = handleHttpResponseCheckUnique;
    xmlHttp.send('');
} 

function checkForCity() {    
	// Build the URL to connect to
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/formvalidation.php?validationtype=ajax&mode=gCities&name=';
	var sId = document.getElementById("name").value;

    xmlHttp.open("GET", url + escape(sId), true);
    xmlHttp.onreadystatechange = handleHttpResponseCheckUnique;
    xmlHttp.send('');
} 

function checkForFeature() {    
	// Build the URL to connect to
	
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/formvalidation.php?validationtype=ajax&mode=gFeatures&name=';///xtenzio/url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
	var sId = document.getElementById("name_en").value;

    xmlHttp.open("GET", url + escape(sId), true);
    xmlHttp.onreadystatechange = handleHttpResponseCheckUnique;
    xmlHttp.send('');
} 

function checkForIsland() {    
	// Build the URL to connect to
	
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/formvalidation.php?validationtype=ajax&mode=gIslands&name=';///xtenzio/url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
	var sId = document.getElementById("name").value;

    xmlHttp.open("GET", url + escape(sId), true);
    xmlHttp.onreadystatechange = handleHttpResponseCheckUnique;
    xmlHttp.send('');
} 

function checkForSpecification() {    
	// Build the URL to connect to
	
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/formvalidation.php?validationtype=ajax&mode=gSpecifications&name=';///xtenzio/url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
	var sId = document.getElementById("name_en").value;

    xmlHttp.open("GET", url + escape(sId), true);
    xmlHttp.onreadystatechange = handleHttpResponseCheckUnique;
    xmlHttp.send('');
} 

function getAreas(sel) {
	document.getElementById('area_id').options.length = 0;
	
	var sId = sel.options[sel.selectedIndex].value;
	//var langId = document.getElementById('language_id').value;
	var langId = 1;
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/ajax_functions.php?mode=gAreas&city_id=';
    //xmlHttp.open("GET", url + escape(sId), true);
    // to avoid the error Permission denied to call method XMLHttpRequest.open http://blog.strainu.ro/programming/html/permission-denied-to-call-method-xmlhttprequestopen/
   	xmlHttp.open("GET", url + sId + '&lang_id=' + langId, true); 
    xmlHttp.onreadystatechange = handleHttpResponseGetArea;
    xmlHttp.send('');		
}

function getDistricts(sel) {
	
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/ajax_functions.php?mode=gDistricts&country_id=';	
	var sId = sel.options[sel.selectedIndex].value;
	var langId = document.getElementById('language_id').value;
	
    if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}
    xmlHttp.open("GET", url + escape(sId) + '&lang_id=' + langId, true);
    isBusy = true;
    xmlHttp.onreadystatechange = handleHttpResponseGetDistrict;
    xmlHttp.send('');	
}

function getCitiesPerDistrict(sel) {
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/ajax_functions.php?mode=gCities&district_id=';
	var sId = sel.options[sel.selectedIndex].value;
	if (sId.length == 0) {
		url = 'http://' + location.host + path + 'assets/modules/realEstate/ajax_functions.php?mode=gCities&country_id=';
		sId = document.getElementById('country_id').options[document.getElementById('country_id').selectedIndex].value;
	} 
	var langId = document.getElementById('language_id').value;
    if (isBusy) {
		xmlHttpCities.onreadystatechange = function () {}
		xmlHttpCities.abort();
	}
    xmlHttpCities.open("GET", url + escape(sId) + '&lang_id=' + langId, true);
    isBusy = true;
    xmlHttpCities.onreadystatechange = handleHttpResponseGetCity;
    xmlHttpCities.send('');	
}

function getCitiesPerCountry(sel) {
	var sId = sel.options[sel.selectedIndex].value;
    if (isBusy) {
		xmlHttpCities.onreadystatechange = function () {}
		xmlHttpCities.abort();
	}
    xmlHttpCities.open("GET",'http://' + location.host + path +'assets/modules/realEstate/ajax_functions.php?mode=gCities&country_id=' + sId, true); 
    
    isBusy = true;
    xmlHttpCities.onreadystatechange = handleHttpResponseGetCity;
    xmlHttpCities.send('');	
}

function getProjects(sel) {
	
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/ajax_functions.php?mode=gProjects&area_id=';
	var sId = sel.options[sel.selectedIndex].value;
   
   if (isBusy) {
		xmlHttpProject.onreadystatechange = function () {}
		xmlHttpProject.abort();
	}
	document.getElementById('project_id').options.length = 0;
	
	xmlHttpProject.open("GET", url + escape(sId), true);
	isBusy = true;
    xmlHttpProject.onreadystatechange = handleHttpResponseGetProject;
    xmlHttpProject.send('');		
}

function getProjectsPerCity(sel) {
	
	var url = 'http://' + location.host + path + 'assets/modules/realEstate/ajax_functions.php?mode=gProjects&city_id=';
	var sId = sel.options[sel.selectedIndex].value;
   
   if (isBusy) {
		xmlHttpProject.onreadystatechange = function () {}
		xmlHttpProject.abort();
	}
	document.getElementById('project_id').options.length = 0;
	
	xmlHttpProject.open("GET", url + escape(sId), true);
	isBusy = true;
    xmlHttpProject.onreadystatechange = handleHttpResponseGetProject;
    xmlHttpProject.send('');		
}


function getProjectInfo(sId) {
	
	var url = 'http://' + location.host + path +'assets/modules/realEstate/ajax_functions.php?mode=gProjects&project_id=';

	if (isBusy) {
		xmlHttpProject.onreadystatechange = function () {}
		xmlHttpProject.abort();
	}

    xmlHttpProject.open("GET", url + escape(sId), true); 
    isBusy = true;
    xmlHttpProject.onreadystatechange = handleHttpResponseGetProjectInfo;
    xmlHttpProject.send('');		
}

function handleHttpResponseGetProjectInfo() {   
	if (xmlHttpProject.readyState == 4) {
		if (xmlHttpProject.status == 200) {
			var obj = document.getElementById('projectInfo');
			//eval('alert( \'hi\');');
			eval(xmlHttpProject.responseText);	
      	}
    }
} // end function handleHttpResponseGetProjectInfo()

function handleHttpResponseGetArea() {   
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var obj = document.getElementById('area_id');
			obj.options.length = 0;
			//obj.options[obj.options.length] = new Option('          Town','');
			eval(xmlHttp.responseText);	
      	}
    }
} // end function handleHttpResponseGetArea()

function handleHttpResponseGetDistrict() 
{   
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var obj = document.getElementById('district_id');
			obj.options.length = 0;
			obj.options[obj.options.length] = new Option('     District ','');
			eval(xmlHttp.responseText);	
      	}
    }
} // end function handleHttpResponseGetIsland()

function handleHttpResponseGetCity() 
{   
	if (xmlHttpCities.readyState == 4) {
		if (xmlHttpCities.status == 200) {
			
			var obj = document.getElementById('city_id');
			obj.options.length = 0;
			//obj.options[obj.options.length] = new Option(' Area ','');
			eval(xmlHttpCities.responseText);	
      	}
    }
} // end function handleHttpResponseGetCity()


function handleHttpResponseGetProject() {   
	if (xmlHttpProject.readyState == 4) {
		if (xmlHttpProject.status == 200) {
			var obj = document.getElementById('project_id');
			obj.options.length = 0;
			obj.options[obj.options.length] = new Option('Project','');
			eval(xmlHttpProject.responseText);	
      	}
    }
} // end function handleHttpResponseGetProject()


function swapFields(sel) {

	if (sel.value == 4) {
		document.getElementById('plotsize').style.display = 'block';
		document.getElementById('bedrooms').style.display = 'none';
	} // end plots
	else {
		document.getElementById('plotsize').style.display = 'none';
		document.getElementById('bedrooms').style.display = 'block';	
	}
}

function setAddressToRequired() {
	document.getElementById('address').className = 'validate required none err_address';
	document.getElementById('address').onblur = function() { return validateMe(this); }
}
function setAddressToOptional() {
	document.getElementById('address').className = '';
	document.getElementById('err_address').innerHTML = '';
	document.getElementById('address').onblur = function() { }
}


//http://codingforums.com/showthread.php?p=604879
function validateCompare() {
	// note that this currently checks all checkboxes on the page
	var chkedBoxes = [], i = 0, inputs = document.getElementsByTagName('input');
	var listings;
	
	while (i<inputs.length) {
	  if (inputs[i].type == 'checkbox' && inputs[i].checked) {
	   	// it's checked
	    chkedBoxes.push(inputs[i].value);
	    inputs[i].checked = false;
	  }
	  i++;
	  
	}
	document.getElementById('listingsToCompare').value = chkedBoxes;
	if (chkedBoxes.length == 0) {
		alert('Please select some properties to compare');
		return false;
	}
	
}

/* http://www.webreference.com/programming/javascript/form/2.html
	this stuff is for the translate select */

var isActive = false;

function IsIE() {
	return ( navigator.appName=="Microsoft Internet Explorer" );
}

function showMenu(){
  isActive = true;
  if (IsIE()) {
  	document.getElementById("language_select").style.visibility="hidden";
  }
}

function hideMenu(){
  isActive = false;
  setTimeout('hide()',5);
}

function hide(){
  if(!isActive){
  	  if (document.getElementById("language_select")) {
    		document.getElementById("language_select").style.visibility="visible";
      }
  }
}
