var map = null;

if (mapOn) {		
	var gSmallIcon = new GIcon();
	gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
	gSmallIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	gSmallIcon.iconSize = new GSize(12, 20);
	gSmallIcon.shadowSize = new GSize(14, 20);
	gSmallIcon.iconAnchor = new GPoint(6, 20);
	gSmallIcon.infoWindowAnchor = new GPoint(5, 1);
}

displayMode = function(mode, style, obj) {
	var elements = document.getElementsByTagName("li")
	for (x=0; x < elements.length; x++) {
		if (elements[x].className == "navEnd" || elements[x].className == "navItem")
			elements[x].style.backgroundColor = "";
	}
	
	if (style == '')
		style = "block";
	
	if (mode != "searchResults")
		obj.parentNode.style.backgroundColor = "#c1c689";

	var ids = ["searchResults", "weather", "news", "web", "city_html"];
	for (var x = 0; x < ids.length; x++) {
		if (mode==ids[x])
			$(mode).style.display = style;
		else
			$(ids[x]).style.display = "none";
	}
}

getMap = function() {
	geocoder = new GClientGeocoder();

	if (GBrowserIsCompatible()) {
		$("mapContainer").style.height = $("mapContainer").offsetWidth + "px";
		map = new GMap2($("mapContainer"));
		map.addControl(new GSmallMapControl());
		if (latitude.length > 0 && longitude.length > 0)
			map.setCenter(new GLatLng(latitude,longitude), 12);
	}
	
	var address = city + "," + state;
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point)
				alert(address + " not found");
			else {
	   	  		gLocalSearch = new GlocalSearch();
				gLocalSearch.setResultSetSize('large');
		   	  	gLocalSearch.setCenterPoint(map);
		    	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
			}
		}
	);
	
	$("searchButton").disabled = false
}

showAddress = function(address, icon, title, zoom, left, top) {
	if (!title || title == '')
		title=address;
	if (!zoom)
		zoom = 13;
	geocoder.getLatLng(
	    address,
    	function(point) {
			if (!point)
				alert(address + " not found");
			else {
	        	map.setCenter(point, zoom);
		        var marker = new GMarker(point, icon);
		        map.addOverlay(marker);
				marker.openInfoWindowHtml(title);
				GEvent.addListener(marker, "click", function() {
			        marker.openInfoWindowHtml(title);
				});
				map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.marginLeft = left + "px";
				map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.marginTop = top + "px";
    		}
  		}
	);
}

showMyTab = function(id, type) {
	$("hidden"+type+id).className = ($("hidden"+type+id).className == "moreInfo") ? "moreInfoHidden" : "moreInfo";
}

mapPanTo = function(lat, lon, id) {
	var myRegExp = /(directions|DIRECTIONS)<\/(div|DIV)><\/(a|A)>[\s\S]+/
	map.openInfoWindow(new GLatLng(lat, lon), this.innerHTML='<div align=\"left\">' +gLocalSearch.results[id].html.innerHTML.replace(myRegExp, "directions</div></a></div>").replace(/'/g, "\\\'") + '</div>');
}

// Our global state
var gLocalSearch;
var gCurrentResults = [];

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
OnLocalSearch = function() {
	if (!gLocalSearch.results) return;

	// Clear the map 
	for (var i = 0; i < gCurrentResults.length; i++)
		map.removeOverlay(gCurrentResults[i].marker());

    gCurrentResults = [];
    for (var i = 1; i < gLocalSearch.results.length; i++) 
    	gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));

	var htmlString = '<div class="searchHeader"><h4>Google Map Search Results:</h4></div><div class="searchLinks">';
	map.closeInfoWindow();
  	for (i=1; i<gLocalSearch.results.length; i++){
		htmlString += "<a href=\"javascript:mapPanTo(" + gLocalSearch.results[i].lat + "," + gLocalSearch.results[i].lng + ",'" + i + "')\">" + gLocalSearch.results[i].title + "</a><br />";
	}
	htmlString += '</div>';
	map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.marginLeft = "0px";
	map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.marginTop = "0px";	
	$("searchResults").innerHTML = htmlString;
}

// Cancel the form submission, executing an AJAX Search API search.
CaptureForm = function(form) {
	geocoder.getLatLng(
		city + ',' + state,
		function(point) {
			if (!point)
				alert(city + ',' + state + " not found");
			else 
				map.setCenter(point, 12);
		}
	)
	$("searchResults").style.display='none';
	displayMode('searchResults', '', $("searchResults"));
	$("searchResults").innerHTML = '<img src="/images/ajax-loader.gif" />';
   	gLocalSearch.execute(form["searchText"].value);
	return false;
}

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
LocalResult = function(result) {
	this.result_ = result;
	map.addOverlay(this.marker(gSmallIcon));
}

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function(opt_icon) {
	if (this.marker_) return this.marker_;
	var marker = new GMarker(new GLatLng(parseFloat(this.result_.lat),parseFloat(this.result_.lng)),opt_icon);
	GEvent.bind(marker, "click", this, function() {
    	marker.openInfoWindow(this.myHtml());})
	this.marker_ = marker;
	return marker;
}

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.myHtml = function() {
	var container = document.createElement("div");
	container.setAttribute("align", "left");
	var myRegExp = /(directions|DIRECTIONS)<\/(div|DIV)><\/(a|A)>[\s\S]+/
	this.result_.html.innerHTML = this.result_.html.innerHTML.replace(myRegExp, "directions</div></a></div>")
	container.appendChild(this.result_.html.cloneNode(true));
	return container;
}

$ = function(i) {return document.getElementById(i);}

OnLoad = function () {
	var searchControl = new GSearchControl();
	var options = new GsearcherOptions();
	
	options.setExpandMode(GSearchControl.EXPAND_MODE_CLOSED);
	searchControl.setResultSetSize(GSearch.LARGE_RESULTSET);
	searchControl.addSearcher(new GnewsSearch(), options);
	searchControl.addSearcher(new GwebSearch(), options);				

	searchControl.setSearchCompleteCallback(this, onSearchComplete);
	searchControl.draw($("search_control"));
		
	// execute an inital search
	searchControl.execute(city+","+state);
 }
	
setLinks = function() {
	var elements = document.getElementsByTagName("span")
	for (x=0; x < elements.length; x++) {
		if (elements[x].className == "spanLink") {
			elements[x].onmouseover = function() {this.className = "spanLinkHover";}
			elements[x].onmouseout = function() {this.className = "spanLink";}
		}
	}
	elements = document.getElementsByTagName("div")
	for (x=0; x < elements.length; x++) {
		if (elements[x].className == "crime") {
			elements[x].onmouseover = function() {this.style.backgroundColor="#dddddd"}
			elements[x].onmouseout = function() {this.style.backgroundColor=""}
		}
	}
}	
if (mapOn) {
	window.onload = function() {getMap(); OnLoad(); setLinks(); getWeather();}
	window.onunload= function() {GUnload();}
}

onSearchComplete = function(sc, searcher, x) {
	if (searcher.results && searcher.results.length > 0) {
		type = searcher.results[0].GsearchResultClass.replace(/(G|Search)/g, "")
		for (var i = 0; i < searcher.results.length; i++)
			$(type + "Links").innerHTML += searcher.results[i].html.innerHTML
	}
}

checkValue = function(obj) {
	if (obj.value.substr(0,1) == "<")
		obj.value='';
}

getWeather = function() {
	$("weatherData").innerHTML = "<img src='/images/ajax-loader.gif'/>";
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'ajaxLoader', 'communityrelocation.NOAAForecast', 'getWeather', latitude, longitude, loadWeather);
}

loadWeather = function(obj) {
	$("weatherData").innerHTML = obj;
}