 
 
var map = null;
var numGeocoded = 0;
var geocoder = null;
var points = null;
var dataFile = "get_events.asp";
var selectMonth = -1;
var onCampusList = new Array();
var offCampusList = new Array();

	
	
	$(document).ready( function() {
		  initialize();
		  $(document).bind('beforeunload', 
		  				function (event) { 
						GUnload(); 
						}); 

		});
		
    
function initialize() {
  
  var hasCanvas = (document.getElementById("map_canvas")!= null);
  if (GBrowserIsCompatible() && hasCanvas) {
    
	map = new GMap2(document.getElementById("map_canvas"));
	map.addControl(new GLargeMapControl3D());
	
	geocoder = new GClientGeocoder();
    map.setCenter(new GLatLng(40.0, -99.5), 4);
	
	
	 $.ajax({
                 type: "GET",
                 url: dataFile,
                 dataType: "xml",
				 error: function (xhr, desc, exceptionobj, thrownError) {
				 			
							 	//IE 7 sometimes has a parseError. We force it here
								var myXml = GXml.parse(xhr.responseText);
							 		getPoints(myXml);
									},
                 success: function(xml){
				 		getPoints(xml);
				 	}
				 });
     
	
	}
}
function setEventListingByMonth(){
	$("#event_listing").html("loading events...");
	var onC = "";
	var offC = "";
	var onWeb = "";
	var finalContent = "";
	var newLine = "";
	
	
	for( i=0; i< points.length; i++){
		
		if ((selectMonth == points[i]['month']) || (selectMonth == -1)){
			
			newLine = "<tr><td><a href='" + points[i]['link'] + "'>"+ points[i]['title'];
			newLine += "</a></td><td>"+ points[i]['startTime']+ "</td></tr>";
			
			if(points[i]['campus'] == "ON"){
				onC  = newLine + onC; 			
			}
			else if ((points[i]['campus'] == "OFF") && (selectMonth > -1)){
				offC = newLine + offC;				
			}
			else{
				onWeb = newLine + onWeb;
				
			}
		
		}
	}

	
	finalContent = "<b><u>On-Campus events</u></b>"
	
	//Display for oncampus list
	if(onC == ""){
		finalContent +="<br/>There are no on-campus events for the selected time<br/>";
	}
	else{
		finalContent += "<table class='eventList'><tbody><tr><th>Event</th><th>Start Time</th></tr>"+ onC +"</tbody></table>";
	}
	
	finalContent += "<br/><b><u>Off-Campus events</u></b>";
	
	if (selectMonth == -1){
		finalContent += " -see the map above<br/>";
	}
	else if (offC == ""){
		finalContent += "<br/>There are no off-campus events for the selected time<br/>";
		$('#showLoad').hide();
	}
	else{
		finalContent += "<br/><table class = 'eventList'><tbody><tr><th>Event</th><th>Start Time</th></tr>"+ offC +"</tbody></table>";
	}
	
	$("#event_listing").html(finalContent);
	$('table.eventList tbody tr:odd').addClass('event_tables_odd');
    $('table.eventList tbody tr:even').addClass('event_tables_even');
	
	
}

function refreshData(){
	
	map.clearOverlays();
	numGeocoded = 0;
	selectMonth = $("select option:selected").attr("value");
	$("#period").html(" " + $("select option:selected").text());
	
	
	setEventListingByMonth();
	map.setCenter(new GLatLng(40.0, -96.0), 4);
	
	if (selectMonth > 0 ) {
		window.setTimeout(geocodeMonth, 50);
		}
	else{
		window.setTimeout(geocodeAll, 50);
	}
	

}

//Extract Information from xml file into an array. 
function getPoints(xml){
   
	var newPoints = new Array();
    var baseLINK = "http://www.tc.columbia.edu/admissions/calendar.htm?EventID=";
	
	
	$('#showLoad').html('<br/>Loading events...<img src="scripts/loadingAnimation.gif">');
	$('#showLoad').show();
	
	
	$(xml).find('event_info').each(function(){
				
				var tempArray = new Array();
				var startTime, endTime,eventDay, detailLink, title;
				
				tempArray['location'] = $(this).find('address').text();
				
				detailLink = baseLINK + $(this).find('EventID').text();
				title = $(this).find('event_title').text();
				tempArray['title'] = title;
				startTime = $(this).find('startTime').text();
				endTime = $(this).find('endTime').text();
				//eventDay = $(this).find('event_date').text();
				
				tempArray['month'] =  startTime.substring(0,startTime.indexOf("/"));
				tempArray['startTime'] = startTime;
				tempArray['link']= detailLink;
				tempArray['info'] = "<p><b>Event:</b> <a href='" + detailLink + "'>"+title + 
									"</a><br/><b>Starts: </b>"+ startTime + 
									"<br/><b>Ends: </b>" +  endTime + "</p>";
				
				//Exclude events that are oncampus.
				if (tempArray['location'].search('Oncampus') > -1 ) {
						tempArray['campus'] = "ON";
				}
				else if (tempArray['location'].search('Online') > -1 ){
					tempArray['campus'] = "WEB";
					
				}
				else{
					tempArray['campus']= "OFF";
				}
				
				newPoints[newPoints.length] = tempArray;
				
				});
				
	points = newPoints;
	
	setEventListingByMonth();
	window.setTimeout(geocodeAll, 50);
	
 }



//Recursive function to Geocode each point
function geocodeAll() {

	  var notFoundPoint = true;
	  var pointsLeft = (numGeocoded < points.length);
	  //$('#showLoad').show("slow");
	  
	   while(notFoundPoint && pointsLeft) {

	   	notFoundPoint =  (points[numGeocoded]['campus'] != "OFF");
	    
	    if (notFoundPoint){
	    	numGeocoded += 1;
	    }
		pointsLeft = (numGeocoded < points.length) ;
	    
	   }
	   
      if (numGeocoded < points.length) {
	  
       geocoder.getLocations(points[numGeocoded]['location'], addressResolved);
	 
      }
	  else{
	  	
		$('#showLoad').hide('slow');

	  }
}


//Recursive function to Geocode points in a specific month
function geocodeMonth() {

	  var notFoundPoint = true;
	  var pointsLeft = (numGeocoded < points.length) ;
	  //$('#showLoad').show("slow");
	  
	   while(notFoundPoint && pointsLeft) {

	   	notFoundPoint =  (! ((points[numGeocoded]['month'] == selectMonth) &&
							 (points[numGeocoded]['campus'] == "OFF")));
		
	    
	    if (notFoundPoint){
	    	numGeocoded += 1;
	    }
		
		pointsLeft = (numGeocoded < points.length) ;
	    
	   }
	   
      if (numGeocoded < points.length) {
	  
       geocoder.getLocations(points[numGeocoded]['location'], addressResolved);
	 
      }
      else{
      	//$('#showLoad').hide();
      	
      }

}


//Function called by the geocoder to deal with response.
//Recursively calls geocodeAll
function addressResolved(response) {
     var delay = 0;
     //alert("status code" + response.Status.code);
     if (response.Status.code == G_GEO_TOO_MANY_QUERIES) {
       // Too fast, try again, with a small pause
       delay = 500;
     } else {
       if (response.Status.code == G_GEO_SUCCESS ) {
         // Success; do something with the address.
         var place = response.Placemark[0];
         point = new GLatLng(place.Point.coordinates[1],
                             place.Point.coordinates[0]);
       
        map.addOverlay(createMarker(point,points[numGeocoded]['info']));
       }
       // Move onto the next address; this skips bad addresses, too.
       numGeocoded += 1;
     }
	 
	if (selectMonth < 0){
    	this.setTimeout(geocodeAll, delay);
    	}
    else {
    	this.setTimeout(geocodeMonth, delay);
    	}
		
    
}
   

// Creates a marker at the given point
// Clicking the marker will hide it
function createMarker(latlng,infoText) {
      var marker = new GMarker(latlng);
      
      GEvent.addListener(marker,"click", function() {
       
        map.openInfoWindowHtml(latlng, infoText);
      });
      
      return marker;
}