
function toggleVideo(link) {
 element = document.getElementById('video');
 //element.style.display = "inline";
 if (link.innerHTML == 'Show Video') {
	 link.innerHTML = 'Hide Video';
	 element.style.display = "inline";
 } else {
	link.innerHTML = 'Show Video';
	element.style.display = "none";
 }
}

function toggleFlash(link, num) {
	 element = document.getElementById('video'+num);
	 //element.style.display = "inline";
	 if (link.innerHTML == 'Show 360° viewer ('+(num+1)+')') {
		 link.innerHTML = 'Hide 360° viewer';
		 element.style.display = "inline";
	 } else {
		link.innerHTML = 'Show 360° viewer ('+(num+1)+')';
		element.style.display = "none";
	 }
	}

// recent sales code

function showAllRecent() {
    jQuery('#sales-info table tr').show();
    jQuery('#sales-info table a').text('[Click to hide]');
}

function toggleSales(type, link) {
  //elements = document.getElementsByClassName(type + '_recent');
  //for (i = 0; i < elements.length; i++) {
  //	  jQuery(elements[i]).toggle();
  //}
  jQuery('.' + type + '_recent').each(function(){
  	jQuery(this).toggleClass('hideme');
  });

  if (link.innerHTML == '[Click to show]') {
    link.innerHTML = '[Click to hide]';
  } else {
    link.innerHTML = '[Click to show]';
  }
}

// rental map ajax below

// AJAX Hello World Demo http://www.hackorama.com/ajax

// Make a POST to the server
// and pass on any data from browser
// via the XMLHTTPRequest

var propertyType;
var main_property;
var nearby_properties = Array();
var showingAll = false;

function talktoServer(uniqueid, rental){
  if (rental) {
    propertyType = "rental";
  }
	var req = newXMLHttpRequest();
	//register the callback handler function
  	var callbackHandler = getReadyStateHandler(req, updateMsgOnBrowser);
  	req.onreadystatechange = callbackHandler;
  	req.open("GET", "/ajax/rentalmapgeo.php?rental="+rental+"&uniqueid="+uniqueid + "&rnd=" + Math.random(), true);
  	// req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  	req.send(null);
}

// This is the callback functions that gets called
// for the response from the server with the XML data

function updateMsgOnBrowser(testXML) {
	if( testXML.getElementsByTagName("latitude")[0] )
		var latitude = testXML.getElementsByTagName("latitude")[0].firstChild.nodeValue;
	if( testXML.getElementsByTagName("longitude")[0] )
		var longitude = testXML.getElementsByTagName("longitude")[0].firstChild.nodeValue;
	if( testXML.getElementsByTagName("htmlPreview")[0] )
		var html = testXML.getElementsByTagName("htmlPreview")[0];
	if( testXML.getElementsByTagName("address")[0] )
		var addresstext = testXML.getElementsByTagName("address")[0].firstChild.nodeValue;
	if( testXML.getElementsByTagName("propertyType")[0] )
		propertyType = testXML.getElementsByTagName("propertyType")[0].firstChild.nodeValue;

	var mapview = document.getElementById("mapview");
	var label = document.getElementById("label");

	if( latitude && longitude ){
		var map = viewMap(latitude, longitude, 15, true, html.firstChild.data);

		for (var i = 0; i < testXML.documentElement.childNodes.length; i++) {
			var node = testXML.documentElement.childNodes[i];
			if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === "entities") {
				for (var j = 0; j < node.childNodes.length; j++) {
					var entityNode = node.childNodes[j];
					if (entityNode.nodeType === Node.ELEMENT_NODE &&
							entityNode.nodeName === "entity") {
						var lt = entityNode.getAttribute("latitude");
						var ln = entityNode.getAttribute("longitude");
						var point = new google.maps.LatLng(parseFloat(lt), parseFloat(ln));
						var icon = new google.maps.Icon();
						icon.image = "/asset/img/map_icons/" + entityNode.getAttribute("icon");
						icon.iconSize = new google.maps.Size(30, 22);
						icon.iconAnchor = new google.maps.Point(16, 16);
						icon.infoWindowAnchor = new google.maps.Point(16, 16);
						var description = entityNode.getAttribute("name") +
									"<br/><br/>" + entityNode.getAttribute("address");
						addEntityMarker(map, point, icon, description);
					}
				}
			}
		}
	}
}



function addEntityMarker(map, point, icon, description)
{
	var marker = new google.maps.Marker(point, icon);
	google.maps.Event.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(description);
	});
	map.addOverlay(marker);
}



//the following two functions are helper infrastructure to
//create a XMLHTTPRequest and register a listner callback function

function newXMLHttpRequest() {
	var xmlreq = false;
	if (window.XMLHttpRequest) {
		xmlreq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
    		// Try ActiveX
		try {
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			// first method failed
			try {
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				 // both methods failed
			}
		}
 	}
   	return xmlreq;
}

function getReadyStateHandler(req, responseXmlHandler) {
	return function () {
	if (req.readyState == 4) {
		if (req.status == 200) {
        		responseXmlHandler(req.responseXML);
		} else {
			var hellomsg = document.getElementById("mapview");
			hellomsg.innerHTML = "ERROR: "+ req.status;
      		}
    	}
 	}
}

function createMarker(point, html, map){
			var icon = new google.maps.Icon();
			icon.image = "/asset/img/houseicon.png";
			icon.iconSize = new google.maps.Size(48, 48);
			icon.iconAnchor = new google.maps.Point(24, 24);
			icon.infoWindowAnchor = new google.maps.Point(24, 24);
			
			var marker = new google.maps.Marker(point,icon);
			map.addOverlay(marker);
			google.maps.Event.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(html); //,{'maxWidth':'300px'}
			});
			return marker;
		}

function viewMap(lat, longit, zoom, marker, address){
			var map = new google.maps.Map2(document.getElementById('mapview'));
			map.addControl(new google.maps.SmallMapControl());
			map.setCenter(new google.maps.LatLng(lat,longit), zoom);

			if( marker == true ){
				main_property = createMarker(
					new google.maps.LatLng(lat,longit),
					address,
					map
				);
			}
      document.map = map;
      google.maps.Event.addListener(document.map, "moveend", mapMoveEnd);
	return map;
}

function toProperCase(s){
	return s.toLowerCase().replace(/^(.)|\s(.)/g,
		  function($1) { return $1.toUpperCase(); });
}

function fetchPropertiesInView(){
  var button = document.getElementById("ShowHide");
  button.onclick = hidePropertiesInView;
  button.innerHTML = "Hide other properties";

  showingAll = true;


  var map = document.map;
	var req = newXMLHttpRequest();
	//register the callback handler function
  	var callbackHandler = getReadyStateHandler(req, showAllProperties);
  	req.onreadystatechange = callbackHandler;
    var lat1, lat2, lng1, lng2;
    var bounds = map.getBounds();
    lat1 = bounds.getNorthEast().lat();
    lat2 = bounds.getSouthWest().lat();
    lng1 = bounds.getNorthEast().lng();
    lng2 = bounds.getSouthWest().lng();
    var params = "";
    params += "lat1=" + lat1;
    params += "&lat2=" + lat2;
    params += "&lng1=" + lng1;
    params += "&lng2=" + lng2;
    params += "&type=" + propertyType;
  	req.open("GET", "/ajax/rentalmapview.php?"+params + "&rnd=" + Math.random(), true);
  	// req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  	req.send(null);
}
function hidePropertiesInView() {
  var map = document.map;
  var button = document.getElementById("ShowHide");
  button.onclick = fetchPropertiesInView;
  button.innerHTML = "Show other properties in this area";

  showingAll = false;

  removeNearby();
  map.addOverlay(main_property);

}
function removeNearby() {
  for (i = 0; i < nearby_properties.length; ++i) {
    document.map.removeOverlay(nearby_properties[i]);
  }
  nearby_properties = null;
  nearby_properties = Array();
}

function showAllProperties(xml) {
  var map = document.map;
  var properties;
  if (propertyType == "rental") {
    properties = xml.getElementsByTagName("rental");
  } else {
    properties = xml.getElementsByTagName("property");
  }
  removeNearby();
  for (i = 0; i < properties.length; ++i) {
    var property = properties[i];
    nearby_properties[nearby_properties.length] =
    showProperty(property);
  }
  map.removeOverlay(main_property);
}

function showProperty(property) {
  var lat = property.getElementsByTagName("latitude");
  var longit = property.getElementsByTagName("longitude");
  var html = property.getElementsByTagName("htmlPreview");
  return createMarker(
      new google.maps.LatLng(lat[0].firstChild.nodeValue,longit[0].firstChild.nodeValue),
      html[0].firstChild.nodeValue,
      document.map
      );
}

function mapMoveEnd() {
  if (showingAll) {
    fetchPropertiesInView();
  }
}
