/**
 * @author Sampson
 */

/*
 * Begin Schedule Control
 */
function ScheduleControl() {
}

ScheduleControl.prototype = new GControl();

ScheduleControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  container.setAttribute("id","scheduleControl");
  container.style.border = "1px solid #666666";
  container.style.padding = "3px";
  
  var divScheduleTitle = document.createElement("div");
  divScheduleTitle.style.backgroundColor = "white";
  divScheduleTitle.style.borderTop = "1px solid #666666";
  divScheduleTitle.style.borderLeft = "1px solid #666666";
  divScheduleTitle.style.borderRight = "1px solid #666666";
  divScheduleTitle.style.fontSize = "80%";
  divScheduleTitle.style.padding = "5px";
    
  var divScheduleHeader = document.createElement("div");
  divScheduleHeader.setAttribute("id","scheduleHeader");
  divScheduleHeader.style.backgroundColor = "white";
  divScheduleHeader.style.borderTop = "1px solid #666666";
  divScheduleHeader.style.borderLeft = "1px solid #666666";
  divScheduleHeader.style.borderRight = "1px solid #666666";
  divScheduleHeader.style.fontSize = "80%";
  divScheduleHeader.style.padding = "5px";
  divScheduleHeader.style.width = "430px";
    
  var divSchedule = document.createElement("div");
  divSchedule.setAttribute("id","scheduleDetail");
  divSchedule.style.backgroundColor = "white";
  divSchedule.style.border = "1px solid #666666";
  divSchedule.style.fontSize = "80%";
  divSchedule.style.padding = "5px";
  divSchedule.style.height = "100px";
  divSchedule.style.width = "430px";
  divSchedule.style.overflowX = "auto";
  divSchedule.style.overflowY = "auto";
    
  container.appendChild(divScheduleTitle);
  container.appendChild(divScheduleHeader);
  container.appendChild(divSchedule);
  divScheduleTitle.innerHTML = '<b>Schedule</b>';
  divScheduleHeader.innerHTML = '<table><tr><th class=\"scheduleDayHeader\">Game Day</th><th class=\"scheduleResultsHeader\">Result</th><th class=\"scheduleAgainstHeader\">Opponent</th></tr></table>';
  divSchedule.innerHTML = 'No games displayed.';
  
  map.getContainer().appendChild(container);
  
  $('scheduleControl').hide();
  
  return container;
}

ScheduleControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 7));
}

/*
 * End Schedule Control
 */


// A function to create the marker and set up the event window
function createTeamsMarker(point, objGame, strLabelMode, customMarker) {
	var marker = new GMarker(point, customMarker);
	var arrInfoTabs = new Array();
	var newDivs = new Array();

	for(i=0;i<objGame.length;i++)
	{
		var html = "", strLabel = "";
		if(objGame.length > 1)
			html = html + "<div class=\"bubble\">";
		
		var strResult = "";
		if(objGame[i].away_score != "na" && objGame[i].home_score != "na")
		{
			if(objGame[i].home_game == "true")
			{
				if(parseInt(objGame[i].home_score) > parseInt(objGame[i].away_score))
				{
					strResult = "W (" + objGame[i].home_score + "-" + objGame[i].away_score + ")";
				}
				else
				{
					strResult = "L (" + objGame[i].away_score + "-" + objGame[i].home_score + ")";
				}
			}
			else
			{
				if(parseInt(objGame[i].home_score) > parseInt(objGame[i].away_score))
				{
					strResult = "L (" + objGame[i].home_score + "-" + objGame[i].away_score + ")";
				}
				else
				{
					strResult = "W (" + objGame[i].away_score + "-" + objGame[i].home_score + ")";
				}

			}
		}

		
		html += "<b>" + objGame[i].game_date + "<br/>" + objGame[i].game_time + "</b><hr/>";
		if(strResult.length > 0)
			html += "<b>" + strResult + "</b><br/>";
		html += "<b>" + objGame[i].away_name + " (" + objGame[i].away_class + ")</b> at <b>"+ objGame[i].home_name + " (" + objGame[i].home_class + ")</b><br/>" +
		        "<b>Stadium: </b>" + objGame[i].stadium_name +
		        "<br> <a href='http://maps.google.com/maps?saddr=&daddr=" + point.toUrlValue() + "+("+objGame[i].stadium_name+")' target ='_blank'>Get Directions</a>";

		if(objGame.length > 1)
			html = html + "</div>";
		
		if(strLabelMode == "date")		
			strLabel = objGame[i].game_date;
		if(strLabelMode == "time")		
			strLabel = objGame[i].game_time;
		
		arrInfoTabs[arrInfoTabs.length] = new GInfoWindowTab(strLabel, html)

		var gameInfo = document.createElement("a");
		gameInfo.innerHTML = "<span class=\"scheduleDay\">" + objGame[i].game_day + "</span>";
		
		var strResult = "<span class=\"scheduleResults\">" + strResult + "&nbsp;</span>";
		gameInfo.innerHTML += strResult;

		if (objGame[i].home_game == "true")
			gameInfo.innerHTML += "<span class=\"scheduleAgainst\">vs " + objGame[i].away_name + "</span>";
		else
			gameInfo.innerHTML += "<span class=\"scheduleAgainst\">at " + objGame[i].home_name + "</span>";
			

			
			
	
		gameInfo.setAttribute("index",i)
		gameInfo.setAttribute("value",objGame[i].game_date.replace(/\-/g,''))
		//$(stadiumBlock).appendChild(gameInfo);
		//$('scheduleDetail').appendChild(gameInfo);
		newDivs[newDivs.length] = gameInfo;

		if(objGame.length > 1)
		{
			GEvent.addDomListener(gameInfo, 'click', function() {
				var tabIndex = this.getAttribute("index");
				marker.openInfoWindowTabsHtml(arrInfoTabs, {maxWidth: 300, selectedTab: tabIndex});
			});
		}
		else
		{
			GEvent.addDomListener(gameInfo, 'click', function() {
				marker.openInfoWindowTabsHtml(arrInfoTabs, {maxWidth: 300});
			});
		}
	}
	
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowTabsHtml(arrInfoTabs, {maxWidth: 300});
	});
	
	//$('scheduleDetail').appendChild(stadiumBlock);
	
	return {marker: marker, newHtml: newDivs};
}


// A function to read the data and creates markers in the Teams Context
function readTeamsMap(url, strCurrViewText, strLabelMode) {
	$('loading').show();
	$('currentView').update("Viewing: Loading...");
	$('scheduleControl').show();
	$('scheduleDetail').update();

	var request = GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = GXml.parse(request.responseText);
			// obtain the array of markers and loop through it
			var markers = xmlDoc.documentElement.getElementsByTagName("stadium");
			
			// hide the info window, otherwise it still stays open where the removed marker used to be
			map.getInfoWindow().hide();
			
			map.clearOverlays();
			
			var last_point = new GLatLng(0,0);
			var objGame = new Array();
			var objGames = new Array();

			for (var i = 0; i < markers.length; i++)
			{
				// obtain the attribues of each marker
				var lat = parseFloat(markers[i].getAttribute("lat"));
				var lng = parseFloat(markers[i].getAttribute("lng"));
				var point = new GLatLng(lat,lng);
				objGame[objGame.length] = {
					game_date: markers[i].getAttribute("game_date"),
					game_day: markers[i].getAttribute("game_day"),
					game_time: markers[i].getAttribute("game_time"),
					home_game: markers[i].getAttribute("home_game"),
					away_name: markers[i].getAttribute("away_name"),
					away_nickname: markers[i].getAttribute("away_nickname"),
					away_conference: markers[i].getAttribute("away_conference"),
					away_class: markers[i].getAttribute("away_class"),
					home_name: markers[i].getAttribute("home_name"),
					home_nickname: markers[i].getAttribute("home_nickname"),
					home_conference: markers[i].getAttribute("home_conference"),
					home_class: markers[i].getAttribute("home_class"),
					away_score: markers[i].getAttribute("away_score"),
					home_score: markers[i].getAttribute("home_score"),
					stadium_name: markers[i].getAttribute("stadium_name")
				};
				
				try
				{
					var color = getMarkerColor(markers[i].getAttribute("home_class"));
					nextPoint = new GLatLng(parseFloat(markers[i + 1].getAttribute("lat")),parseFloat(markers[i + 1].getAttribute("lng")))
					if(!point.equals(nextPoint))
					{
						var newMarkerObjs = createTeamsMarker(point, objGame, strLabelMode, iconMarkers[color]);
						map.addOverlay(newMarkerObjs.marker);
						objGames[objGames.length] = newMarkerObjs.newHtml;
						objGame.clear();
					}
				}
				catch (error)
				{
					var color = getMarkerColor(markers[i].getAttribute("home_class"));
					var newMarkerObjs = createTeamsMarker(point, objGame, strLabelMode, iconMarkers[color]);
					map.addOverlay(newMarkerObjs.marker);
					objGames[objGames.length] = newMarkerObjs.newHtml;
					objGame.clear();
				}
				last_point = point;
			}

			objGames = objGames.flatten();
			var strTemp = "Before Sort\n===============\n";
			objGames.sortBy(function(s){
				return $(s).readAttribute("value")}
			);
			
			for(i=objGames.length;i>=0;i--)
			{
				var flipped = false;
				for (j = 0; j<i-1; j++)
				{
					if (objGames[j].readAttribute("value") > objGames[j+1].readAttribute("value"))
					{
						var T = objGames[j];
						objGames[j] = objGames[j+1];
						objGames[j+1] = T;
						flipped = true;
					}
				}
				if (!flipped)
					break;
			}
			
			objGames.each(function(game){
				$('scheduleDetail').appendChild(game);
			});
			
			$('loading').hide();
			$('currentView').update(strCurrViewText);
		}
	}
	request.send(null);
}


if (GBrowserIsCompatible()) {
	var i = 0;

	//create the map
	var map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new FootballLegendControl());
	map.addControl(new ScheduleControl());
	map.setCenter(new GLatLng(40.440676262682395, -80.00930786132812), 8);
	map.enableScrollWheelZoom();

	
	//----- Stop page scrolling if wheel over map ----
	function wheelevent(e)
	{
		if (!e) e = window.event;
		if (e.preventDefault) e.preventDefault();
		e.returnValue = false;
	}
	
	GEvent.addDomListener(document.getElementById("map"), "DOMMouseScroll", wheelevent);
	document.getElementById("map").onmousewheel = wheelevent;
	
	var loadingDiv = document.createElement("div");
	loadingDiv.setAttribute("id","loading");
	loadingDiv.innerHTML = "<img src=\"/images/ajax-loader.gif\" /><br />Loading...";
	$(loadingDiv).hide();
	
	document.getElementById("map").appendChild(loadingDiv);

	
}
else
{
  alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/   
// http://www.econym.demon.co.uk/googlemaps/
