//Dependencies: google map api 2.x, COEService.js

var map;
var bounds;
var blueIcon;
var markerArray = new Array();

function load() {

	if (GBrowserIsCompatible()) {
		map = new GMap2( document.getElementById("map") );
		map.addControl( new GLargeMapControl() );
		map.addControl( new GMapTypeControl() );
		geocoder = new GClientGeocoder();
		map.setCenter(new GLatLng(37.44, -92.25), 3); 
	}
} 

function validForm() {

	var city  = document.getElementById("txt_city").value;
	var state = document.getElementById("sel_State").value;
	var zip =  document.getElementById("zip");
	
	var validZipCode = ( zip.value != '' )? true: false;
	var validCityState = ( city == "" || state == "" )? false : true;
	
	if( validZipCode  ){ 
		if( !isZipCode( zip.value )){
			alert( "Please Enter Valid 5 digit zip code" );
			zip.focus();
		}
	}
	else {
		if ( !validCityState ){
			city = "";
			state = "";
			zip.value  = "";
			alert("Please Enter a zip code or City and State");
		}	
	} 
	return  validZipCode  || validCityState;
}	

function isZipCode( value ){

	var numericExpression = /^[0-9]+$/;
	if( value.match( numericExpression )){
		if( value.length > 4 && value.length < 6 )
			return true
		else
			//alert('Error: Length is '+value.length);
			return false;
	}else
		return false; 
}

function createMarker( point, details) {
	
	var marker = new GMarker( point, blueIcon);
	map.addOverlay( marker );
	markerArray.push(marker) ; 
		
	bounds.extend(point);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml( details );
	});
	
	var sidebarEntry = createSidebarEntry(marker, details );
	document.getElementById("sidebar").appendChild(sidebarEntry);
} 


function createSidebarEntry( marker, details ) { 

      var div 			= document.createElement('div');
      var html 			= details + "<br />";
      div.innerHTML 	= html;
      div.style.cursor 	= 'pointer';
      div.style.marginBottom = '2px'; 
	  
      GEvent.addDomListener(div, 'click', function() {
		GEvent.trigger(marker, 'click');
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#f5f5f5';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#fff';
      });
      return div;
}


function createDetails( result ) {

	var e = result.event;
	var ed = result.eventDetails;	
	var description =  "<span  class='sidebarTitle'><b>" + e.EventName + "</b></span>";	

	try {
		description += "<br/><span class='sidebar_red' ><b>" + ed.LocationName +  "</b></span>";
	}catch(e0){}
	try {
		description += "<br/><span class='sidebar' >"+ e.Address;
	}catch(e1){}
	try {
		description +=  "<br />" + e.City;
	}catch(e2){}
	try {
		description +=  ", "+ e.State;
	}catch(e3){}
	try {
		var startDate  = e.StartDate.replace( "/20", "/" ).replace( ":00 ", " " );
	}catch(e4){
		var startDate = ""
	}
	try {
		var endDate  = e.EndDate.replace( "/20", "/" ).replace( ":00 ", " " );
	}catch(e5){
		var endDate = ""
	}
	description += "<br/>Starts:&nbsp;"+startDate +"<br/>Ends:&nbsp;"+endDate
	try {
		description += "<br/>Event Distance:&nbsp;" + e.Distance;
	}catch(e6){}
	description += "</span>";
	try {
		description += "<br /><a href='" + e.EventURL + "' TARGET='_blank'  class='sidebar' style='color:blue' > Event Website</a><br />"
	}catch(e7){
		description += "<br /><a href='http://www.relayforlife.com/docroot/home/index.asp' TARGET='_blank' style='color:blue' > Event Website</a><br />";
	}
	try {
		description += "</span><a href='http://www.google.com/maps?f=q&hl=en&q=" + e.Address + ","  + e.City + ","  + e.State + "' TARGET='_blank'   ><span class='sidebar_red' >Get Directions</span></a>";
	}catch(e8){}
	description += "<br/>";
	return description;

} 


function submit() {

	if( validForm() ){
	
		document.getElementById("searchText").style.visibility = "visible";
		document.getElementById("searchText").value = "Searching...";
		document.getElementById("sidebar_title").innerHTML  = "";
		document.getElementById("sidebar").innerHTML  = "<br/>";
		document.body.style.cursor = 'wait';

		blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.image =  "images/purplePushpin.png"
		blueIcon.shadow = "images/purplePushpinShadow.png";

		if (document.getElementById("selectedRadius").value == "5" ) {
			 blueIcon.iconSize = new GSize(20,20);
			 blueIcon.shadowSize = new GSize(38, 20);
			 blueIcon.iconAnchor = new GPoint(20, 35);
			 blueIcon.infoWindowAnchor = new GPoint(19, 2);
			 blueIcon.infoShadowAnchor = new GPoint(36, 19);
		} else {
			 blueIcon.iconSize = new GSize(17,17);
			 blueIcon.shadowSize = new GSize(34, 17);
			 blueIcon.iconAnchor = new GPoint(17, 32);
			 blueIcon.infoWindowAnchor = new GPoint(16, 1);
			 blueIcon.infoShadowAnchor = new GPoint(33, 16);
		}	
					
		map.setCenter(new GLatLng(37.44, -92.25), 3); 
		bounds = new GLatLngBounds();
		
		for( var i=0; i < markerArray.length; i++ )
			map.removeOverlay(markerArray[i]); 
		var userRad
		userRad = ( document.getElementById("selectedRadius").value == 'select')? '40': document.getElementById("selectedRadius").value;
		radius = padRadius(userRad);
		new COEService().getEvents(	
			document.getElementById("zip").value, radius, 
			document.getElementById("txt_city").value, 
			document.getElementById("sel_State").value, 	
				function ( results ) {
 					var nEvents = 0;
					if( results ){
							for( var r in results ){
								var e = results[ r ].event;
								var ed = results[ r ].eventDetails;
								var eDistance = 300;
								// display only those events which are less than or equal to 'padded' radius
								if (e.Distance) {
									eDistance = Math.round(e.Distance);
								}  else {
									eDistance = 200;
								}
							var userRadius
		userRadius = ( document.getElementById("selectedRadius").value == 'select')? '40': document.getElementById("selectedRadius").value;


								if (padRadius(userRadius) >= eDistance) {
										if( e.Latitude && e.Latitude != '' & e.Latitude != '0'){						
											var pt = new GLatLng( (+e.Latitude), (+e.Longitude));
											createMarker( pt, createDetails( results[ r ]) );
											nEvents++;
										} else {
											alert(" NOT FOUND")
											alert(results[ r ].eventDetails)
										}	
								}
							}	

							document.body.style.cursor = 'default';
							var radius = document.getElementById("selectedRadius").value;
							radius = ( radius == 'select')? '40': radius;
							var html;
							var isZipHeader
							html = "......"
						    if ( document.getElementById("zip").value != "") {
								isZipHeader = " zip " + document.getElementById("zip").value
							} else {
								isZipHeader = document.getElementById("txt_city").value + ", " + document.getElementById("sel_State").value; 
							}
							
					if ( nEvents > 1) {
						html = "<Strong>There are "+ nEvents +" events within a "+ radius +" mile radius of " + isZipHeader +"</Strong><br/><br/>";
					} else if ( nEvents == 1) {
						html = "<Strong>There is one event within a " + radius + " mile radius of " + isZipHeader + "</Strong><br/><br/>";
					} else {
						html = "<Strong>There are no events within a " + radius + " mile radius of " + isZipHeader + "</Strong><br/><br/>";
					}
							document.getElementById("sidebar_title").innerHTML = html;
							document.getElementById("searchText").style.visibility = "hidden";							
					} 	
				},
				function ( error ){
						document.body.style.cursor = 'default';
						document.getElementById("searchText").style.visibility = "hidden";		
						alert("there has been an error - Failure" + error.responseText);			
				},
				
				function ( exception ){
					document.body.style.cursor = 'default';
					document.getElementById("searchText").style.visibility = "hidden";
					if ( document.getElementById("selectedRadius").value != "") {
							alert("Cannot find a Relay For Life event within " + document.getElementById("selectedRadius").value + " miles of this zip code");
					} else {
							alert("Cannot find a Relay For Life event within " + document.getElementById("selectedRadius").value + " miles of this city and state");
					}			
				}
		);

	}		
}
function padRadius(userRad) {
	var userRad
		if (userRad == 5) 
		{
			userRad = 8
		} 
		else if (userRad == 10)  
		{
			userRad  = 15
		} 
		else if (userRad == 20)
		{
			userRad  = 25
		} 
		else if (userRad == 30) 
		{
			userRad  = 35
		} 
		else if (userRad == 40) 
		{
			userRad  = 45
		}
		else if (userRad == 50) 
		{
			userRad  = 55
		} 
		else if (userRad == 100) 
		{
			userRad  = 150
		} 
		else if (userRad == 200) 
		{
			userRad  = 250
		}
		return userRad
}

