/* 
 * Playground Scripts
 * supporting functions for playgrounds.eagletribune.com
 * Some original code provided by The Blackpool Community Church Javascript Team
 * http://www.econym.demon.co.uk/googlemaps/
 * Modified by Chris Wible  / Matt Ouellette for Eagle-Tribune Publishing Company
 * May 2007
 */

/*
 * Do Search
 * gets value of search field and calls new feed
 */

function doSearch() {
	var val = document.getElementById('search').value;
	var res = document.getElementById('results_for');
	res.innerHTML = val;
	newFeed('','',val,'','','');
	return false;
}

/*
 * My House
 * explodes address form input and calls newFeed()
 * in two different ways, depending on whether the user
 * specified city, state or zipcode
 */

function myHouse() {
	var form = document.forms['myhouse'];
	var address = form.address.value;
	var citystate = form.citystate.value;
	var city = citystate.split(',')[0];
	var state = citystate.split(',')[1];
	var nozip = citystate.indexOf(',');
	var range = form.miles.value;
	if (address && city && state && nozip > 0) {
		newFeed(city,state,'',address,range,'');
		}else{
		newFeed('','','',address,range,citystate);
	}
	return false;
}

/* 
 * New Feed
 * accepts variety of paremeters and decides how to call for the next feed
 */
function newFeed(city,state,search,address,range,zip) {

	request = GXmlHttp.create();
	map.getInfoWindow().hide();
	map.clearOverlays();
	// empty the array
	markers = [];
	
	var res = document.getElementById('results_for');
	var filename = 'all.xml';
	
	if (city && !state && !range) {
		var filename = "google.xml?city="+city;
		res.innerHTML = city;
	}
	if (city && state && !range) {
		var filename = "google.xml?city="+city+"&state="+state;
		res.innerHTML = city;
	}
	if (search && !range) {
		var filename = "google.xml?search="+search;
		res.innerHTML = search;
	}
	if (address && range && city && state) {
		var filename = "google.xml?startaddress="+address+","+city+","+state+"&range="+range;
		res.innerHTML = "";
	}
	if (address && range && zip) {
		var filename = "google.xml?startaddress="+address+","+zip+"&range="+range;
		res.innerHTML = "";
	}
	request.open("GET", filename, true);
	request.onreadystatechange = processTabbedXML;
	request.send(null);
}


/*
 * Center and Zoom On Bounds
 * extend GMap to have center function
 * as processTabbedXML processes markers they are added to 'bounds'
 * this finds the corners and calculates the best view to contain all markers
 */
GMap.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;
   var center = new GLatLng(center_lat,center_lng)
   map.setCenter(center, map.getBoundsZoomLevel(bounds));
}

/*
 * Process Tabbed XML
 * parses repsonse XML in Google-friendly way
 * creates new markers for each marker in feed, etc
 * also checks for myhouse in feed
 */
function processTabbedXML() {
	startdate = new Date();
	starttime = startdate.getTime();
	
	toggleSpinner('show',0); // display loading spinner

	var bounds = new GLatLngBounds();
	
	if (request.readyState == 4) {
		if ((request.status != 200) && (request.status != 304)) {
			alert("file not found: "+filename);
			return;
		}
	
	var xmlDoc = GXml.parse(request.responseText);
	
	// obtain the array of markers
	var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	
	// sidebar html is provided by the feed
	var sidebar = xmlDoc.documentElement.getElementsByTagName("sidebar")[0];
	document.getElementById("sidebar").innerHTML = GXml.value(sidebar);;

	// clear any previous overlays prior to displaying new set
	for (var i=0; i < gmarkers.length; i++) {
		map.removeOverlay(gmarkers[i]);
	}

	gmarkers = new Array();
	
	for (var i = 0; i < markers.length; i++) {
		// obtain the attributes of each marker
		var lat = parseFloat(markers[i].getAttribute("lat"));
		var lng = parseFloat(markers[i].getAttribute("lng"));
		var label = markers[i].getAttribute("label");
		var icon;
		var info = GXml.value(markers[i].getElementsByTagName("moreinfo")[0]);
		
		// if we receive a bad point say so
		if (isNaN(lat) || isNaN(lng)) {
			alert("bad point "+i);
			continue;
		}
		var point = new GLatLng(lat,lng);
		// get the tab info
		tabInfo = markers[i].getElementsByTagName("tab");
		var tabs = new Array();
		
		if (tabInfo.length > 0) {
			for (var j = 0; j < tabInfo.length; j++) {
				var tabLabel = GXml.value(tabInfo[j].getElementsByTagName("label")[0]);
				var tabHtml = GXml.value(tabInfo[j].getElementsByTagName("contents")[0]);
				if ((j==0) && (tabInfo.length > 2)) { 
					// adjust the width so that the info window is large enough for this many tabs
					tabHtml = '<div style="width:'+tabInfo.length*88+'px">' + tabHtml + '</div>';
				}
				tabs.push(new GInfoWindowTab(tabLabel,tabHtml));
			}
		} else { 
			var tabLabel = "Nothing";
			var tabHtml = markers[i].getAttribute("html");
			tabs.push(new GInfoWindowTab(tabLabel,tabHtml));
		}      
		if (!markers[i].getAttribute("nodirections") || (markers[i].getAttribute("nodirections").toLowerCase() == "no")) {
			// add directions tab
			var tabLabel = "Directions";
			var tabHtml = '<div style="width:250px">'+'<h3>' + label + '</h3>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a></div>';
			tabs.push(new GInfoWindowTab(tabLabel,tabHtml));
		}
		// create the marker
		var marker = createMarker(point,label,tabs,icon,info);
		bounds.extend(point);
		map.addOverlay(marker);
	}
	
	// if user has specified an address (myhouse) process that marker
	// if user has specified their location, get that info

	var myhouse = xmlDoc.documentElement.getElementsByTagName("myhouse");

	if(myhouse.length > 0) {
		var zip = xmlDoc.documentElement.getElementsByTagName("myhouse")[0].getElementsByTagName("zip")[0];
		var zipvalue = GXml.value(zip);
		var address = xmlDoc.documentElement.getElementsByTagName("myhouse")[0].getElementsByTagName("street_address")[0];
		var addressvalue = GXml.value(address);
		var lat = xmlDoc.documentElement.getElementsByTagName("myhouse")[0].getElementsByTagName("lat")[0];
		var latvalue = GXml.value(lat);
		var lng = xmlDoc.documentElement.getElementsByTagName("myhouse")[0].getElementsByTagName("lng")[0];
		var lngvalue = GXml.value(lng);
		if (zipvalue != '' && zipvalue != null) {
				setCookie('zipcode',zipvalue,30);
		}
		if (addressvalue != '' && addressvalue != null) {
				setCookie('address',addressvalue,30);
		}
		res = document.getElementById('results_for');
		res.innerHTML = '';
		var houseIcon = new GIcon();
				houseIcon.iconSize=new GSize(32,32);
				houseIcon.shadowSize=new GSize(56,32);
				houseIcon.iconAnchor=new GPoint(16,32);
				houseIcon.infoWindowAnchor=new GPoint(16,0);
		var house = new GIcon(houseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon48.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon48s.png");
		
		var point = new GLatLng(latvalue,lngvalue);
		var marker = createMarker(point,'','','house','');
		bounds.extend(point);
		gmarkers.push(marker) ; 
		map.addOverlay(marker);
	}

	// center the map to view all present markers
	map.centerAndZoomOnBounds(bounds);

	// update our time and toggle the spinner
	enddate = new Date();
	endtime = enddate.getTime();
	difference = endtime - starttime;
	toggleSpinner('hide', difference);
	} // end if readyState == 4
} // end processTabbedXML()

/*
 * Create Marker
 * Create a marker and set up the event window
 * Accepts a variable number of tabs, passed in the arrays htmls[] and labels[]
 * also displays 'myhouse' icon
 */
function createMarker(point,label,tabs,icon,info) {
	var marker;
	if (icon == 'house') {
      var houseIcon = new GIcon();
          houseIcon.iconSize=new GSize(32,32);
          houseIcon.shadowSize=new GSize(56,32);
          houseIcon.iconAnchor=new GPoint(16,32);
          houseIcon.infoWindowAnchor=new GPoint(16,0);
      var house = new GIcon(houseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon48.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon48s.png");
		 marker = new GMarker(point,house);
	} else {
		 marker = new GMarker(point);
	}
	var marker_num = gmarkers.length;
	marker.name = label;
	marker.marker_num = marker_num;
	marker.tabs = tabs;
	marker.more_info = info;
	gmarkers[marker_num] = marker;
	
	if (icon != 'house') {
		GEvent.addListener(gmarkers[marker_num], "click", function() {
			displayMoreInfo(marker.more_info);
			marker.openInfoWindowTabsHtml(gmarkers[marker_num].tabs);
		});
	}
	return marker;
}

/*
 * Trigger markers
 * called from links in sidebar - opens infowindow on corresponding marker
 * more functions can be attached here
 * renaming this function would make me smile
 */
function myclick(i) {
	 GEvent.trigger(gmarkers[i], "click");
}

/*
 * Directions tab functions
 * functions that open the directions forms
 */
function tohere(i) {
	var tabLabel = 'Directions';
	var numTabs = gmarkers[i].tabs.length;
	var name = gmarkers[i].name;
	var divWidth = numTabs * 88;
	if (numTabs < 3) divWidth = 3*88;
	// The info window version with the "to here" form open
	var tabHtml = '<div style="width:'+divWidth+'px">'+
		 'Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
		 '<br />Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
		 '<input type="text" size="40" maxlength="40" name="saddr" id="saddr" value="" /><br />' +
		 '<input value="Get Directions" type="submit"/>' +
		 '<input type="hidden" name="daddr" value="' + gmarkers[i].getPoint().lat() + ',' + gmarkers[i].getPoint().lng() + '(' + name + ')' +
						// "(" + name + ")" + 
		 '"/></div>';
	gmarkers[i].tabs[numTabs-1]= new GInfoWindowTab(tabLabel,tabHtml);
	gmarkers[i].openInfoWindowTabsHtml(gmarkers[i].tabs,{selectedTab:numTabs-1});
	populateDirectionsAddress('saddr');
}

function fromhere(i) {
	var name = gmarkers[i].name;
	var tabLabel = 'Directions';
	var numTabs = gmarkers[i].tabs.length;
	var divWidth = numTabs * 88;
	if (numTabs < 3) divWidth = 3*88;
	// The info window version with the "from here" form open
	var tabHtml = '<div style="width:'+divWidth+'px">'+
		 'Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
		 '<br />End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
		 '<input type="text" size="40" maxlength="40" name="daddr" id="daddr" value="" /><br />' +
		 '<input value="Get Directions" type="submit"/>' +
		 '<input type="hidden" name="saddr" value="' + gmarkers[i].getPoint().lat() + ',' + gmarkers[i].getPoint().lng() + '(' + name + ')' +
						// "(" + name + ")" + 
		 '"/></div>';
	gmarkers[i].tabs[numTabs-1]= new GInfoWindowTab(tabLabel,tabHtml);
	gmarkers[i].openInfoWindowTabsHtml(gmarkers[i].tabs,{selectedTab:numTabs-1});
	populateDirectionsAddress('daddr');
}

/* 
 * Populate Directions Address
 * when displaying an info window, check to see if the user has filled out the 
 * form and prepopulate the address field for them
 */
function populateDirectionsAddress(field) {
	var ad = document.getElementById('address').value;
	var ci = document.getElementById('citystate').value;
	if (ad != 'Address' && ci != 'City, State or Zipcode') {
		var fi = document.getElementById(field);
		var address = ad + ', ' + ci;
		fi.value = address;
	}
}

/* 
 * Display More Info
 * receives text to display from marker onclick
 * and populates the moreinfo area at bottom of page
 */
function displayMoreInfo(display) {
	var moreinfo = document.getElementById('moreinfo');
	if (moreinfo.style.display != 'block') {
		moreinfo.style.display = 'block';
	}
	moreinfo.innerHTML = display;
}

/* 
 * Toggle Spinner
 * called at beginning and end of processTabbedXML
 * first time, show the spinner graphic
 * second time, receive the time it took to process the xml
 * if processing time was less than minDisplayTime set timer to 
 * difference and hide spinner at end
 * otherwise, just hide on second call
 */
function toggleSpinner(action,time) {
	var spin = document.getElementById('spinner');
	var minDisplayTime = 1000;
	
	if (action == 'show') {
		spin.style.display = 'block';
	}else{
		if(time > minDisplayTime || time == 'stop') {
			spin.style.display = 'none';
		}else{
			var remainder = minDisplayTime - time;
			setTimeout("toggleSpinner('hide','stop')",remainder)
		}
	}		
}

/*
 * Cookie functions
 * when user fills out address field we get back a mytown node in the xml
 * that uses setCookie() to write zip and address cookies
 * if user returns, getCookie() prepopulates the address form
 * and sends the zip code to Omniture
 */
function setCookie(c_name,value,expiredays) {
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
function getCookie(c_name) {
	if (document.cookie.length>0)
		{
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
			{ 
			c_start=c_start + c_name.length+1 
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
			} 
		}
	return ""
}
function checkCookie() {
	var zip = getCookie('zipcode');
	var address = getCookie('address');
	if (zip!=null && zip!="") {
  	var zipfield = document.getElementById('citystate');
  	zipfield.value = zip;
  }
  if (address!=null && address!='') {
    var addressfield = document.getElementById('address');
  	addressfield.value = address;
  }
}

/* 
 * Ajax functions
 * When page loads, request a list of cities from database
 * and populate the cities div on the page
 */

function displayCities(response) {
	var cities = document.getElementById('towns');
	cities.innerHTML = response;
}
function xmlhttpPost(action) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', action, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            if(action == 'city_list') {
            	displayCities(self.xmlHttpReq.responseText);
            }
        }
    }
    self.xmlHttpReq.send();
    return false; //return false forces form not to submit onsubmit
}

