// JavaScript Document
var map;
var directions;
var Icon;
var points = {};

function initialize() {
  if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas")); 
		map.addControl(new GLargeMapControl());
		map.setCenter(new GLatLng(39.952254,-75.163136), 13);
		Icon = new GIcon();
	    Icon.image = "../images/flagIcon.png";
		Icon.iconSize = new GSize(34, 27);
		Icon.iconAnchor = new GPoint(3, 26);
		Icon.infoWindowAnchor = new GPoint(3, 1);
		Icon.transparent = "../images/flagIconTrans.png";
		dlData();
	}
}



//updates the existing tab with new content

function updateTab(lat, lng, index) {

  if(index > -1 ){

	map.updateInfoWindow( [new GInfoWindowTab(points[lat][lng].contentsArray[index].label, 

		points[lat][lng].contentsArray[index].content)]);

  }else{

  	map.updateInfoWindow( [new GInfoWindowTab("Select an Event", points[lat][lng].menuContent) ]);

  }

}

function showDirectionsWindow(address, lat, lng){
	var dirDiv = document.createElement("directionsWindow");
	var htm = "<p class='eventTitle'>Get Directions</p><p class='eventDesc'>Destination: "+address+"</p>";

	htm += "<input class='inputField' name='fromAddress' id='fromAddress' value='Starting Address' onclick='this.value=\"\"'></input><button value='Go' label='Go' "
	+ "onclick='requestDirections(document.getElementById(\"fromAddress\").value,\""+address+"\","+lat+", "+lng+");'/>Go</button>";

	dirDiv.innerHTML = htm;

	map.updateInfoWindow( [new GInfoWindowTab("Get Directions", dirDiv)]);

}
function requestDirections(from, to, lat, lng){
	var loadHandle;
	var errorHandle;
	if(!directions){ directions = new GDirections(map, document.getElementById("directionsOutput")); }
	directions.clear();
	loadHandle = GEvent.addListener(directions, "load", function() {
	  map.closeInfoWindow();
	  GEvent.removeListener(loadHandle);
	  GEvent.removeListener(errorHandle);
	});
	errorHandle = GEvent.addListener(directions, "error", function() {
	  alert("Sorry, there was an error. Please try again.");
	  GEvent.removeListener(loadHandle);
	  GEvent.removeListener(errorHandle);
	});
	directions.load("from: "+from+" to: "+lat+","+lng);
}
// Creates a marker at the given point with the given label

function createMarker(lat, lng, id) {

  //store references to markers by the lat/lng so we can group the event details into tabs

  if(!points[lat]){ points[lat] = {} };

  if(!points[lat][lng]){ 

  	points[lat][lng] = {marker: new GMarker(new GLatLng(lat, lng), Icon), infoArray:[], contentsArray:[]}; 

    map.addOverlay( points[lat][lng].marker );

  };

  

  var marker = points[lat][lng].marker;

	

  var container = document.getElementById("detailsContainer");

  var details = document.getElementById("eventDetails"+id);  

  

  GEvent.addListener(marker, "click", function() {  



	   if(!details){ 

			showLoading();

			details = document.createElement('div');

			details.setAttribute('id', "eventDetails"+id);

			details.overflow = 'auto';

			container.appendChild(details);

		   GDownloadUrl("php/returnDetails.php?i="+id,function(data,responseCode){

		   		 var xml = GXml.parse(data);

      			var items = xml.documentElement.getElementsByTagName("item");

				var htm = "<span class='eventTitle'>" + items[0].getAttribute("name") +"</span><br/>"

					+"<span class='eventDate'>"+items[0].getAttribute("date") +" - "+items[0].getAttribute("startTime") +"</span>"

					+"<br/><span class='eventAddress'>"+items[0].getAttribute("address")+"</span>"

					+"<p class='eventDesc'>" + items[0].getAttribute("description") +"</p><br/>";

				if(items[0].getAttribute("url"))

				{

					htm += "<a class='eventURL' target='_blank' href='"+items[0].getAttribute("url")+"'>More Details</a>"; 

				} 

				htm += " <a class='eventURL' href='#' onclick='javascript:showDirectionsWindow(\""
						+items[0].getAttribute("address")+"\","+lat+","+lng+")'>Directions</a>";

				details.innerHTML = htm;

				

				points[lat][lng].infoArray.push( new GInfoWindowTab(items[0].getAttribute("name").substr(0,10), details) );

				//I cant access the properties of a GInfoTab after it is created, so i have to store them separately, ugh

				points[lat][lng].contentsArray.push( {label:items[0].getAttribute("name"), content:details} );

			  	if(  points[lat][lng].infoArray.length < 6 )

				{

					marker.bindInfoWindowTabs(points[lat][lng].infoArray);

					marker.openInfoWindowTabs(points[lat][lng].infoArray, {maxWidth:300}); //open immediately

				}else{

					var menuContent = "<span class='eventDesc'>There are many events at this location. Please select one below for details.</span>"

						+"<br/><span class='eventAddress'>"+items[0].getAttribute("address")+"</span>"

						+ "<p><select name='eventSelect' onchange='updateTab("+lat+","+lng+",this.selectedIndex-1);return false;'>"
						+ "<option value=''>Select an event...</option>";

					for(i=0;i<points[lat][lng].infoArray.length;i++)

					{

						menuContent += "\n<option value='"+i+"' >" + points[lat][lng].contentsArray[i].label +"</option>";

					}

					menuContent += "</select></p>";

					points[lat][lng].menuContent = menuContent;

					marker.bindInfoWindowTabs(null);

					marker.bindInfoWindowHtml( menuContent, {maxWidth:300} );

					marker.openInfoWindowHtml( menuContent, {maxWidth:300} );

				}

				hideLoading();

		   } );

		}

  });

 // marker.openInfoWindowHtml(details);

  return marker;

}

function showLoading(){

  	document.getElementById("loadingPic").setAttribute("style","display:block;position:relative;top:-150px;left:20%;");

}

function hideLoading(){

	document.getElementById("loadingPic").setAttribute("style","display:none;");

}

//Downloads and processes the points data

//Check out the tutorial here: http://www.asiteforever.com/index.php/2007/10/21/adding-google-map-on-your-website-using-ajax/

function dlData(){

	showLoading();

	GDownloadUrl("php/returnPointsXML.php",function(data,responseCode) {

      var xml = GXml.parse(data);

      var markers = xml.documentElement.getElementsByTagName("marker");



      for (var i = 0; i < markers.length; i++) {

         var mark = createMarker(parseFloat(markers[i].getAttribute("lat")),

                            parseFloat(markers[i].getAttribute("lon")),

							markers[i].getAttribute("id"));

      }

	  hideLoading();

	});

}



function findPos(obj) {

	var curleft = curtop = 0;

	if (obj.offsetParent) {

		curleft = obj.offsetLeft

		curtop = obj.offsetTop

		while (obj = obj.offsetParent) {

			curleft += obj.offsetLeft

			curtop += obj.offsetTop

		}

	}

	return [curleft,curtop];

}