//Google maps
/*Global variables*******/
var gmap = null;
//create http object
var request = GXmlHttp.create();
//start level,lat/lng and map 
var sZLevel = 11;
var sLat = 53.7;
var sLng = -2.5;
/*map type constants more info http://www.google.com/apis/maps/documentation/reference.html#GMapType
G_NORMAL_MAP 	This is the normal street map type.
G_SATELLITE_MAP 	This map type shows Google Earth satellite images.
G_HYBRID_MAP This map type shows transparent street maps over Google Earth satellite images.
*/
var sMapType = G_NORMAL_MAP;

//zoom level when select from drop down
var zLevel = 17;
//type of map when selected from drop down 
var mapType = G_SATELLITE_MAP; 

/*Loading data stuff*/
var loadingId = 'loading';//only change if 
var imgHolderId = 'img_holder';
//loading graphic
var loadingGraphic = 'graphics/loading.gif';
//loading transparent background
var loadingBackGround = 'loading_bk';

//arrays containing attributes, marker objects and latLng
var marker=[];
var attribute=[];
var	lat=[]; 
var lng=[];
var title=[];
/*XML DATA TYPES********
Example xml file 
<marker schid="14042" postcode="OL12 8SS" lat="53.648218" lng="-2.179168" schname="Whitworth Tonacliffe Primary School">
</marker>
*************************/
//defines the xml tag where marker data is stored as attributes <--Example above-->
var markerTag = 'marker';
//title for info bubble and list headings in cluster bubble <--Must be attribute of markerTag-->
var bubbleTitle = 'schname';
//attribute that contains latitude <--Must be attribute of markerTag-->
var latA = 'lat';
//lng attribute
var lngA = 'lng';
//item/marker id - you'll need to check for this in any php files that deal with ajax <-- if($_GET['schid']){//do php stuff}-->
var id = 'schid';  
//ajax url
var url = 'includes/school_details.xml.php';

//select box container id 
var selectId = 'side';

//google map container
var mapContainer = 'map_border';

//google map
var mapId = 'map';

//drop down - select box option default text -> This value will be the selected value in the select box
var dropDownTxt = 'Select an individual school';
 
	 
// ====== This function displays the tooltip ======
      // it can be called from an icon mousover
function showTooltip(title,marker){
    tooltip.innerHTML = '<h1 class="tooltip">'+title+'</h1>';
	var point=gmap.getCurrentMapType().getProjection().fromLatLngToPixel(gmap.fromDivPixelToLatLng(new GPoint(0,0),true),gmap.getZoom());
	var offset=gmap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),gmap.getZoom());
	var anchor =marker.getIcon().iconAnchor;
	var width= marker.getIcon().iconSize.width;
	var height= tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}


/***MAKE MARKERS DEPENDING ON WHAT IS SENT TO FUNCTION****************************************/
function gMapAjax(gets,marker){
	if(!gets) return false;
	if(!marker){
		//loading
		document.getElementById('loading').className = loadingBackGround;
		document.getElementById('img_holder').innerHTML = '<img src="'+loadingGraphic+'" />';
	   	buildMap();//build map 
	}
	if(gets.nodeType !== 1){//gets as a string 
		request.open("GET", url+'?'+gets+'&key=f140869e1af8fffabe9abe8a30f701b2b71c7850', true);
	}else{//gets as an object <a href="?key=val&key&val">get map details of xyx</a>
		//get url attributes
		var attributes = gets.getAttribute('href').split('?');
		request.open("GET", url+'?'+attributes[1]+'&key=f140869e1af8fffabe9abe8a30f701b2b71c7850', true);
	}	
	request.onreadystatechange = function(){
		if (request.readyState == 4){
			if(request.status == 200){
			//get xml document
			if(marker){//single marker 
				if(request.responseText){
					var xhtml = request.responseText;
				}else{
					var xhtml = 'Sorry but there is no data available.';
				}
				marker.openInfoWindow(xhtml);
			}else{
				//if(request.responseXML) //works in FF not IE
				//if(request.responseXML.documentElement) //works IE not FF
				/*Thought this would work, but it didn't : ( 
				if(request.responseXML || request.responseXML.documentElement){
					var xmlDoc = request.responseXML;
					feedMarkers(xmlDoc);
				}else{
					document.getElementById('loading').className = '';
					document.getElementById('img_holder').innerHTML = '';
					alert('No data could be found');
				}				
				*/
				//But the following works in IE and FF : ) 
				if(!request.responseXML || !request.responseXML.documentElement){
					document.getElementById('loading').className = '';
					document.getElementById('img_holder').innerHTML = '';
					alert('Sorry but there is no data available.');
				}else{
					var xmlDoc = request.responseXML;
					feedMarkers(xmlDoc);
				}
			}
		}
		}
	}	
	request.send(null);
}

//loop through xml data and feed data into createMarker() function
function feedMarkers(xmlDoc){
	//drop old select box
	var sNodeO = document.getElementById(selectId);
	if(sNodeO.firstChild){//check if an old select box exists
		//remove old box
		sNodeO.removeChild(sNodeO.firstChild);
	}
	//create select tag for drop down of links
	 sNode= document.createElement('select');
	 var xmlLine = xmlDoc.documentElement.getElementsByTagName(markerTag);
	 var lngAll = 0;//store all lng
	 var latAll = 0;//store all lat
	 //used to set zoom and centre the map so every marker can be seen 
	 var bounds= new GLatLngBounds();
	 var point; 
	 for (var i = 0; i < xmlLine.length; i++){
		//create marker
		createMarker(xmlLine[i]);
		//add lat and lng to bound 
		point = new GLatLng(parseFloat(xmlLine[i].getAttribute(latA)),parseFloat(xmlLine[i].getAttribute(lngA)));	
		bounds.extend(point);
	}
	//create start text node and option for select box and append to select tag
	var opNode = document.createElement('option');
	opNode.setAttribute('selected','selected');
	var txtNode = document.createTextNode(dropDownTxt);
	opNode.appendChild(txtNode);
	sNode.appendChild(opNode);
	//work out average zoomlevel and centre the map according to the markers and map size
	var boundszoom = gmap.getBoundsZoomLevel(bounds, gmap.getSize());
	gmap.setCenter(bounds.getCenter(), boundszoom);

	//add select with options box to page
	document.getElementById(selectId).appendChild(sNode);
	//remove loading image
	document.getElementById('loading').className = '';
	document.getElementById('img_holder').innerHTML = '';
}
//create marker
function createMarker(xmlLine){
	//create marker location
	var point = new GLatLng(parseFloat(xmlLine.getAttribute(latA)),parseFloat(xmlLine.getAttribute(lngA)));	
	//marker id
	var markerId = xmlLine.getAttribute(id);
	//create marker with tool tip
	//marker[markerId] = new GMarker(point,{title:xmlLine.getAttribute(bubbleTitle)});
	marker[markerId] = new GMarker(point);
	attribute[markerId] = id+'='+markerId;
	lat[markerId] = xmlLine.getAttribute(latA);
	lng[markerId] = xmlLine.getAttribute(lngA);
	var opNode = document.createElement('option');
	opNode.setAttribute('value',xmlLine.getAttribute(id));
	var txtNode = document.createTextNode(xmlLine.getAttribute(bubbleTitle));
	opNode.appendChild(txtNode);
	sNode.onchange=function(){//function to run when option selected 
		if(this.value === dropDownTxt) return false;//check initial/start option is selected, if so return false and stop rest of script
			gMapAjax(attribute[this.value],marker[this.value]);//get info for individual marker and open bubble
			//zoom and center to marker
			gmap.setCenter(new GLatLng(lat[this.value],lng[this.value]),zLevel,mapType);
	}		
	sNode.appendChild(opNode);
	//create info bubble on click	
	GEvent.addListener(marker[markerId],"click",function(){gMapAjax(attribute[markerId],marker[markerId]);});
	//create info bubble on rollover
	//GEvent.addListener(marker[markerId],"mouseover",function(){marker[markerId].openInfoWindow(title[markerId])});
	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker[markerId],"mouseover", function() {showTooltip(xmlLine.getAttribute(bubbleTitle),marker[markerId]);});        
    GEvent.addListener(marker[markerId],"mouseout", function() {tooltip.style.visibility="hidden"});        
	//create cluster with clusterList
	clusterer.AddMarker(marker[markerId],xmlLine.getAttribute(bubbleTitle));
}

//check browser
//create map and features 
function buildMap(){
	//check browser is capable
	if(GBrowserIsCompatible()){
		var attributes = [];
		var val = window.location.href.split('?');	
		if(val[1] != undefined || val[1] != null){
			var attributes = getUrlAttributes(val[1]);
			if(attributes['linktomap'] != undefined || attributes['linktomap'] != null){
				//insert map
				document.getElementById(mapContainer).innerHTML = '<div id="'+mapId+'"></div>';				
			}
		}
		//create map object 
		if(document.getElementById(mapId)){	
			//====== set up marker mouseover tooltip div ======
			tooltip = document.createElement("div");			
			//build map
			gmap = new GMap2(document.getElementById(mapId));
			//add controles for pan/zooming 
			gmap.addControl(new GSmallMapControl());
			//add switch option for map/satellite
			gmap.addControl(new GMapTypeControl());
			//collapsible overview small map in corner
			//gmap.addControl(new GOverviewMapControl(new GSize(100,100)));		
			//sort out lat/lng and zoom level
			if(attributes['linktomap'] == undefined || attributes['linktomap'] == null){
			//sort out lat/lng and zoom level
			gmap.setCenter(new GLatLng(sLat,sLng),sZLevel,sMapType);
			//append tooltip div to map object
			gmap.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
			//hide tooltip div
			tooltip.style.visibility="hidden";
			//create the clusterer
			clusterer = new Clusterer(gmap);
			}else{//zoom into single marker
			gmap.setCenter(new GLatLng(attributes['lat'],attributes['lng']),zLevel,mapType);	
			//create marker object 
			var point = new GLatLng(parseFloat(attributes['lat']),parseFloat(attributes['lng']));
			var marker = new GMarker(point);
			gMapAjax(id+'='+attributes[id],marker);
			gmap.addOverlay(marker);
			}
		}
	}else{	
		alert("Sorry, your brower cannot handle this");		
	}
}
/*addLoadEvent*/
addLoadEvent(buildMap);
window.onunload = GUnload;
