var map;
var geocoder;

function initWindow()
{
	initMap();
	Input.initialize();
	//changeButton('');
	changeType();
}

function initMap()
{
	if( GBrowserIsCompatible() )
	{
		map = new GMap2( document.getElementById("div_map") );
		//map.addControl( new GSmallMapControl() );
		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()
{
	var zip = document.getElementById('zip').value;
	if( zip == '' )
	{
		alert( 'Please enter your zipcode.' );
		return;
	}
	if( ! /^\d{5}$/.test(zip) )
	{
		alert( 'Please enter your 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< bugtypes.length; ++i )
	{
		var radios = document.forms['bugChooser']["radio_" + bugtypes[i]];
		for( var j=0; j<radios.length; ++j )
		{
			if( radios[j].checked )
			{
				selectedBugs[bugtypes[i]] = radios[j].value;
				++count;
				break;
			}
		}
	}
	if( count != bugtypes.length )
	{
		alert( "please click yes or no for each kind of bug" );
		return;
	}
	
	// first change display to load current season's points
	// SEASONS HAVE BEEN REMOVED AND POINTS ARE LOADED WHEN PAGE LOADS
	// changeType(current_season);
	
	//$("step_three").scrollTo();
	Effect.ScrollTo( "step_three",{duration:0.75} );
	
	// then submit and overlay new point
	$('bugChooser').request( {
		onComplete: function( resp ) {
			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 )
			{
				if( response.Status.code != 200 )
				{
					showLoc( "Unable to look up zipcode (error code: " + response.Status.code + ")" );
					return;
				}
				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;
	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 )
	{
	}
	finally
	{
		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, false );
	}
	);
}

function showPoints( data, isNewPoint )
{
	var imgPath = "/kidsite/img/bugs"; // for bug icon images inside popups
	
	// icons borrowed from google examples
	var baseIcon = new GIcon();
	//baseIcon.image = "http://labs.google.com/ridefinder/images/mm_20_purple.png";
	baseIcon.image = "http://maps.google.com/mapfiles/ms/micons/red-pushpin.png";
	//baseIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	baseIcon.shadow = "http://maps.google.com/mapfiles/ms/micons/pushpin_shadow.png";
	//baseIcon.iconSize = new GSize(12, 20);
	baseIcon.iconSize = new GSize(32, 32);
	//baseIcon.shadowSize = new GSize(22, 20);
	baseIcon.shadowSize = new GSize(59, 32);
	//baseIcon.iconAnchor = new GPoint(6, 20);
	baseIcon.iconAnchor = new GPoint(8, 32);
	//baseIcon.infoWindowAnchor = new GPoint(5, 1);
	baseIcon.infoWindowAnchor = new GPoint( 20,5 );
	
	var blueIcon = new GIcon( baseIcon );
	//blueIcon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
	blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/blue-pushpin.png";
	
	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].getElementsByTagName('zip')[0].childNodes[0].nodeValue;
		var title = zip;
		var html = "ZIP code <b>" + zip + "</b><br/>";
		var isUser = ( markers[i].getAttribute("user") == 1 );
		
		var icon;
		// use big icon if this is a newly added point, else use small icons
		if( isNewPoint )
			icon = blueIcon;
		//	icon = G_DEFAULT_ICON;
		else // red icon for general points, blue icon if current user has data associated with this point
			icon = isUser ? blueIcon : baseIcon;
		
		var markerOpts = { title: title, icon: icon };
		var allHTML = '';
		var userHTML = '';
		var usercount = 0;
		var othercount = 0;
		for( var j=0; j<bugtypes.length; ++j )
		{
			var thisBug = markers[i].getElementsByTagName(bugtypes[j])[0];
			var bugcount = thisBug.childNodes[0].nodeValue;
			//html += bugtypes[j] + ": " + bugcount + "<br/>";
			if( bugcount > 0 )
			{
				imgsuffix = "";
				altxtra = " found";
				++othercount;
			}
			else
			{
				altxtra = " not found";
				imgsuffix = "_ghost";
			}
			allHTML += '<img src="' + imgPath + '/' + bugtypes[j] + imgsuffix + '.png" alt="' + bugtypes[j] + altxtra + '" title="' + bugtypes[j] + altxtra + '" width="24px" height="24px"/>';
			if( isUser )
			{
				if ( thisBug.getAttribute("user") == 1 )
				{
					imgsuffix = "";
					altxtra = " found";
					++usercount;
				}
				else
				{
					altxtra = " not found";
					imgsuffix = "_ghost";
				}
				userHTML +=  '<img src="' + imgPath + '/' + bugtypes[j] + imgsuffix + '.png" alt="' + bugtypes[j] + altxtra + '" title="' + bugtypes[j] + altxtra + '" width="24px" height="24px"/>';
			}
		}
		
		if( isUser )
		{
			html += '<div class="popupLabel thisUser">You have found ' + usercount+ ' of ' + bugtypes.length + ' bugs:</div><div class="popupIcons thisUser">' + userHTML + "</div>";
		}
		html += '<div class="popupLabel">Others have found ' + othercount + ' of ' + bugtypes.length + ' bugs:</div><div class="popupIcons">' + allHTML + '</div>';

		var marker = new GMarker(point, markerOpts);
		marker.html = html;
		GEvent.addListener( marker, "click", function() {
				this.openInfoWindowHtml(this.html);
			}
		);
		map.addOverlay(marker);
	}
	if( isNewPoint )
	{
		map.setCenter( point );
		marker.openInfoWindowHtml(marker.html);
	}
}

function changeType() // type )
{// no more seasons
	map.clearOverlays();
	var url = '/kidsite/bugs/get_map_points/1'; //  /0/0/' + type;
	loadPoints(url);
	// changeButton( type );
}

/*
function changeButton( season )
{
	var seasons = ['spring','summer','fall','winter'];
	for( var s=0; s < seasons.length; ++s )
	{
		var btn = document.getElementById("a_"+seasons[s]);
		if( ! btn )
		{
			continue;
		}
		if( $(btn).hasClassName('disabled') )
		{
			btn.onclick = function(){return false;};
			btn.onmouseout = null;
			btn.onmouseover = null;
			continue;
		}
		//alert( seasons[s] );
		//alert(btn);
		var img = document.getElementById("btn_" + seasons[s]);
		if( seasons[s] == season )
		{// alert(season);
			btn.onclick = function(){return false;};
			btn.onmouseout = null;
			btn.onmouseover = null;
			img.src = '/kidsite/img/bugs/season_labels/' + season + '_over.jpg';
			continue;
		}
		img.src = '/kidsite/img/bugs/season_labels/' + seasons[s] + '.jpg';
		btn.onmouseout = MM_swapImgRestore;
		btn.onmouseover = function () {
			var season = this.id.substr(2);
			// alert(season + 'mouseover');
			MM_swapImage('btn_' + season,'','/kidsite/img/bugs/season_labels/' + season + '_over.jpg',1);
		}
		btn.onclick = function () {
			var season = this.id.substr(2);
			changeType(season);
			return false;
		}
	}
}
*/

//////// inputs.js
// based on http://ryanfait.com/articles/2007/01/05/custom-checkboxes-and-radio-buttons/

var Input = {
	initialize: function() {
		if( document.getElementsByTagName("form") )
		{
			var divs = document.getElementsByTagName( "div" );
			for( var i = 0; i < divs.length;  ++i )
			{
				if( divs[i].className.match("radioy") || divs[i].className.match("radion") )
				{
					divs[i].onmouseover = Input.effect;
					divs[i].onmouseup = Input.handle;
					divs[i].onmouseout = Input.clear;
					
					var inputs = divs[i].getElementsByTagName('input');
					var input = inputs[0]; // should only be 1 input inside this div
					if ( input.type == 'radio' )
					{
						if( input.checked )
						{
							divs[i].className = "radio" + divs[i].className.substr(5,1) + " selected";
							divs[i].style.backgroundPosition = "0 0";
						}
					}
				}
			}
		}
	},

	effect: function() {
		if(this.className.match("radio") ) {
			this.style.backgroundPosition = "0 0";
		}
	},

	handle: function() {
		var selector = this.getElementsByTagName("input")[0];
		var YorN = this.className.substr(5,1);
		if( this.className.substr(0,5) == "radio" )
		{
			selector.click();
			this.className = "radio" + YorN + " selected";
			this.style.backgroundPosition = "0 0";
			
			inputs = document.getElementsByTagName("input");
			for(i = 0; i < inputs.length; i++) {
				if(inputs[i].getAttribute("name") == selector.getAttribute("name")) {
					if(inputs[i] != selector) {
						inputs[i].parentNode.className = "radio" + inputs[i].parentNode.className.substr(5,1);
						inputs[i].parentNode.style.backgroundPosition = "0 -29px";
					}
				}
			}
		}
	},

	clear: function() {
		if( this.className.match("radio") && !this.className.match("selected") ){
			this.style.backgroundPosition = "0 -29px";
		}
	}
}
////// end inputs.js

window.onload = initWindow;
window.onunload = GUnload;
