function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

var map;
var pin;

var listmap;
//var gmarkers = [];
//var htmls = [];
var sh_points=[];

      
function sh_map_load() {
	if (document.getElementById("gmap_params")) { //map with single marker
	  sh_map("gmap_params");	
	}
	if (document.getElementById("gmap_params_list")) { //big list of markers found in json variable
	  sh_listmap("gmap_params_list");	
	}
}

//http://econym.googlepages.com/example_map12a.htm
// A function to create the marker and set up the event window
function sh_createMarker(point,html) {  
        var marker = new GMarker(point);
         GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
         });        
        return marker;
}

          
function sh_listmap(paramname) {
	if (document.getElementById(paramname)) {
	if (GBrowserIsCompatible()) {
		var zo=document.getElementById(paramname).getAttribute("zoom");
		var mtype=document.getElementById(paramname).getAttribute("maptype"); //listmap 
		var mapid=document.getElementById(paramname).getAttribute("mapid"); 
			
		listmap = new GMap2(document.getElementById(mapid));
		listmap.addControl(new GLargeMapControl());
		listmap.addControl(new GMapTypeControl());		
   		listmap.setCenter(new GLatLng(30,-36), 2);
		sh_process_it();
        sh_resizeMap( listmap, sh_points );
       
     
	}
	}
}   
      // === Define the function thats going to process the JSON file ===
function  sh_process_it() {
        // === Parse the JSON document === 
     //   var jsonData = eval('(' + map_jsondata + ')');
        
        // === Plot the markers ===
        for (var i=0; i<map_jsondata.markers.length; i++) {
	     	 var point=new GLatLng(map_jsondata.markers[i].lat,map_jsondata.markers[i].lon);
         	 var marker = sh_createMarker(point, map_jsondata.markers[i].html);
         	 listmap.addOverlay(marker);
         	 sh_points.push( point );
        }

 }               
     

function sh_map(paramname) {
	if (document.getElementById(paramname)) {
	if (GBrowserIsCompatible()) {
		var la=document.getElementById(paramname).getAttribute("lat");
		var lo=document.getElementById(paramname).getAttribute("lon");
		var lainput=document.getElementById(paramname).getAttribute("latinput");
		var loinput=document.getElementById(paramname).getAttribute("loninput");
		var zo=document.getElementById(paramname).getAttribute("zoom");
		var mtype=document.getElementById(paramname).getAttribute("maptype"); //map , clickmap 
		var miinput=document.getElementById(paramname).getAttribute("miinput"); //miles radius to draw circle if not provided no circle is drawn
		var mapid=document.getElementById(paramname).getAttribute("mapid"); 
		//if not la and lo are provided read the latinput loninput fields to get location
		if (!(la || lo)) {
			la=document.getElementById(lainput).value;
			lo=document.getElementById(loinput).value;			
		}
		
		map = new GMap2(document.getElementById(mapid));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		if ( lo=='' || la=='' ) {
		  map.setCenter(new GLatLng(30,-36), 1);
		}else {		
		  pin=new GLatLng(la, lo);
		  map.setCenter(pin, 1*zo);		      
		  map.addOverlay(new GMarker(pin));		      
		}
		//map.panTo(pin);	
		if (mtype == 'clickmap') {
		  document.getElementById(lainput).onchange=sh_updatemap;
		  document.getElementById(loinput).onchange=sh_updatemap;
		  if (miinput) {
		  	document.getElementById(miinput).onchange=sh_updatemap;
	  	  }
		
		  GEvent.addListener(map, 'click', function(overlay,point) {
  			if (overlay) {
    			map.removeOverlay(overlay);
    			point=overlay.getPoint();
  			}else{
	  			map.clearOverlays()
  			}
  			 map.addOverlay(new GMarker(point));
			 pin=point;
  			 document.getElementById(lainput).value=pin.lat();
  			 document.getElementById(loinput).value=pin.lng();
  			 //var miles=document.getElementById('sh_miles').value;
  			 //sh_drawCircle(point,miles,'#664400', 1, 0.5); 			 
  			 if (miinput) {
 				sh_drawCircleWrap();
			 }
 			});
 		  if (miinput) {
	 	  		var miles=document.getElementById(miinput).value;
  				setTimeout("sh_drawCircle(new GLatLng("+la+","+lo+"),"+miles+",'#f06000', 1, 0.5)",100);
  				//setTimeout('sh_drawCircleWrap()',200);
		  }
		}
  	}
	}
}
function sh_updatemap() {	
	var lainput=document.getElementById("gmap_params").getAttribute("latinput");
	var loinput=document.getElementById("gmap_params").getAttribute("loninput");
	var miinput=document.getElementById("gmap_params").getAttribute("miinput"); //miles radius to draw circle if not provided no circle is drawn
	la=document.getElementById(lainput).value;
	lo=document.getElementById(loinput).value;		
	map.clearOverlays();
    pin=new GLatLng(la, lo);
	map.setCenter(pin);		      
	map.addOverlay(new GMarker(pin));		      
	if (miinput) {
	  var miles=document.getElementById(miinput).value;	
	  setTimeout("sh_drawCircle(new GLatLng("+la+","+lo+"),"+miles+",'#f06000', 1, 0.5)",100);
  							
	}	
}

function sh_drawCircleWrap() {
	var miinput=document.getElementById("gmap_params").getAttribute("miinput"); //miles radius to draw circle if not provided no circle is drawn		 				
	var miles=document.getElementById(miinput).value;
	sh_drawCircle(pin,miles,'#f06000', 1, .5);	
}

function sh_drawCircle(center, radius, color, thickness, opacity) {
	if (radius > 5000) {return;}
	//Function created by Chris Haas
	var circleQuality = 10;			//1 is best but more points, 5 looks pretty good, too
	var M = Math.PI / 180;			//Create Radian conversion constant
	var L = map.getBounds();		//Holds copy of map bounds for use below
	var sw = L.getSouthWest();
	var ne = L.getNorthEast();
	
	radius=radius/75;//wild guess
	
	//The map is not completely square so this calculates the lat/lon ratio
	// this works because we create a square map
	var circleSquish =(ne.lng() - sw.lng()) / (ne.lat() - sw.lat());
	//stanh aspect ratio of the window
	circleSquish=circleSquish*180/300

	var points = [];							//Init Point Array
	//Loop through all degrees from 0 to 360
	for(var i=0; i<360; i+=circleQuality){
		var P = new GLatLng(
			center.lat() + (radius * Math.sin(i * M)),
			center.lng() + (radius * Math.cos(i * M)) * circleSquish
			);
		points.push(P);
	}
	points.push(points[0]);	// close the circle
	var p = new GPolyline(points, color, thickness, opacity)
	map.addOverlay(p);
}

//called from node edit form button above map
//does geocode of info in location fields of form into lat,lon fields so map marker gets placed
function geohack_geocodenode() {
	var street=document.getElementById("edit-locations-0-street").value;
	var city=document.getElementById("edit-locations-0-city").value;
	var state=document.getElementById("edit-locations-0-province").value;
	var zip=document.getElementById("edit-locations-0-postal-code").value;
	var country=document.getElementById("edit-locations-0-country").value;
	
	state=state.substr(3);
	var addres=street+' '+city+', '+state+' '+zip+ ' '+country;
	
	//http://www.google.com/apis/maps/documentation/#Geocoding_Examples
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(addres,
    	function(point) {
	      if (!point) {
	        alert("'"+addres +"' was not found. Check spelling then click on the map below to find correct location.");
	      } else {
		    var lainput=document.getElementById("gmap_params").getAttribute("latinput");
			var loinput=document.getElementById("gmap_params").getAttribute("loninput");		
		     document.getElementById(lainput).value=point.lat();
		     document.getElementById(loinput).value=point.lng();
		  	 map.clearOverlays()  			
  			 map.addOverlay(new GMarker(point));
  			 if (street) {map.setCenter(point, 12);}
  			 else{map.setCenter(point, 6);}        
	      }
	   }
   );
}

//initalize timeline input: timeline_jsondata , <div id='my-timeline'> required
function timeline_onLoad() {
	 if (document.getElementById("my-timeline")) {
	  var eventSource = new Timeline.DefaultEventSource(); 
	 var theme = Timeline.ClassicTheme.create();
            theme.event.label.width = 140; // px
            theme.event.bubble.width = 190;
            theme.event.bubble.height = 200;
         
	  var bandInfos = [
	   Timeline.createBandInfo(
	  { eventSource: eventSource,
	  //  date: new Date().toString(), //"Aug 1 2007 00:00:00 GMT", 
	    width: "70%",
	    intervalUnit: Timeline.DateTime.DAY,
	    intervalPixels: 150,
	    trackHeight: 1,
	    trackGap: 0.1,
	    timeZone:0 ,
	    theme: theme
	   } ),
	   Timeline.createBandInfo(
	   { eventSource: eventSource,
	   //  date: new Date().toString(), //"Aug 1 2007 00:00:00 GMT", 
	     showEventText: false,
	     trackHeight: 0.4,
	     trackGap: 0.1,
	     width: "30%", 
	     intervalUnit: Timeline.DateTime.MONTH, 
	     intervalPixels: 300,
	     timeZone:0,
	     theme: theme
   		} 
	   ) ];
	   bandInfos[1].syncWith = 0; bandInfos[1].highlight = true;
	   bandInfos[1].eventPainter.setLayout(bandInfos[0].eventPainter.getLayout()); 
	
	   tl = Timeline.create(document.getElementById("my-timeline"), bandInfos); 
	   eventSource.loadJSON(timeline_jsondata, ''); 
	  }
}
	   
function sh_resizeMap( lmap, points ) {
  var minLong = 999;
  var minLat = 999;
  var maxLong = -999;
  var maxLat = -999;
  
  
var bounds = lmap.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var baseHeight = northEast.lng() - southWest.lng();
var baseWidth = northEast.lat() - southWest.lat();

  
  // Figure out the elemental unit (depends on the size of the map)
  // You will need to re-run resizeMap() if the size of the map changes.
  if ( lmap.getZoom() > 0 ) {
    baseWidth /= Math.pow( 2, 17-lmap.getZoom() );
    baseHeight /= Math.pow( 2, 17-lmap.getZoom() );
  }
  
  // Find the max/min points
  for ( var i = 0; i < points.length; i++ ) {
    if ( points[i].x < minLong ) minLong = points[i].x;
    if ( points[i].x > maxLong ) maxLong = points[i].x;
    if ( points[i].y < minLat ) minLat = points[i].y;
    if ( points[i].y > maxLat ) maxLat = points[i].y;
  }
  
  // Find the optimal Width Zoom
  var wZoom = 0;
  var w = Math.abs( maxLong - minLong );
  for ( var i = 1; i < 16; i++ ) {
    if ( baseWidth > w ) break;
    baseWidth *= 2;
    wZoom = i;
  }
  
  // Find the optimal Height Zoom
  var hZoom = 0;
  var h = Math.abs( maxLat - minLat );
  for ( var i = 1; i < 16; i++ ) {
    if ( baseHeight > h ) break;
    baseHeight *= 2;
    hZoom = i;
  }
  
  // Reposition
  lmap.setCenter(
    new GLatLng( ( minLat + maxLat ) / 2 ,( minLong + maxLong ) / 2),16-( wZoom > hZoom ? wZoom : hZoom )
  );
}

addLoadEvent(sh_map_load);
addLoadEvent(timeline_onLoad);
