//<![CDATA[

var defaultLatitude = 36.77;
var defaultLongitude = -119.72;
var defaultZoomLevel = 11;
var defaultMapElement = "openHomesMap";
var defaultListElement = "openHomesListUL";
var markerData = "http://www.fresnobee.com/static/openhomes/data.xml";
var dateData = "http://www.fresnobee.com/static/openhomes/dates.xml";
var photoAvatar = "http://www.fresnobee.com/static/images/icons/photos.gif";
var fromDateDiv = "fromDate";
var toDateDiv = "toDate";
var addressDisplay = "";
var markers = new Array;
var maxLat = -90;
var minLat = 90;
var maxLng = -180;
var minLng = 180;
var map;

function doOpenHomes() {

	if (GBrowserIsCompatible()) {
	
		// set the dates 
		setDates();

		// build the markers aray 
		buildMapArray();
				
		// build the bounding box for the zoom scope
		var northEast = new GLatLng(maxLat, maxLng);
		var southWest = new GLatLng(minLat, minLng);
		var bounds = new GLatLngBounds(southWest, northEast);
		
		// set page status to "loading" ... remove when complete
	
		// create the map
		map = new GMap2(document.getElementById(defaultMapElement));
		map.addControl(new GSmallMapControl());
		
		// use protoype function to to center and zoom
		map.centerAndZoomOnBounds(bounds);

		// add markers to the map and to the list
		for (m = 0 ; m < markers.length ; m++) {
		
			// add an event to the GMarker
			GEvent.addListener(markers[m].marker, "click", toggleInfoWindow);
		
			// add the marker to the map			
			map.addOverlay(markers[m].marker);

			createListLink(m);
			
		}
	
			
	} else {
	
		alert("Your browser is not compatible with Google Maps");		
	
	}
	
}

function buildMapArray() {

	// create the XHR object and get the XML document
	var xhr = new XMLHttpRequest();
	xhr.open("GET", markerData, false);
	xhr.send('');
	
	// remove whitespace so that you can use it in both IE and FF
	removeWhiteSpaceDOM(xhr.responseXML.documentElement, true);
	
	// get the markers out
	var tmpMarkers = xhr.responseXML.documentElement.getElementsByTagName("marker");
	
	// cycle thru the XML data and do the following
	// - assign an id to the marker
	// - create an object that contains the GMarker as well as the DOM element 
	//   it represents
	// - push it into the markers array
	
	for (var l = 0; l < tmpMarkers.length ; l++) {
	
		var tmpObject = new Object;
	
		// set the id to the DOM Element
		tmpMarkers[l].setAttribute('id', l);
		
		// create the GMaps point and marker objects
		var lat = parseFloat(tmpMarkers[l].getAttribute('lat'));
		var lng = parseFloat(tmpMarkers[l].getAttribute('lng'));
		var point = new GLatLng(lat, lng);
		var marker = new GMarker(point);
		
		// set the id to the marker as well.  That way, when we pass the marker
		// to the toggleInfoWindow function, we can pull the DOM element from
		// the array
		marker.id = l;
		
		// assign the point, marker and DOM Element to the object
		tmpObject.point = point;
		tmpObject.marker = marker;
		tmpObject.DOMElement = tmpMarkers[l];
		
		// push the object into the markers array
		markers[l] = tmpObject;
			
		// find min/max lat/lng
		maxLat = (lat > maxLat ? lat : maxLat);
		minLat = (lat < minLat ? lat : minLat);			
		maxLng = (lng > maxLng ? lng : maxLng);
		minLng = (lng < minLng ? lng : minLng);		
			
	}


}

function setDates() {

	// create the XHR object and get the XML document
	var xhr = new XMLHttpRequest();
	xhr.open("GET", dateData, false);
	xhr.send('');
	
	// remove whitespace so that you can use it in both IE and FF
	removeWhiteSpaceDOM(xhr.responseXML.documentElement, true);

	// get the one element
	var dateInfo = xhr.responseXML.documentElement.getElementsByTagName("date");
	
	var fromDate = dateInfo[0].getAttribute("from-date");
	var toDate = dateInfo[0].getAttribute("to-date");
	
	document.getElementById(fromDateDiv).innerHTML = fromDate;
	document.getElementById(toDateDiv).innerHTML = toDate;
	
}

function toggleInfoWindow(id) {

	if (!markers[id]) {
		id = this.id
	}
	
	
	// if this has an image, make it a tabbed window
	if (markers[id].DOMElement.getAttribute('img')) {
		
		var infoWindowTabs = [
			new GInfoWindowTab("Information", createInfoWindowHTML(id)),
			new GInfoWindowTab("Photo", createInfoWindowPhotoHTML(id))
		];
		
		markers[id].marker.openInfoWindowTabsHtml(infoWindowTabs);
		
	} else {
	
		// just open an info window with no tabs
		markers[id].marker.openInfoWindowHtml(createInfoWindowHTML(id));

	}
	
	map.setCenter(markers[id].point, 16);
	
	// swap out the text in the information and directions box
	toggleInformationDirectionsBoxes(id);
	
}

function createListLink(id) {

	if (!markers[id]) {
		return false;
	}
	
	// get the list element
	var list = document.getElementById(defaultListElement);
		
	var address = markers[id].DOMElement.getAttribute('address');
	var city = markers[id].DOMElement.getAttribute('city');
	
	// create the DOM elements for the
	var li = document.createElement("li");
	var a = document.createElement("a");
	a.setAttribute("href", "javascript:toggleInfoWindow('" + id + "');");
	var aText = document.createTextNode(address + ', ' + city);

	a.appendChild(aText);
	li.appendChild(a);

	// see if there are photos
	if (markers[id].DOMElement.getAttribute('img')) {
	
		var img = document.createElement("img");
		img.setAttribute("src", photoAvatar);
		li.appendChild(img);
	
	}

	list.appendChild(li);
	
}

function createInfoWindowHTML(id) {
	
	if (!markers[id]) {
		return false;
	}
	
	var tmpElement = markers[id].DOMElement;
	
	var HTML = "<div class='GmapsInfoWindow'><b>";
	HTML += tmpElement.getAttribute('address') + "</b><br>";
	HTML += tmpElement.getAttribute('city') + ', CA ';
	HTML += tmpElement.getAttribute('zip') + "<br>" 
	HTML += tmpElement.getAttribute('price') + "<br><br>";
	HTML += tmpElement.getAttribute('description');
	HTML += "</div>";

	return HTML;
	 

}

function createInfoWindowPhotoHTML(id) {

	if (!markers[id]) {
		return false;
	}
	
	var tmpElement = markers[id].DOMElement;

	var HTML = "<div class='GmapsInfoWindow'><img src='";
	HTML += tmpElement.getAttribute('img') + "'>";
	HTML += "</div>";

	return HTML;

}

function toggleInformationDirectionsBoxes(id) {

	if (!id) {
		return false;
	}
	
	var tmpElement = markers[id].DOMElement;
	var infoDiv = document.getElementById('homeDetailDiv');
	var directionsDiv = document.getElementById('directionsDiv');
	
	// do the information box
	var infoHTML = "";
	infoHTML += "<b>Address:</b><br/>" + tmpElement.getAttribute('address') + 
		"<br/>";
	infoHTML += tmpElement.getAttribute("city") + ", CA " + 
		tmpElement.getAttribute("zip") + "<br/><br/>";
	
	if (!/\S*/.test(tmpElement.getAttribute('price')) || 
		tmpElement.getAttribute('price')) {
		
		infoHTML += "<b>Price:</b> " + tmpElement.getAttribute('price') + 
			"<br/>";
		
	} 

	if (!/\S*/.test(tmpElement.getAttribute('beds')) || 
		tmpElement.getAttribute('beds')) {
		
		infoHTML += "<b>Bedrooms:</b> " + tmpElement.getAttribute('beds') + 
			"<br/>";
		
	} 
	
	if (!/\S*/.test(tmpElement.getAttribute('baths')) || 
		tmpElement.getAttribute('baths')) {
		
		infoHTML += "<b>Bathrooms:</b> " + tmpElement.getAttribute('baths') + 
			"<br/>";
		
	} 
	
	if (!/\S*/.test(tmpElement.getAttribute('realtor')) || 
		tmpElement.getAttribute('realtor')) {
		
		infoHTML += "<b>Realtor:</b> " + tmpElement.getAttribute('realtor') + 
			"<br/>";
		
	} 

	if (!/\S*/.test(tmpElement.getAttribute('realtor-phone')) || 
		tmpElement.getAttribute('realtor-phone')) {
		
		infoHTML += "<b>Realtor Phone:</b> " + 
			tmpElement.getAttribute('realtor-phone') + "<br/>";
		
	} 
	
	if (!/\S*/.test(tmpElement.getAttribute('realtor-web')) || 
		tmpElement.getAttribute('realtor-web')) {
		
		infoHTML += "<a href='" + tmpElement.getAttribute('realtor-web') + 
			"'>" + tmpElement.getAttribute('realtor-web') + "</a>";
		
	} 
	
	infoDiv.innerHTML = infoHTML;	
	
	// do the directions box
	
	directionsHTML = "<b>From:</b><br/>";
	directionsHTML += "Address: <input type='text' id='mp_address' value=''><br/>";
	directionsHTML += "City: <input type='text' id='mp_city' value='' size='10'><br/>";
	directionsHTML += "State: <input type='text' id='mp_state' value='' size='2'><br/>";
	directionsHTML += "Zip: <input type='text' id='mp_zip' value='' size='7'><br/><br/>";
	
	directionsHTML += "<b>To:</b><br/>";
	directionsHTML += tmpElement.getAttribute('address') + 
		"<br/>";
	directionsHTML += tmpElement.getAttribute("city") + ", CA " + 
		tmpElement.getAttribute("zip");	
	
	directionsHTML += '<form action="http://maps.google.com/maps" method="get" name="directions_form" id="directions_form">';
	directionsHTML += '<input type="hidden" name="saddr" id="saddr">';
	directionsHTML += '<input type="hidden" name="daddr" id="daddr">';
	directionsHTML += '<input type="hidden" name="hl" value="en" />';
	directionsHTML += '<input type="button" id="go-button" name="go" value="Get Driving Directions" onClick="findDirections(' + id + ');">';
	directionsHTML += '</form>';
	
	directionsDiv.innerHTML = directionsHTML;
	
}


function findDirections(id) {

	if (!markers[id]) {
		return false;
	}
	
	if (!id) {
		return false;
	}

	var tmpElement = markers[id].DOMElement;
	var regex = /^\s*$/g;
	var error_string = "The following errors occured: \n";
	var error = 0;
	var fields = new Array();
	
	fields["mp_address"] = "'To' Address";
	fields["mp_city"] = "'To' City";
	fields["mp_zip"] = "'To' Zip";
	
	for (var key in fields) {
	
		if (!document.getElementById(key).value || regex.test(document.getElementById(key).value)) {
		
			error_string += fields[key] + " must be filled in. \n";
			error = 1;
			
		}
		
	}
	
	if (error) {
	
		alert(error_string);
		return false;
		
	} else { 
	
		document.getElementById('daddr').value = 
			tmpElement.getAttribute('address') + ", " +
			tmpElement.getAttribute('city') + ", CA " +
			tmpElement.getAttribute('zip'); 
		
		document.getElementById('saddr').value = 
		document.getElementById('mp_address').value + ", " +
		document.getElementById('mp_city').value + ", CA " + 
		document.getElementById('mp_zip').value;      			
		
		document.getElementById('directions_form').submit();
	
	}

}


// prototype function for centering and zooming 
GMap2.prototype.centerAndZoomOnBounds = function(bounds) {

	var center_lat = (bounds.getNorthEast().lat() + 
		bounds.getSouthWest().lat()) / 2.0;

	var center_lng = (bounds.getNorthEast().lng() +
		bounds.getSouthWest().lng()) / 2.0;
	
	if(bounds.getNorthEast().lng() < bounds.getSouthWest().lng()) {
		center_lng += 180;
	}

	var center = new GLatLng(center_lat,center_lng)
	map.setCenter(center, map.getBoundsZoomLevel(bounds));

}

//]]>