// netEconomist Google Map integration code and other general purpose functions
// ewhitten :  7.31.2006

var maps = {};
var http_request = false;
var client_id = "";

function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}

/* Make it so I only have to include one file */
function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)
}

/* Generic cross-platform XML HTTP requestor */
function makeRequest(url, parameters,callback,mimeType,asynchronous) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType(mimeType);
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = callback;
      http_request.open('GET', url + parameters, asynchronous);
      http_request.send(' ');
}

function initializeMapDivs()
{
	// get list of mapDivs
	var divCollection = document.getElementsByTagName("div");
	var theList = new Array();
	var j = 0;
	
    for (var i = 0; i < divCollection.length; i++) {
    	if(divCollection[i].getAttribute("class") == "mapDivStub") {
			theList[j] = divCollection[i].getAttribute("id");
			j++;
        } 
    }
	// set display:none and overflow:hidden for all the ones I want
	for (var i = 1; i < theList.length; i++) {
		document.getElementById(theList[i]).style.display = "none";
		document.getElementById(theList[i]).style.overflow = "hidden";
	}

}

function showOrHide(divName,address) {
	
	var mapDiv 	= document.getElementById(divName);
	var x = new Array();
	x = divName.split("_");
	var mapTitle = "mapTitle_" + x[1];
	
/* Is map currently visible? If yes, slide up and hide.  If no, slide down and make visible */
	
	if (document.getElementById(mapTitle).innerHTML == "Map this Property") {
		mapDiv.style.display = "block";
		mapDiv.style.overflow = "visible";
		/* add map to div */
		addGoogleMap(divName,address);
		document.getElementById(mapTitle).innerHTML = "Hide this Map";
	} else {
		document.getElementById(mapTitle).innerHTML = "Map this Property";
		mapDiv.style.display = "none";
		mapDiv.style.overflow = "hidden";
		// clear map from div
		mapDiv.innerHTML = "";
	}
	
}

function addGoogleMap(divName,address) 
{
	if (GBrowserIsCompatible())  {    
        var map = new GMap2(document.getElementById(divName));
		
		if ((address == "0,0") || (address == "None,None")) {
			document.getElementById(divName).innerHTML = "<span class='mapStyle'>We were unable to find an address for this property.<br/>We apologize for the inconvenience.</span>";
		} else {
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			var coordArray = address.split(",");
			var point = (new GLatLng(coordArray[0],coordArray[1]));		
       		var icon = new GIcon(G_DEFAULT_ICON);
			icon.image = "http://static.blazingsystems.com/themes/default/blue-marker.png";
           	icon.shadow = "http://static.blazingsystems.com/themes/default/blue-shadow.png";
           	icon.iconSize = new GSize(20,34);
           	icon.shadowSize = new GSize(53,34);
           	icon.iconAncher = new GPoint(10,34);
           	icon.infoWindowAnchor = new GPoint(10,1);
        	map.setCenter(point, 15);
        	var marker = new GMarker(point, {icon:icon});
        	map.addOverlay(marker);
      	}
    }
}

function featurePageMap()
{
	var address = document.getElementById("mapData").innerHTML;

	addGoogleMap("mapDiv",address);
}


/* Global variable to make Gmap2 object accessible */
var map = "";
var result_id = 0;

function addGoogleSearchMap(divName,latitude,longitude) {
	// add a google search map with to a given div with starting lat/long
	if (GBrowserIsCompatible())  {    
        map = new GMap2(document.getElementById(divName));
		
       	map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(latitude,longitude), 12);
	}
}

function initSearchPage()
{
	if(typeof Rico != 'undefined') {
		var roundCorners = Rico.Corner.round.bind(Rico.Corner);
		roundCorners('mapOption',{corners:"bl br"});	
		roundCorners('neighborhoodOption',{corners:"bl br"});	
		roundCorners('popularCitiesOption',{corners:"bl br"});
	}
	
	if(document.getElementById("extendedNeighborhood")) {
		document.getElementById("extendedNeighborhood").style.display = "none";
		document.getElementById("extendedNeighborhood").style.overflow = "hidden";
	}
	if(document.getElementById("extendedMap")) {
		document.getElementById("extendedMap").style.display = "none";
		document.getElementById("extendedMap").style.overflow = "hidden";
	}
	
	
	/* Load global client_id for xmlhttp-based link creation */
	client_id = 674

	/* Eli Ribble - May 23, 2008 - Very hackish. The customer at 255 doesn't want to show the map by default any more, so we remove it if one of their other customizations is present. */
	if(document.getElementById("extendedSchoolDistrict") != null) {
		roundCorners('schoolDistrictOption',{corners:"bl br"});
		document.getElementById("extendedSchoolDistrict").style.display = "none";
		document.getElementById("extendedSchoolDistrict").style.overflow = "hidden";
	}
	else 
		initMapSearch();
}

function initNeighborhoodSearch() 
{
	// Hide all other extended search divs and show neighborhood div
	document.getElementById("extendedMap").style.display = "none";
	document.getElementById("extendedMap").style.overflow = "hidden";
	
	document.getElementById("extendedPopularCities").style.display = "none";
	document.getElementById("extendedPopularCities").style.overflow = "hidden";
	
	if(document.getElementById("extendedSchoolDistrict")) {
		document.getElementById("extendedSchoolDistrict").style.display = "none";
		document.getElementById("extendedSchoolDistrict").style.overflow = "hidden";
	}

	// clear popular city array and conflicting select boxes
	selectedCities.length = 0;
	selectInDropdown("county_id","-- Any County --")
	selectInDropdown("school_district_sel_id","-- School Districts --")
	selectInDropdown("city_sel_id","-- Cities --")
	document.getElementById("in_postal_code").value = "";
	
	var showDiv = document.getElementById("extendedNeighborhood");
	showDiv.style.display = "block";
	showDiv.style.overflow = "visible";
	
	
	// Change extendedHeader text
	document.getElementById("extendedHeader").innerHTML = "Choose the neighborhoods you'd like to search by below:";
	document.getElementById("bottomSearch").style.visibility = "visible";
}

function initMapSearch()
{
	// Hide all other extended search divs and show mapsearch div
	if(document.getElementById("extendedNeighborhood")) {
		document.getElementById("extendedNeighborhood").style.display = "none";
		document.getElementById("extendedNeighborhood").style.overflow = "hidden";
	}
	
	if(document.getElementById("extendedPopularCities")) {
		document.getElementById("extendedPopularCities").style.display = "none";
		document.getElementById("extendedPopularCities").style.overflow = "hidden";
	}
	
	if(document.getElementById("extendedSchoolDistrict")) {
		document.getElementById("extendedSchoolDistrict").style.display = "none";
		document.getElementById("extendedSchoolDistrict").style.overflow = "hidden";
	}
	
	if(document.getElementById("map_full_results"))
		document.getElementById("map_full_results").style.display="none";	
	
	var showDiv = document.getElementById("extendedMap");
	if(showDiv) {
		showDiv.style.display = "block";
		showDiv.style.overflow = "visible";
	}
	
	// Change extendedHeader text
	if(document.getElementById("extendedHeader"))
		document.getElementById("extendedHeader").innerHTML = "Enter an address and select a range to find properties in your area.";	
	
	// Reset search options
	if(document.getElementById("searchAddressInput"))
		document.getElementById("searchAddressInput").value = "";
	if(document.getElementById("mapSearchRadius"))
		document.getElementById("mapSearchRadius").selectedIndex = 0;
	if(document.getElementById("mapRefineBeds"))
		document.getElementById("mapRefineBeds").value = "";
	if(document.getElementById("mapRefinePropertyType"))
		document.getElementById("mapRefinePropertyType").value = "";
	if(document.getElementById("mapRefinePriceRange"))
		document.getElementById("mapRefinePriceRange").value = "";
	
	/* Hide search refining options */
	if(document.getElementById("mapSearchOptions"))
		document.getElementById("mapSearchOptions").style.visibility = "hidden";
	if(document.getElementById("bottomSearch"))
		document.getElementById("bottomSearch").style.visibility = "hidden";
	
	// Load the map centered on the user-selected coordinates
	var startCoordinates = document.getElementById("google_map_start").value;
	var coordArray = startCoordinates.split(",");
	
//	addGoogleSearchMap("map",39.948701,-75.164337);
	if(document.getElementById("map"))
		addGoogleSearchMap("map",coordArray[0],coordArray[1]);
}

function initPopularCities()
{
	// Hide all other extended search divs and show popular city divs
	document.getElementById("extendedMap").style.display = "none";
	document.getElementById("extendedMap").style.overflow = "hidden";
	
	document.getElementById("extendedNeighborhood").style.display = "none";
	document.getElementById("extendedNeighborhood").style.overflow = "hidden";
	
	if(document.getElementById("extendedSchoolDistrict")) {
		document.getElementById("extendedSchoolDistrict").style.display = "none";
		document.getElementById("extendedSchoolDistrict").style.overflow = "hidden";
	}

	// clear neighborhood array and conflicting select boxes
	selectedNeighborhoods.length = 0;
	selectInDropdown("county_id","-- Any County --")
	selectInDropdown("school_district_sel_id","-- School Districts --")
	selectInDropdown("city_sel_id","-- Cities --")
	document.getElementById("in_postal_code").value = "";
	
	
	document.getElementById("extendedPopularCities").style.display = "none";
	document.getElementById("extendedPopularCities").style.overflow = "hidden";
	
	var showDiv = document.getElementById("extendedPopularCities");
	showDiv.style.display = "block";
	showDiv.style.overflow = "visible";
	
	
	// Change extendedHeader text
	document.getElementById("extendedHeader").innerHTML = "Choose the popular cities you'd like to search by below:";
	document.getElementById("bottomSearch").style.visibility = "visible";
}

/* Added by Eli Ribble May 23, 2008. Originally I wanted to add this to the custom files for user 255, glocker.com, as per their request to add the school district search. Unfortunately, I couldn't figure out how to easily get a custom ne_functions.js file to be read from the directory structure, so I opted to put the function here, in the general file, because I didn't see any harm in having additional functions that are only used by a single user. Sure, it'd be way better to have it with the other custom files, but I'm uncertain if the system can intelligently use it, so I'm leaving it here for now. Also, I've modified the other init functions to properly hide the school district search tab, even though it won't be present in any other site. */
function initSchoolDistrictSearch()
{
	// Hide all other extended search divs and show school district divs
	document.getElementById("extendedMap").style.display = "none";
	document.getElementById("extendedMap").style.overflow = "hidden";
	
	document.getElementById("extendedNeighborhood").style.display = "none";
	document.getElementById("extendedNeighborhood").style.overflow = "hidden";
	
	document.getElementById("extendedPopularCities").style.display = "none";
	document.getElementById("extendedPopularCities").style.overflow = "hidden";

	// clear neighborhood array and conflicting select boxes
	//selectedNeighborhoods.length = 0;
	//selectInDropdown("county_id","-- Any County --")
	//selectInDropdown("school_district_sel_id","-- School Districts --")
	//selectInDropdown("city_sel_id","-- Cities --")
	//document.getElementById("in_postal_code").value = "";
	
	
	document.getElementById("extendedSchoolDistrict").style.display = "none";
	document.getElementById("extendedSchoolDistrict").style.overflow = "hidden";
	
	var showDiv = document.getElementById("extendedSchoolDistrict");
	showDiv.style.display = "block";
	showDiv.style.overflow = "visible";
	
	
	// Change extendedHeader text
	document.getElementById("extendedHeader").innerHTML = "Choose the school district you'd like to search by below:";
	document.getElementById("bottomSearch").style.visibility = "visible";
}
function searchAddress() {
	/* Pull address and range for search and geocode */
	var srcAddress = document.getElementById("searchAddressInput").value;
	
	/* Geocode source point */
	if (srcAddress != "") {
		googleGeocode(srcAddress);
	} else {
		alert("You must enter a starting address.");
	}
}

function plotMapSourcePoint(srcPoint) {
	/* This function should handle initial search as well as refining searches */
	
	map.setCenter(srcPoint,14);
	map.savePosition();
	
	/* Clear previously generated overlays, if any. */
	map.clearOverlays();
	
	/* Show visual hint spinner */
	document.getElementById("spinner").style.visibility = "visible";
	
	/* Set zoom appropriately */
	var searchRange = document.getElementById("mapSearchRadius").value;
	switch (searchRange) {
		case ".1":map.setZoom(16); break;
		case "1": map.setZoom(14); break;
		case "2": map.setZoom(13); break;
		case "5": map.setZoom(12); break;
		case "10": map.setZoom(11); break;
		case "20": map.setZoom(10); break;
		default: break;
	}
	
	/* Poll for all map search options */
	var additionalMapSearchOptions = refineMapSearchOptions();
	
	/* Fire XMLHTTP request to find properties in range */
	makeRequest('/radialSearch.php','?searchRadius=' + searchRange + '&srcLong='  + srcPoint.x + '&srcLat=' + srcPoint.y + additionalMapSearchOptions,plotMapSearchResults,'text/xml',true);
}

function refineMapSearchOptions() {
	/* Build list of refining map options */
	var optionArray = new Array();
	
	/* Refine number of beds, property type, and price range */
	if (document.getElementById("mapRefineBeds").value != "") {
		optionArray.push(document.getElementById("mapRefineBeds").value);
	}
	if (document.getElementById("mapRefinePropertyType").value != "") {
		optionArray.push(document.getElementById("mapRefinePropertyType").value);
	}
	if (document.getElementById("mapRefinePriceRange").value != "") {
		optionArray.push(document.getElementById("mapRefinePriceRange").value);
	}
	
	if (optionArray.length != 0) {
		return "&" + optionArray.join("&")
	}
	return "";
}

function storeMapRefineOption(refineOption,refineValue,refineDivName,optionType) {
	/* temporarily store some map search options */
	document.getElementById(refineOption).value = refineValue;
	/* Highlight selected refine option */
	hintMapOptions(optionType,refineDivName);
	
	/* Restore to original position/zoom and fire off new search */
	map.returnToSavedPosition();
	plotMapSourcePoint(map.getCenter());
}

function hintMapOptions(optionType,selectedOption) {
	var numBeds = new Array("refineBedsAny","refineBedsOneTwo","refineBedsThreeFour","refineBedsFivePlus");
	var propertyType = new Array("refinePropertyTypeAny","refinePropertyTypeMobile","refinePropertyTypeTownhouse","refinePropertyTypeMultiFamily","refinePropertyTypeLandFarms","refinePropertyTypeCommercial","refinePropertyTypeResidentialRental","refinePropertyTypeAllResidential");
	var priceRange = new Array("refinePriceAny","refinePriceOne","refinePriceTwo","refinePriceThree","refinePriceFour","refinePriceFive","refinePriceSix");
	
	if (optionType == "beds") {
		for (i = 0; i < numBeds.length; i++) {
			document.getElementById(numBeds[i]).style.backgroundColor = "#FFFFFF";
		}
		highlightCell(selectedOption);
	}
	
	if (optionType == "property") {
		for (i = 0; i < propertyType.length; i++) {
			document.getElementById(propertyType[i]).style.backgroundColor = "#FFFFFF";
		}
		highlightCell(selectedOption);
	}
	
	if (optionType == "price") {
		for (i = 0; i < priceRange.length; i++) {
			document.getElementById(priceRange[i]).style.backgroundColor = "#FFFFFF";
		}
		highlightCell(selectedOption);
	}
}

function plotMapSearchResults() {
	/* Fill in map with markers for property results */
	if (http_request.readyState == 4) {
    	if (http_request.status == 200) {
			if (BrowserDetect.browser == "Explorer") {
				var response = new ActiveXObject("Microsoft.XMLDOM");
				response.loadXML(http_request.responseText);
			} else { 
				var response = http_request.responseXML;
			}
			/* Build custom icon for marker too */
		        var icon = new GIcon(G_DEFAULT_ICON);
        		icon.image = "http://static.blazingsystems.com/ts/themes/default/blue-marker.png";
        		icon.shadow = "http://static.blazingsystems.com/ts/themes/default/blue-shadow.png";
        		icon.iconSize = new GSize(20,34);
        		icon.shadowSize = new GSize(53,34);
        		icon.iconAncher = new GPoint(10,34);
        		icon.infoWindowAnchor = new GPoint(10,1);

			var oRoot = response.documentElement;
			var properties = oRoot.getElementsByTagName("property");
			for (var i = 0; i < properties.length; i++) {
				var property_id = properties[i].getAttribute("id");
				result_id = properties[i].getAttribute("result_id");
				var count = properties[i].getAttribute("count");
				currentChild = properties[i].firstChild;
				do {
					switch (currentChild.childNodes[0].parentNode.nodeName) {
						case "latitude": proplat = currentChild.childNodes[0].nodeValue; break;
						case "longitude": proplong = currentChild.childNodes[0].nodeValue; break;
						default: break;
					}
				} while (currentChild = currentChild.nextSibling);
				point = new GLatLng(proplat,proplong);
				map.addOverlay(createMarker(point,property_id,result_id,icon));
			}
			/* Hide spinner again */
			document.getElementById("spinner").style.visibility = "hidden";
			
			/* Show search refining options */
			document.getElementById("mapSearchOptions").style.visibility = "visible";

			/* Build "View All Results link" */
			var client_id = document.getElementById("client_id").value;
			var template = document.getElementById("results_template").value;
			var t = template.split(".");
			var path = t[0].split("_");
			var resultsURL = "http://mls.blazingsystems.com/" + path[2] + "/" + path[0] + "/" + path[1] + "/" + client_id + "/" + result_id + "/0";
			if (count > 1) {
				document.getElementById("map_full_results").innerHTML = '<a href="' + resultsURL + '">View All ' + count + ' Properties.</a>';
			} else if (count == 1) {
				document.getElementById("map_full_results").innerHTML = '<a href="' + resultsURL + '">View The Current Property.</a>';
			} else {
				document.getElementById("map_full_results").innerHTML = '<span style="color:#006699;font-size:10px">No properties found.</span>';
			}
			document.getElementById("map_full_results").style.display="block";
		}
	}
}

function createMarker(point,property_id,result_id,icon) {
	var client_id = document.getElementById("client_id").value;
	var client_type = document.getElementById("client_type").value;
	var mls_name = document.getElementById("mls_name").value;

	var marker = new GMarker(point, {icon:icon});
	GEvent.addListener(marker, "click", function() {
		var request = GXmlHttp.create();
		request.open("GET", "/radialSearchDetail.php?client_id=" + client_id + "&mls_name=" + mls_name + "&client_type=" + client_type + "&property_id=" + property_id + "&result_id=" + result_id, true);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
		        marker.openInfoWindowHtml(request.responseText);
			} else {
				marker.openInfoWindowHtml("Loading ...<img src='http://static.blazingsystems.com/shared/spinner.gif'");
			}
 		};
		request.send(null);
  });
  return marker;
}

function googleGeocode(srcAddress) {
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(srcAddress,function (point) {
		if (!point) {
			alert(srcAddress + " was not found.  Please try again.");
		} else {
			plotMapSourcePoint(point);
		}
	});
}

function savePropertyListing(client_id,property_id) {
        var request = GXmlHttp.create();
        request.open("GET", "/save/" + client_id + "/" +  property_id + "/0/0/" + Math.random(), true);
        request.onreadystatechange = function() {
                if (request.readyState == 4) {
                        // reload iframe to show new property in save box... try/catch in case we're on the search page
						try {
				            var saves = document.getElementById("saved_property_sidebar");
							try {
								window.frames.saved_property_sidebar.reloadMe();
							} catch(e) {
								// nada
							}
				         } catch (e) {
							// do nothing.
				         }
                }
        };
        request.send(null);
}

function delPropertyListing(client_id,property_id) {
	var request = GXmlHttp.create();
	request.open("GET", "/saved_property_del/" + client_id + "/" +  property_id + "/" + Math.random(), true);
	request.onreadystatechange = function() {
	        if (request.readyState == 4) {
	                document.location.href = document.location.href;
	        }
	};
	request.send(null);
}

function saveSearch(email) {
	if (email == "None") {
		email = "";
	}
		
	/* Reset fields */
	//document.getElementById("save_search_name").value = "";
	document.getElementById("save_search_email").value = email;
	document.getElementById("save_search_freq").selectedIndex = 0;
	
	/* Ask the user to name this search and select a frequency */
	var promptSlider = document.getElementById("testSlide");
	promptSlider.style.display = "block";
	document.getElementById("cpanel_saveSearch").style.height = '169px';
	/* The rest is triggered below. */
}

function saveSearchSubmit(person_id,result_id,client_id,email) {
	
	/* Get SQL query used to generate these results. Grab it differently if this is a featured result set. */
	sql_query = document.getElementById("squery").value;
	if (sql_query == "None") {
		sql_query = document.getElementById("fquery").value;
	}

	/* Bypass weird PIE string issues */
	foo = sql_query.split("\\");
	sql_query = foo.join('');
	
	/* In case of a map search, the + sign seems to get chopped somewhere.  Replace it on this end with a PLUS,then
	   undo this on the other end */
	if (sql_query.indexOf("+") != -1 ) {
		bar = sql_query.split("+");
		sql_query = bar.join("PLUS");
	}
	
	search_name = document.getElementById("save_search_name").value;
	email = document.getElementById("save_search_email").value;
	
	f = document.getElementById("save_search_freq");
	frequency = f.options[f.selectedIndex].value;
	client_id = document.getElementById("client_id").value;
	person_id = document.getElementById("person_id").value;
	
	if (email == "") {
		alert("You must register or login for an account in order to save your searches.");
		return false;
	}
	
	if ((email == "") || (search_name == "") || (frequency == "")) {
		alert("You must enter a valid email address, name, and frequency for your saved search.");
		return false;
	}
	
	var promptSlider = document.getElementById("testSlide");
	promptSlider.style.display = "none";
	document.getElementById("cpanel_saveSearch").style.height = '36px';
	
	/* Post this out */
	var rq = "client_id=" + client_id + "&person_id=" + person_id + "&email=" + email + "&name=" + search_name + "&freq=" + frequency + "&sql=" + sql_query;
	
	var request = GXmlHttp.create();
	    request.open("GET", "/render.pie?tmpl=save_search.xml&" + encodeURI(rq), true);
	     request.onreadystatechange = function() {
	             if (request.readyState == 4) {
	                    // reload iframe to show new saved search in save box
						var saves = document.getElementById("saved_searches_sidebar");
						window.frames.saved_searches_sidebar.reloadMe();
	             }
	     };
	     request.send(null); 
}

function delSearch(person_id,search_cache_id,client_id) {
        var request = GXmlHttp.create();
        request.open("GET", "/del_search/" + person_id + "/" +  search_cache_id + "/" + client_id + "/" + Math.random(), true);
        request.onreadystatechange = function() {
                if (request.readyState == 4) {
                        document.location.href = document.location.href;
                }
        };
        request.send(null);
}


/* global var to handle neighborhood search list */
var selectedNeighborhoods = new Array();
var selectedCities = new Array();

function highlightCell(cell) {
	document.getElementById(cell).style.backgroundColor = "#FFFFCC";
}

function removeHighlight(searchObject,sourceArray,defaultStyle) {
	var cell = document.getElementById(searchObject);
	if (!isSelectedItem(searchObject,sourceArray)) {
		if (defaultStyle == 0) {
			cell.style.backgroundColor = "#FFFFFF";
		} else {
			cell.style.backgroundColor = "#F0F0F0";
		}
	} else {
		cell.style.backgroundColor = "#FFFF99"
	}
}

function selectItem(searchObject,sourceArray,defaultStyle) {
	/* Function to build user selection of items in a grid for search */
	var cell = document.getElementById(searchObject);
	
	/* If item is already in the list, remove and revert style */
	if (isSelectedItem(searchObject,sourceArray)) {
		sourceArray = removeArrayItem(sourceArray,searchObject);
		if (defaultStyle == 0) {
			cell.style.backgroundColor = "#FFFFFF";
		} else {
			cell.style.backgroundColor = "#F0F0F0";
		}
	}
	else {
		/* If no, add to end and highlight cell */
		document.getElementById(searchObject).style.backgroundColor = "#FFFF99";
		sourceArray.push(searchObject);
	}
	// document.getElementById("debug").innerHTML = outputArray(sourceArray);
}

function removeArrayItem(array,searchText) {
	var x = new Array ();
	for (i = 0; i < array.length; i++) {
		if (array[i] != searchText) {
			x.push(array[i])
		}
	}
	return x;
}

function isSelectedItem(searchObject,sourceArray) {
	/* Determine if an array contains a given object */
	for (i = 0; i < sourceArray.length; i++) {
		if (sourceArray[i] == searchObject) {
			return true;
		}
	}
	return false;
}
	
function collectArray(destinationInput,sourceArray) {
	/* Place the contents of a given array as comma-delimited list in a given input object */
	document.getElementById(destinationInput).value = outputArray(sourceArray);
}

function outputArray(array) {
	return array.join();
}

function selectInDropdown(dropdown,searchText) {
	// generic function to search a given dropdown and select the searchText
	var selectList = document.getElementById(dropdown);
	
	for (i = 0; i < selectList.options.length; i++) {
		if (selectList.options[i] == searchText) {
			dropdown.selectedIndex = i;
		}
	}
}

/* XMLHTTP functions for saved property signup functionality */
function myPropertiesSignup() {
	o=document.getElementById('signup');
	o.style.visibility='visible';
	o.style.display='block';
}


function doLogin() {
	var login = document.getElementById("login_email").value;
	var pass = document.getElementById("login_password").value;
	var request = GXmlHttp.create();
	var client_id = document.getElementById("client_id").value;
	
	if ((login != '') && (pass != '')) {
		request.open('GET',"/render.pie?tmpl=saved_property_login.xml&client_id=" + client_id + "&login_email=" + login + "&login_password=" + pass ,true);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				if (request.responseText.indexOf('OK') !== -1 ) {
					location.reload();
				} else {
					alert("Incorrect Username/Password.  Please try again.");
				}	
			}
		};
		request.send(null);
	} 	
}

function doSignup() {
	var password = document.getElementById('signup_password').value;
	var verify = document.getElementById('signup_verify').value;
	var signup_email = document.getElementById('signup_email_address').value;
	var client_id = document.getElementById("client_id").value;
	var person_id = document.getElementById("person_id").value;

	if (password != verify) {
		alert("Your password and verify do not match");
	} else if (signup_email.indexOf("@") == -1) {
		alert("Please enter a valid email address");
	} else if (password.length < 4) {
		alert("Please enter a password with at least four characters");
	} else {
		var request = GXmlHttp.create();
		request.open("GET","/render.pie?tmpl=signup_user.xml&amp;sid=" + Math.random() + "&amp;client_id=" + client_id + "&amp;signup_password=" + escape(password) + "&amp;signup_email=" + escape(signup_email) + "&amp;in_person_id=" + person_id,true);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				c = request.responseText;
				if (c.indexOf("error")==0) {
                                	errText=c.substr(7);
                        	} else {
                                	o = document.getElementById('signup');
                               		o.style.display='none';
                                	//o.style.overflow='visible';
                                	n = c.split("|");
                                	var login_person_id = n[0];
                                	var login_password = n[1];
                                	//alert("id: " + login_person_id + "  | pass:  " + login_password);
					var nextyear=new Date();
                                	nextyear.setFullYear(nextyear.getFullYear()+1);
                                	//saveData("login_person_id",login_person_id);
					//saveData("login_password",login_password);
					document.cookie="login_person_id=" + login_person_id + "; path=/; expires=" + nextyear.toGMTString();
                                	document.cookie="login_password=" + login_password + "; path=/; expires=" + nextyear.toGMTString();
                        		location.reload();
				}
			}
		};
		request.send(null);
	}
}



function hide(layer) {
	o=document.getElementById(layer);
	o.style.display='block';
	o.style.overflow='visible';
}

function saveData(in_name, in_data) {
	if (in_data!=undefined) {
		nextyear=new Date();
		nextyear.setFullYear(nextyear.getFullYear()+1);
		document.cookie=in_name+"="+in_data+"; path=/; domain=$domain; expires="+nextyear.toGMTString();
	}
}

function getCookie(in_name) {
	c=document.cookie.split(";");
	for (a=0;a < c.length;a++) {
		z=c[a].split("=");
		z[0]=z[0].replace(" ","");
		if (z[0]==in_name) {
			return z[1];
		}
	}
	return "";
}

function delLoginCookie() {
	var expirationDate = new Date();
	expirationDate.setYear(expirationDate.getYear() - 1);
	expirationDate = expirationDate.toGMTString();

	var dc = document.cookie;
	var tempString = "";
	var tempChar;
	var count = 0;
	var cookieLength = dc.length;

	while (count < cookieLength) {
		tempChar = dc.charAt(count);
		if (tempChar == '=') {
			if (tempString == "login_person_id" || tempString == "login_password") {
				document.cookie = tempString + "=null; path=/; expires= " + expirationDate;
			}
			tempString = "";
		}
		if (tempChar == ';') {
			tempString = "";
		} 
		if (tempChar != '=' && tempChar != ';' && tempChar != " ") {
			tempString += tempChar;
		}
		count += 1;
	}	
	location.reload();
}

function Hash()
{
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
   
	this.removeItem = function(in_key)
	{
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}
	   
		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}

			this.items[in_key] = in_value;
		}
	   
		return in_value;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}
}
	
function popup(width,height,url,scrollbars)
{
	if (!(height < 1000 && height>100))
	{
		height=450;
	}
	if (!(width<2000&&width>150))
	{
		// Should fall to this condition if it's undefined
		// this catches a problem in IE where it doesn't understand
		// the value 'undefined'
		width=500;
	}
	namn = window.open(url,'blarf','toolbar=0,status=0,directories=0,scrollbars='+scrollbars+',resizable=yes,menubar=0,location=0,width='+width+',height='+height);
}


function createXMLRequest() {
	var xmlhttp=false;

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}

	if (!xmlhttp) {
		alert("Your browser version is not supported - please upgrade to at least Internet Explorer 5.5 or Netscape Navigator 7, Firefox 1.0 or Mozilla 1.0");
	}

	return xmlhttp;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
	};
	BrowserDetect.init();

