var map;
var geocoder;
var planttypes = [ "leaves", "needles", "palm", "cacti" ];
var plantLongNames = {leaves:"Trees with leaves", needles:"Trees with needles", palm:"Palm trees", cacti:"Cacti" };

function initWindow()
{
	initMap();
	changePlantButton("");
}

function initMap()
{
	if( GBrowserIsCompatible() )
	{
		map = new GMap2(document.getElementById("div_map") );
		//map.addControl( new GSmallMapControl() );
		//map.addControl( new GMapTypeControl() );
		map.addControl( new KidsiteMapMoveControl() );
		map.addControl( new KidsiteMapTypeControl() );
		map.setCenter( new GLatLng(37.5, -94.0), 4 );
	}
	else
	{
		var m = document.getElementById( 'div_map' );
		m.innerHTML = "<strong>Sorry, your web browser is not capable of displaying the map.</strong>";
	}
}

function addNewPoint()
{//alert('new');
	var zip = document.getElementById('zip').value;
	if( zip == '' )
	{
		alert( 'Please enter your zipcode.' );
		return;
	}
	if( ! /^\d{5}$/.test(zip) )
	{
		alert( 'Please enter a valid zipcode.' );
		return;
	}
	var lat = document.getElementById('lat').value;
	var lon = document.getElementById('lon').value;
	if( lat == '' || lon == '' )
	{
		alert( "We could not find the location of your zipcode so we can't put a new point on the map." );
		return;
	}
	var selectedBugs = {};
	var count = 0;
	for( var i=0; i< planttypes.length; ++i )
	{
		var pval = document.forms['plantChooser']["tf_" + planttypes[i]].value;
		if( (pval!='') && (!isNaN( pval )) && (pval >= 0) )
			++count;
	}
	if( count != planttypes.length )
	{
		alert( "please enter zero or a value for each plant type." );
		return;
	}
	
	Effect.ScrollTo( "step_three",{duration:0.75} );
	
	$('plantChooser').request( {
		onComplete: function( resp ) {
			//alert(resp.responseText);
			showPoints(resp.responseText, 1);
		}
	});
	
}

function doGeocode( zip )
{
	showLoc( '' );
	document.getElementById(['lat']).value = '';
	document.getElementById(['lon']).value = '';
	if( ! /^\d{5}$/.test(zip) )
	{
		return;
	}
	
	if( ! geocoder )
	{
		geocoder = new GClientGeocoder();
	}
	
	if( response = geocoder.getCache().get( zip ) )
	{
		var pmark = response.Placemark[0];
		processZip( pmark );
	}
	
	else
	{
		geocoder.getLocations(
			zip,
			function ( response )
			{//alert("status: " + response.Status.code );
				if( response.Status.code != 200 )
				{
					showLoc( "Unable to look up zipcode (error code: " + response.Status.code + ")" );
					return;
				}
				//alert( response.Placemark.length );
				//var alrt = '';
				//for( var i=0; i<response.Placemark.length; ++i )
				//{
				//	alrt += i + ": " + response.Placemark[i].AddressDetails.Country.CountryNameCode + "  ";
				//}
				//alert(alrt);
				var pmark = response.Placemark[0];
				processZip( pmark );
				geocoder.getCache().put( zip, response );
			}
		);
	}
}

function processZip( pmark )
{
	var lat = pmark.Point.coordinates[1];
	var lon = pmark.Point.coordinates[0];
	document.getElementById('lat').value = lat;
	document.getElementById('lon').value = lon;
	//alert(lat + ", " +lon);
	var loc = "";
	try
	{
		if( pmark.AddressDetails.Country )
		{
			var pcountry = pmark.AddressDetails.Country;
			var countryname = pcountry.CountryNameCode;
			loc = countryname + loc;
			if( pcountry.AdministrativeArea )
			{
				var parea = pcountry.AdministrativeArea
				var statename = parea.AdministrativeAreaName;
				loc = statename + ", " + loc;
				if( parea.SubAdministrativeArea.Locality )
				{
					var pcity = parea.SubAdministrativeArea.Locality
					var cityname = pcity.LocalityName;
					loc = cityname + ", " + loc;
				}
			}
		}
	}
	catch( ex )
	{
	//	alert( ex );	
	}
	finally
	{
		//alert(pcountry);
		if( loc == '' )
			loc = pmark.address;
		showLoc( loc );
	}
}

function showLoc( loc )
{
	document.getElementById('show_loc').innerHTML = loc;
}

function loadPoints( url )
{
	GDownloadUrl( url, function(data, responseCode)
	{
		showPoints(data);
	}
	);
}

function showPoints( data, centerOnLastPoint )
{
	// borrowed from google examples
	var baseIcon = new GIcon();
	baseIcon.image = "/kidsite/img/plants/dots/star.png";
	baseIcon.shadow = "/kidsite/img/plants/dots/star.png";
	baseIcon.iconSize = new GSize(23, 23);
	baseIcon.shadowSize = new GSize(0, 0);
	baseIcon.iconAnchor = new GPoint(11, 11);
	baseIcon.infoWindowAnchor = new GPoint(18, 4);
	
	var xml = GXml.parse(data);
	var markers = xml.documentElement.getElementsByTagName("point");
	for (var i = 0; i < markers.length; ++i)
	{
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                        		parseFloat(markers[i].getAttribute("lon")));

		var zip = markers[i].getAttribute('zip');
		var title = zip;
		var html = "ZIP code <b>" + zip + "</b><br/>"; //<table>\n<tr><th>" + bugtypes.join("</th><th>") + "</tr>\n";
		var isUser = ( markers[i].getAttribute("user") == 1 );
		var icon;
		// check child nodes for type to see if this is showing one type of plant or multiple types
		var childCount = 0;
		var thisType;
		for( var nt=0; nt < markers[i].childNodes.length; ++nt )
		{
			var plantCount;
			if( markers[i].childNodes[nt].nodeType == 1)
			{
				++childCount;
				thisType = markers[i].childNodes[nt].tagName;
				plantCount = parseInt( GXml.value(markers[i].childNodes[nt]) );
				var userPlantCount = parseInt( markers[i].childNodes[nt].getAttribute("user") );
				if( ! isNaN( userPlantCount ) )
					plantCount += userPlantCount;
			}
		}
		if( childCount == 1 )
		{
			// there's only one leaf type shown so change icon
			icon = new GIcon( baseIcon );
			var iconPrefix;
			switch( thisType )
			{
				case "leaves":
					iconPrefix = 'g';
					break;
				case "needles":
					iconPrefix = 'b';
					break;
				case "palm":
					iconPrefix = 'o';
					break;
				case "cacti":
					iconPrefix = 'y';
					break;
			}
			var iconNum = ( plantCount > 20 ) ? "lots" : plantCount;
			icon.image = "/kidsite/img/plants/dots/" +iconPrefix + iconNum + ".png";
			// with only 1 plant type we're not showing popups, so add info to the title
			title += ": " + plantCount + " " + plantLongNames[thisType];
		}
		else
		{
			icon = baseIcon;
			thisType = "all";
		}
		var markerOpts = { title: title, icon: icon };
		var counts = [];
		if( isUser )
			html += '<div class="popupLabel thisUser">You saw:</div><div class="popupInfo">';
		for( var j=0; j<planttypes.length; ++j )
		{
			var thisPlant = markers[i].getElementsByTagName(planttypes[j])[0];
			if( !thisPlant)
			{
				counts[j] = 0;
				continue;
			}
			else
			{
				var plantCount = GXml.value(thisPlant);
				counts[j] = plantCount;
			}
			if( isUser && thisPlant.getAttribute("user")>0 )
			{
				var userCount = thisPlant.getAttribute("user");
				html += '<div class="popupRow"><img src="/kidsite/img/plants/'+planttypes[j] + '.png" width="25px" height="25px"/> '+' '+ userCount + " " + plantLongNames[planttypes[j]] + "</div>";
			}
		}
		if( isUser )
		{
			html = html.substr(0, html.length-4);
			html += "</div>";
			//alert(html);
		}
		html += '<div class="popupLabel">Other people saw:</div><div class="popupInfo">';
		for( j=0; j<counts.length; ++j )
		{
			if( counts[j] > 0 )
				html += '<div class="popupRow"><img src="/kidsite/img/plants/'+planttypes[j] + '.png" width="25px" height="25px"/> '+ counts[j]+' '+plantLongNames[planttypes[j]]+'</div>';
		}
		html += '</div>';
		var marker = new GMarker(point, markerOpts);
		marker.html = html;
		//if( thisType == "all" )
		//{
			GEvent.addListener( marker, "click", function() {
				this.openInfoWindowHtml(this.html);
			});
		//}
		map.addOverlay(marker);
	}
	
	if( centerOnLastPoint )
	{
		map.setCenter( point );
		marker.openInfoWindowHtml(marker.html);
	}
}

function changeType(type)
{
	map.clearOverlays();
	var url = '/kidsite/plants/get_map_points/1/0/0';
	if( type != "all" )
		url = url + '/' + type;
	loadPoints(url);
	changePlantButton( type );
}

function changePlantButton( activetype )
{
	for( var p=0; p<planttypes.length; ++p )
	{
		var pt = planttypes[p];
		preparePlantButton( pt, ( pt == activetype ) );
	}
	preparePlantButton( "all", ( "all" == activetype ) );
}

function preparePlantButton(type, active)
{
	var btn = $( "btn_" + type );
	var type = btn.id.substr(4);
	if( active )
	{
		btn.onclick = '';
		btn.onmouseover = '';
		btn.onmouseout = '';
		btn.className = "tree_type_btn active";
		$("img_"+type).src = '/kidsite/img/plants/chooser_btns/' + type + '_o.gif';
	}
	else
	{
		btn.className = "tree_type_btn";
		$("img_"+type).src = '/kidsite/img/plants/chooser_btns/' + type + '.gif';
		
		btn.onclick = function ()
		{
			changeType( this.id.substr(4) );
		};
		btn.onmouseover = function ()
		{
			this.className = "tree_type_btn over";
			var type = this.id.substr(4);
			$("img_"+type).src = '/kidsite/img/plants/chooser_btns/' + type + '_o.gif';
		};
		btn.onmouseout = function ()
		{
			this.className = "tree_type_btn";
			var type = this.id.substr(4);
			$("img_"+type).src = '/kidsite/img/plants/chooser_btns/' + type + '.gif';
		};
	}
}

window.onload = initWindow;
window.onunload = GUnload;
