// JavaScript Document

// GLOBAL_VARIABLES

var RYE_MAP ;

var MAIN_LAT = 43.65872874896846 ;
var MAIN_LNG = -79.37926769256592 ;

// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
//http://www.econym.demon.co.uk/googlemaps/index.htm
var RYE_MARKER_INDEX = 0; 
var RYE_MARKER = [] ;
var RYE_MARKER_INFO = [] ;
var RYE_MARKER_INFO_DRIVING_TO = [] ;
var RYE_MARKER_INFO_DRIVING_FROM = [] ;
var RYE_MARKER_POINT = [] ;

var RYE_XML_DOC_CLASSROOM ;
var RYE_XML_DOC_OTHER_CENTER ;

var RYE_XML_DOC_PROGRAMS ;
var RYE_XML_DOC_PROGRAMS_FACULTY_ARTS ;
var RYE_XML_DOC_PROGRAMS_FACULTY_BUS ;
var RYE_XML_DOC_PROGRAMS_FACULTY_BUS_MGMT ;
var RYE_XML_DOC_PROGRAMS_FACULTY_CAD ;
var RYE_XML_DOC_PROGRAMS_FACULTY_CMS ;
var RYE_XML_DOC_PROGRAMS_FACULTY_ENG_SCN ;

var RYE_XML_DOC_OTHERS_STUDENT_SERVICES ;
var RYE_XML_DOC_OTHERS_ADMISSION ;
var RYE_XML_DOC_OTHERS_SECURITY ;
var RYE_XML_DOC_OTHERS_PLANNING_ADVANCEMENT ;
var RYE_XML_DOC_OTHERS_COMMON_SERVICES ;
var RYE_XML_DOC_DEPARTMENT_OTHER ;

var P_RYE_MAP ; //custom map type
var MAIN_POINT ; //the location of ryerson using MAIN_LAT & MAIN_LNG
var MAIN_MARKER ; //the marker that will point to ryerson location

/**
 * This function is being called when the body of the webpage loads.
 * The function will first check the browser, whether it is compatible
 * or not in order to show google map. If it is, then the function to create
 * the map will be called and further manipulation of the map will take
 * place.
 */
function load()
{
	//alert("loading") ;
	displayLoadingInfo("on") ;
	// check browser compatibility
	if (GBrowserIsCompatible())
	{
		initMap() ;
		//resize the map to the window size 
		resizeMap() ;
		// browser is compatible. create map
		createRyeMap() ;
		//create defalult point
		MAIN_POINT = new GLatLng(MAIN_LAT, MAIN_LNG) ;
		MAIN_MARKER = new GMarker(MAIN_POINT) ;
		
		//read the xml file
		loadMapXml("db/buildings/classroomBuildings.xml", "classroomLocationList", "classroom") ;
		//load the xml for informationLocationBuildings
		loadMapXml("db/buildings/informationBuildings.xml", "infoLocationList", "infoLoc") ;
	
	}
	else
	{
		// browser is not compatible. alert the user
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
	displayLoadingInfo("off") ;
}

/**
 * This function creates the actual map
 */
function createRyeMap()
{
	//create a new map object
	RYE_MAP = new GMap2(document.getElementById("ryeMap"));
	// add control to zoom in/out and pane using buttons
	RYE_MAP.addControl(new GLargeMapControl());

	//custom map
      CustomGetTileUrl=function(a,b)
	  {
		var c=Math.pow(2,b);
        var d=a.x;
        var e=a.y;

        //return "http://ccgi.snaffle.plus.com/tiles.php?t="+f
		var alink = "GoogleMap/index.php?" + "x=" + d + "&y=" + e + "&zoom=" + b ;
	  //alert(alink) ;
        return alink ;
      } 

		var customCopyRight = new GCopyrightCollection("Ryerson Campus") ;
		
		var customTileLayer = [new GTileLayer(customCopyRight, 0, 17)] ;
		customTileLayer[0].getTileUrl = CustomGetTileUrl ;
		
		customTileLayer[0].getCopyright = function(a,b) {
        	return {prefix:"Map: ", copyrightTexts:["Pman"]};
      	}
		var customProjection = G_NORMAL_MAP.getProjection() ; //G_SATELLITE_MAP.getProjection() ;
		
		P_RYE_MAP = new GMapType(customTileLayer, customProjection, "Ryerson", {errorMessage: "Error creating Ryerson's custom map"}) ;
		RYE_MAP.addMapType(P_RYE_MAP) ;

	//end of custom map	
	
	//add control to switch between different types of map
    RYE_MAP.addControl(new GMapTypeControl());
	//set the map to show ryerson campus
	RYE_MAP.setCenter(new GLatLng(MAIN_LAT, MAIN_LNG), 17, P_RYE_MAP);
	//add an event listener for zoomend event
	GEvent.addListener(RYE_MAP, "zoomend", zoomChanged) ;
	//add an event listener for maptypechanged event
	//GEvent.addListener(RYE_MAP, "maptypechanged", mapTypeChanged) ;

}

/**
 * This function will read the xml file from the server and
 * use the google's api to load it. After the loading is done
 * it will parse the data and create marker for each point.
 * Thanks to Mike (http://www.econym.demon.co.uk/googlemaps/basic3.htm)
 * for this excellent tutorial.
 */
function loadMapXml(xmlFileName, outputLocation, xmlFileId)
{
	//alert("loading... " + xmlFileName) ;
	var infoTabs = [] ;
	var infoTabContents = [] ;
	
	// Read the data from xml file
	var request = GXmlHttp.create();
	
	request.open("GET", xmlFileName, true) ;
		
	request.onreadystatechange = function()
	{
		if(request.readyState == 2 || request.readyState == 1)
		{
			displayLoadingInfo("on") ;
		}
		if (request.readyState == 4)
		{
			var xmlDoc = request.responseXML;
			
			//save the xmlFile instance to the global variable passed as argument
			if(xmlFileId == "classroom")
				RYE_XML_DOC_CLASSROOM = xmlDoc ;
			else if(xmlFileId == "infoLoc")
				RYE_XML_DOC_OTHER_CENTER = xmlDoc ;
			else if(xmlFileId == "otherCourses")
				RYE_XML_DOC_PROGRAMS = xmlDoc ;
			else if(xmlFileId == "facultyArts")
				RYE_XML_DOC_PROGRAMS_FACULTY_ARTS = xmlDoc ;
			else if(xmlFileId == "facultyBus")
				RYE_XML_DOC_PROGRAMS_FACULTY_BUS = xmlDoc ;
			else if(xmlFileId == "facultyBusMgmt")
				RYE_XML_DOC_PROGRAMS_FACULTY_BUS_MGMT = xmlDoc ;
			else if(xmlFileId == "facultyCad")
				RYE_XML_DOC_PROGRAMS_FACULTY_CAD = xmlDoc ;
			else if(xmlFileId == "facultyCms")
				RYE_XML_DOC_PROGRAMS_FACULTY_CMS = xmlDoc ;
			else if(xmlFileId == "facultyEngScn")
				RYE_XML_DOC_PROGRAMS_FACULTY_ENG_SCN = xmlDoc ;
			else if(xmlFileId == "otherDepartment")
				RYE_XML_DOC_DEPARTMENT_OTHER = xmlDoc ;
			else if(xmlFileId == "othersStudentService")
				RYE_XML_DOC_OTHERS_STUDENT_SERVICES = xmlDoc ;
			else if(xmlFileId == "othersAdmission")
				RYE_XML_DOC_OTHERS_ADMISSION = xmlDoc ;
			else if(xmlFileId == "othersSecurityServices")
				RYE_XML_DOC_OTHERS_SECURITY = xmlDoc ;
			else if(xmlFileId == "othersPlanningAdvancement")
				RYE_XML_DOC_OTHERS_PLANNING_ADVANCEMENT = xmlDoc ;
			else if(xmlFileId == "othersCommonServices")
				RYE_XML_DOC_OTHERS_COMMON_SERVICES = xmlDoc ;
				
			// obtain the array of markers and loop through it
			var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	
			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);
				//obtain the label tag and then retrieve the value and the id of the label
				var labelValue = GXml.value(markers[i].getElementsByTagName("label")[0]);
				var labelId = markers[i].getElementsByTagName("label")[0].getAttribute("id") ;
				var label ;
				if(labelId)
					label = "<span class='bldCode'>" + labelId + " - </span><span class='bldName'>" + labelValue + "</span>" ;
				else 
					label = "<span class='bldName'>" + labelValue + "</span>" ;
				//obtain the html info that is a child element of <marker>
				/**
				 * Since the htmlInfo element also has multiple elements for tabs,
				 * loop over its child elements and save all the tabs in an array
				 */
				var html = markers[i].getElementsByTagName("htmlInfo");
				//first loop over htmlInfo element to get all the tabs
				var tabs = html[0].getElementsByTagName("tab") ;
				var tabLabel ;
				var tabContent ;
				
				for (var j = 0 ; j < tabs.length ; j++)
				{
					//now, for each tab's get it's label tag and content tag
					tabLabel = GXml.value(tabs[j].getElementsByTagName("tabLabel")[0]) ;
					tabContent = GXml.value(tabs[j].getElementsByTagName("tabContent")[0]) ;
					
					infoTabs.push(tabLabel) ;
					infoTabContents.push(tabContent) ;
					/*infoTabs[j] = tabLabel ;
					infoTabContents[j] = tabContent ;*/
				}
				var tabbedWindow = [] ;
				for (var j = 0 ; j < infoTabs.length ; j++)
				{
					tabbedWindow.push(new GInfoWindowTab(infoTabs[j], infoTabContents[j])) ;
					//tabbedWindow[j] = new GInfoWindowTab(infoTabs[j], infoTabContents[j]) ;
				}
				createMarker(point,label, labelValue, outputLocation, tabbedWindow);
				infoTabs = removeArrayContent(infoTabs) ;
				infoTabContents = removeArrayContent(infoTabContents) ;
				tabbedWindow = removeArrayContent(tabbedWindow) ;
				//alert(infoTabs.length) ;
			}
			//alert("loaded " + xmlFileName) ;
			//document.getElementById('searchResultDisplay').innerHTML += "<br/>loaded " + xmlFileName + "<br/>" ;
			displayLoadingInfo("off") ;
		}
	}
	request.send(null);
}

/**
 * A function to create the marker and set up the event window.
 * Every point that is received in the parameter, add it to the
 * global MARKER array using push method. Once the points are 
 * created and stored in the array, write the marker label
 * in the div called "sidebar", in which the user will click to
 * see the marker on the map.
 * @point - GPoint information of the marker. the point where the marker
 *			will be placed.
 * @name - 	The text that will be displayed in the sidebar
 * @sidebarObjId - The sidebar where this marker's label/name will be placed
 * @markerTab - The tabs and its contents for html information that will show
 * up in the information window	when the marker is clicked.
 */
 
function createMarker(point,name, nameTooltip, sidebarObjId, markerTab)
{
	// this variable will collect the html which will eventualkly be placed in the sidebar
	var sidebar_html = "";
	var marker = new GMarker(point);
	var tabs = [] ;
	
	GEvent.addListener(marker, "click", function(){
		marker.openInfoWindowTabsHtml(markerTab) ;
	});
		
	// save the info we need to use later for the sidebar
	RYE_MARKER.push(marker) ;
	RYE_MARKER_INFO.push(markerTab) ;
	RYE_MARKER_POINT.push(point) ;
	
	//create the innerHTML
	var sidebarHtml = '<li><a title = "' + nameTooltip + '" href = "javascript:displayMarker(' + RYE_MARKER_INDEX + ')">' + name + '</a></li>' ;
	// add a line to the sidebar html+ ', ' + marker +
//	document.getElementById("sidebar").innerHTML += '<a href="javascript:myclick(' + i + ', ' + point + ')">' + name + '</a><br>';
	document.getElementById(sidebarObjId).innerHTML += sidebarHtml ;
	RYE_MARKER_INDEX++;
	//return marker;
}

/**
 * This function will add the marker to the map using addOverlay
 * and set the center of the map to that point. After the html
 * info for that marker will be shown.
 */
function displayMarker(index)
{
	// remove anyother markers from the map
	RYE_MAP.clearOverlays() ;
	//set the center of the map to this marker by using the point of the marker
	//map.setCenter(RYE_MARKER_POINT[index]) ;
	//add the new marker to the map
	RYE_MAP.addOverlay(RYE_MARKER[index]);
	RYE_MARKER[index].openInfoWindowTabsHtml(RYE_MARKER_INFO[index]);
	//RYE_MARKER[index].openInfoWindowHtml(RYE_MARKER_INFO[index]);

}


function removeArrayContent(arrayObj)
{
	/*for(var i = arrayObj.length ; i >= 0 ; i--)
		arrayObj.pop() ;*/
		
	/*while(arrayObj.length > 0)
		arrayObj.pop() ;
	return arrayObj ;*/
	var tempArray = [] ;
	arrayObj = tempArray ;
	return tempArray ;
}

function getDirectionToHere(toObjectId)
{
	//get the parentNode whose innerHTML will be replaced
	var directionDiv = document.getElementById(toObjectId) ;
	var innerHTMLa = "<p class='directionNav'><span>Get Directions: </span><span>To Here</span> - <span><a href = 'javascript:getDirectionFromHere(this)'>From Here</a></span></p>" +
					"<p class='directionInstruction'>Start Address</p>";

	innerHTMLa += "<div class='directionForm'>" +
				 "<form action='http://maps.google.com/maps' method='get'>" +
				 "<input type='text' size=40 name='saddr' id='saddr' value=''/>" +
				 "<input type='submit' value='Go'/>" +
				 "</form></div>" ;

	innerHTMLa += "<p><span>&laquo; Back</span></p>" ;
	alert(directionDiv.innerHTML) ;
	directionDiv.innerHTML = innerHTMLa ;
	alert(directionDiv.innerHTML) ;
}

function zoomChanged(oldLevel, newLevel)
{
	//alert('Previous Zoom Level: ' + oldLevel + '\nNew Zoom Level: ' + newLevel) ;
	//get currently selected map type
	var currentMapType = RYE_MAP.getCurrentMapType() ;
	
	// if the new zoom is below 12, then display
	// a marker at ryerson location
	
	/*if(newLevel <= 12)
	{
		RYE_MAP.addOverlay(MAIN_MARKER) ;
	}
	if(newLevel > 12)
	{
		RYE_MAP.removeOverlay(MAIN_MARKER) ;
	}*/
	
	// change map type based on zoom level
	if(newLevel >= 15)
	{
		//change to RYE map type
		RYE_MAP.setCenter(new GLatLng(MAIN_LAT, MAIN_LNG), newLevel, P_RYE_MAP) ;
	}
	else if(newLevel < 15)
	{
		if(currentMapType == P_RYE_MAP)
		{
			//change it to normal map type by default ;
			currentMapType = G_NORMAL_MAP ;
		}

		RYE_MAP.setCenter(new GLatLng(MAIN_LAT, MAIN_LNG), newLevel, currentMapType) ; //G_NORMAL_MAP);
	}
	
	currentMapType = "" ;
}

function mapTypeChanged()
{
	//get currently selected map type
	var currentMapType = RYE_MAP.getCurrentMapType() ;
	// get current zoom level
	var currentZoomLevel = RYE_MAP.getZoom() ;
	alert(currentZoomLevel) ;
	/*if(currentZoomLevel < 16 && currentMapType != P_RYE_MAP)
	{
		//change to RYE map type
		RYE_MAP.setCenter(new GLatLng(MAIN_LAT, MAIN_LNG), 16, P_RYE_MAP) ;
	}*/
}