/* Participate Google maps file */

GoogleMaps = {};

GoogleMaps.map = '';

GoogleMaps.xmlFileName = 'at_download/xmlFile';

GoogleMaps.getSchoolData = function(schoolurl) {
    url = schoolurl + "/school_view_for_map";
    GDownloadUrl(url, function(data, responseCode) {
	    GoogleMaps.popup.innerHTML = data;
	});
};
    
GoogleMaps.showSchoolData = function(marker, schoolurl) {
    url = schoolurl + "/school_view_for_map";
    GDownloadUrl(url, function(data, responseCode) {
	    GoogleMaps.popup.innerHTML = data;
	    marker.openInfoWindow(GoogleMaps.popup);
	});
    //GoogleMaps.getSchoolData(schoolurl);
    //marker.openInfoWindow(GoogleMaps.popup);
};

GoogleMaps.createSchoolMarker = function(map, schoolurl, point) {
    var marker = new GMarker(point);
    GEvent.addListener(marker, 
		       "click", 
		       function() {
			   GoogleMaps.showSchoolData(marker, schoolurl);
		       });

    map.addOverlay(marker);
    return marker;
};

GoogleMaps.loadSchoolBrowser = function() {
    if (!GBrowserIsCompatible()) {
	return;
    }

    GoogleMaps.map = new GMap2(document.getElementById("map-holder"));

    GoogleMaps.popup = document.createElement('div');

    //map.addControl(new GSmallMapControl());
    GoogleMaps.map.addControl(new GLargeMapControl());
    //map.addControl(new GMapTypeControl());

    //Set the default position of the map -->
    rootpos = new GLatLng(51.454756, -2.606459)
    GoogleMaps.map.setCenter(rootpos, 6);

    GoogleMaps.map.enableContinuousZoom();
    GoogleMaps.map.continuousZoomEnabled();


    // Check current school
    school = document.getElementById('schoolurl');
    if (school) {
	GoogleMaps.schoolurl = school.value;
    } else {
	GoogleMaps.schoolurl = '';
    }

    // Load in the Schools data
    xml = "schools.xml"
    url = xml + '?time=' + (new Date()).getTime()
    GDownloadUrl(url, function(data, responseCode) {
	    var xml = GXml.parse(data);
	    var schools = xml.documentElement.getElementsByTagName("school");
	    for (var i = 0; i < schools.length; i++) {
		var point = new GLatLng(parseFloat(schools[i].getAttribute("lat")),
					parseFloat(schools[i].getAttribute("lng")));
		var url = schools[i].getAttribute("url");

		// Create the marker
		mk = GoogleMaps.createSchoolMarker(GoogleMaps.map,
						   url,
						   point);

		// Show the user's school automatically and center on it
		if (url == GoogleMaps.schoolurl) {
		    GoogleMaps.map.setCenter(point, 6);
		    GoogleMaps.showSchoolData(mk, url);
		}
	    }
	});
	
};

GoogleMaps.loadDataMap = function() {

    /* !! Taken from the ScienceScope website !!
       http://www.sciencescope.co.uk/JData3D_Maps/GoogleMapsExample1.htm
    */

    if (GBrowserIsCompatible()) {
	// arrays to hold copies of the markers and html used by the side_bar
	// because the function closure trick doesnt work there
	// ==== first part of the select box ===
	var select_html = '<select onChange="GoogleMaps.handleSelected(this)">' +
	'<option selected> - Select a Point - </option>';
	// =====================================
	var side_bar_html = "";
	var key_table_html= "";
	GoogleMaps.gmarkers = [];
	var htmls = [];
   	var i = 0;
	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(32,32);
	baseIcon.shadowSize=new GSize(56,32);
	baseIcon.iconAnchor=new GPoint(16,32);
	baseIcon.infoWindowAnchor=new GPoint(16,32);
	var startIcon = new GIcon(baseIcon, "http://www.sciencescope.co.uk/images/icon13green.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon13s.png");
	var endIcon   = new GIcon(baseIcon, "http://www.sciencescope.co.uk/images/icon13red.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon13s.png");

	startIcon.transparent = "http://www.sciencescope.co.uk/images/icon13green_trs.png";
	endIcon.transparent = "http://www.sciencescope.co.uk/images/icon13red_trs.png";

	// A function to create the marker and set up the event window
	function createMarker(point,name,html,iconX) {
	    // === marker with tooltip ===

	    var marker = new GMarker(point,{icon:iconX,title:name,clickable:true});
	    var gicon = marker.getIcon();
	    gicon.infoWindowAnchor=new GPoint(16,32);
	    GEvent.addListener(marker, "click", function() {
		    marker.openInfoWindowHtml(html);
		});
	    // save the info we need to use later for the side_bar
	    GoogleMaps.gmarkers[i] = marker;
	    htmls[i] = html;
	    // add a line to the side_bar html
	    side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
	    // ======= Add the entry to the select box =====
	    select_html += '<option> ' + name + '</option>';
	    // ==========================================================
	    i++;
	    return marker;
	}
	// A function to create the key header
	function createKeyTableHeader(Heading) {
	    key_table_html += '<table width="100%" cellspacing="0" cellpadding="0"><tr><td colspan="2"><p class="subheading">'+Heading+'</p></td></tr>';
	}

	// A function to create the key table Row
	function createKeyTableEntry(colourVal,unitAndValue) {
	    key_table_html +=	'<td bgcolor="'+colourVal+'" class="scale_colour">&nbsp;</td> <td>'+unitAndValue+'</td> </tr>';
	}
	// A function to create the key Footer
	function createKeyTableFooter() {
	    key_table_html += '</table>';
	}

	// This function picks up the click and opens the corresponding info window
	function myclick(i) {
	    GoogleMaps.gmarkers[i].openInfoWindowHtml(htmls[i]);
	}

	// Display the map, with some controls and set the initial location
	GoogleMaps.map = new GMap2(document.getElementById("data_map"));
	GoogleMaps.map.addControl(new GLargeMapControl());
	GoogleMaps.map.addControl(new GMapTypeControl());

	// Read the data from example4.xml

	var request = GXmlHttp.create();
	request.open("GET", 'at_download/xmlFile', true);
	request.onreadystatechange = function() {
	    if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
          	// ================================================
		// obtain the gMapPosition and loop through it
		var gMapPosition = xmlDoc.documentElement.getElementsByTagName("gMapPosition");
		for (var b = 0; b < gMapPosition.length; b++) {
		    // get any GMapPosition attributes
		    var latitude = parseFloat(gMapPosition[b].getAttribute("latitude"));
		    var longitude = parseFloat(gMapPosition[b].getAttribute("longitude"));
		    var zoom = parseFloat(gMapPosition[b].getAttribute("zoom"));
		    GoogleMaps.map.setCenter(new GLatLng(latitude,longitude), zoom);
		}
		// ================================================

		// 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);
		    var html = markers[i].getAttribute("html");
		    var label = markers[i].getAttribute("label");
		    // create the marker
		    if(i == 0){
			var marker = createMarker(point,label,html,startIcon);
			GoogleMaps.map.addOverlay(marker);
		    }
		    else if (i == markers.length-1){
			var marker = createMarker(point,label,html,endIcon);
			GoogleMaps.map.addOverlay(marker);
		    }
		    else{
			var marker = createMarker(point,label,html,null);
			GoogleMaps.map.addOverlay(marker);
			marker.hide();
		    }
		}
		// put the assembled side_bar_html contents into the side_bar div
		// document.getElementById("side_bar").innerHTML = side_bar_html;
 		select_html += '</select>';
		document.getElementById("selection").innerHTML = select_html;

		// ========= Now process the polylines ===========
		var lines = xmlDoc.documentElement.getElementsByTagName("line");
		// read each line
		for (var a = 0; a < lines.length; a++) {
		    // get any line attributes
		    var colour = lines[a].getAttribute("colour");
		    var width  = parseFloat(lines[a].getAttribute("width"));
		    // read each point on that line
		    var points = lines[a].getElementsByTagName("point");
		    var pts = [];
		    for (var i = 0; i < points.length; i++) {
			pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
					     parseFloat(points[i].getAttribute("lng")));
		    }
		    line = new GPolyline(pts,colour,width,1);
		    GoogleMaps.map.addOverlay(line);
		}
		// ========= Now process the keyColours ===========

		var keyColoursArray = xmlDoc.documentElement.getElementsByTagName("keycoloursArray");
		for (var c = 0; c < keyColoursArray.length; c++) {
		    var heading = keyColoursArray[c].getAttribute("heading");
		    createKeyTableHeader(heading);
		    var keycolour = keyColoursArray[c].getElementsByTagName("keycolour");
		    for (var d = 0; d < keycolour.length; d++) {
			var colourVal = keycolour[d].getAttribute("colourvalue")
			    var valueAndUnit = keycolour[d].getAttribute("valueAndUnit")
			    createKeyTableEntry(colourVal,valueAndUnit);
		    }
		    createKeyTableFooter();
		}
		// put the assembled key_table contents into the side_bar div
		document.getElementById("key_table").innerHTML = key_table_html;

		// ================================================
	    }
	}
	request.send(null);

    }

    // display a warning if the browser was not compatible
    else {
	alert("Sorry, the Google Maps API is not compatible with this browser");
    }

};

GoogleMaps.toggleBalloons = function() {
    if(document.getElementById("ToggleBalloons").value === "Show Markers"){
	
	document.getElementById("ToggleBalloons").value = "Hide Markers";
	for (var k = 0; k < GoogleMaps.gmarkers.length; k++) {
	    if(k == 0){}
	    else if( k == GoogleMaps.gmarkers.length-1){}
	    else
		GoogleMaps.map.addOverlay(GoogleMaps.gmarkers[k]);
	}
    }
    else {
	document.getElementById("ToggleBalloons").value = "Show Markers";
	for (var k = 0; k < GoogleMaps.gmarkers.length; k++) {
	    if(k == 0){}
	    else if( k == GoogleMaps.gmarkers.length-1){}
	    else {
		GoogleMaps.map.removeOverlay(GoogleMaps.gmarkers[k]);
	    }
	}
    }
};


GoogleMaps.handleSelected = function(opt) {
    
    // ======= This function handles selections from the select box ====
    // === If the dummy entry is selected, the info window is closed ==
    var i = opt.selectedIndex - 1;
    if (i > -1) {
	GEvent.trigger(GoogleMaps.gmarkers[i],"click");
    }
    else {
	GoogleMaps.map.closeInfoWindow();
    }
};

