// Javascript written by Simon Hume of Stratford-on-Avon District Council.
// Elements of this code are written by:

	// function to get a tile given tile coords and zoom 

function TileToQuadKey ( tx,  ty,  zl){
	var quad;
	quad = "";
	for (var i = zl; i > 0; i--){
		var mask = 1 << (i - 1);
		var cell = 0;
		if ((tx & mask) != 0)
			cell++;
		if ((ty & mask) != 0)
			cell += 2;
		quad += cell;
		}
	return quad;
}
	

    if (GBrowserIsCompatible()) {
	  var gmarkers = [];
      var gicons = [];
	  var htmls = [];
	  var i = 0;
	  var to_htmls = [];
      var from_htmls = [];
	  
	  
	   // Create some custom icons
      
      // Declare variables for markers below
 
		var ParkingIcon = new GIcon();
		ParkingIcon.image = "http://www.stratford.gov.uk/mapping/icons/parking.png";
		ParkingIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		ParkingIcon.iconSize = new GSize(22, 26);
		ParkingIcon.shadowSize = new GSize(22, 20);
		ParkingIcon.iconAnchor = new GPoint(18, 26);
		ParkingIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var DistrictParkingIcon = new GIcon();
		DistrictParkingIcon.image = "http://www.stratford.gov.uk/mapping/icons/district.png";
		DistrictParkingIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		DistrictParkingIcon.iconSize = new GSize(22, 26);
		DistrictParkingIcon.shadowSize = new GSize(22, 20);
		DistrictParkingIcon.iconAnchor = new GPoint(18, 26);
		DistrictParkingIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var LeisureIcon = new GIcon();
		LeisureIcon.image = "http://www.stratford.gov.uk/mapping/icons/sports.png";
		LeisureIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		LeisureIcon.iconSize = new GSize(22, 26);
		LeisureIcon.shadowSize = new GSize(22, 20);
		LeisureIcon.iconAnchor = new GPoint(18, 26);
		LeisureIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var ToiletsIcon = new GIcon();
		ToiletsIcon.image = "http://www.stratford.gov.uk/mapping/icons/toilets.png";
		ToiletsIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		ToiletsIcon.iconSize = new GSize(22, 26);
		ToiletsIcon.shadowSize = new GSize(22, 20);
		ToiletsIcon.iconAnchor = new GPoint(18, 26);
		ToiletsIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var HospitalIcon = new GIcon();
		HospitalIcon.image = "http://www.stratford.gov.uk/mapping/icons/hospital.png";
		HospitalIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		HospitalIcon.iconSize = new GSize(22, 26);
		HospitalIcon.shadowSize = new GSize(22, 20);
		HospitalIcon.iconAnchor = new GPoint(18, 26);
		HospitalIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var SchoolIcon = new GIcon();
		SchoolIcon.image = "http://www.stratford.gov.uk/mapping/icons/school.png";
		SchoolIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		SchoolIcon.iconSize = new GSize(22, 26);
		SchoolIcon.shadowSize = new GSize(22, 20);
		SchoolIcon.iconAnchor = new GPoint(18, 26);
		SchoolIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var TaxiIcon = new GIcon();
		TaxiIcon.image = "http://www.stratford.gov.uk/mapping/icons/taxi.png";
		TaxiIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		TaxiIcon.iconSize = new GSize(22, 26);
		TaxiIcon.shadowSize = new GSize(22, 20);
		TaxiIcon.iconAnchor = new GPoint(18, 26);
		TaxiIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var BicycleIcon = new GIcon();
		BicycleIcon.image = "http://www.stratford.gov.uk/mapping/icons/bicycle.png";
		BicycleIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		BicycleIcon.iconSize = new GSize(22, 26);
		BicycleIcon.shadowSize = new GSize(22, 20);
		BicycleIcon.iconAnchor = new GPoint(18, 26);
		BicycleIcon.infoWindowAnchor = new GPoint(22, 0);
				
		var PitchIcon = new GIcon();
		PitchIcon.image = "http://www.stratford.gov.uk/mapping/icons/pitch.png";
		PitchIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		PitchIcon.iconSize = new GSize(22, 26);
		PitchIcon.shadowSize = new GSize(22, 20);
		PitchIcon.iconAnchor = new GPoint(18, 26);
		PitchIcon.infoWindowAnchor = new GPoint(22, 0);
				
		var TrainIcon = new GIcon();
		TrainIcon.image = "http://www.stratford.gov.uk/mapping/icons/train.png";
		TrainIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		TrainIcon.iconSize = new GSize(22, 26);
		TrainIcon.shadowSize = new GSize(22, 20);
		TrainIcon.iconAnchor = new GPoint(18, 26);
		TrainIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var TipIcon = new GIcon();
		TipIcon.image = "http://www.stratford.gov.uk/mapping/icons/tip.png";
		TipIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		TipIcon.iconSize = new GSize(22, 26);
		TipIcon.shadowSize = new GSize(22, 20);
		TipIcon.iconAnchor = new GPoint(18, 26);
		TipIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var RecycleIcon = new GIcon();
		RecycleIcon.image = "http://www.stratford.gov.uk/mapping/icons/recycle.png";
		RecycleIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		RecycleIcon.iconSize = new GSize(22, 26);
		RecycleIcon.shadowSize = new GSize(22, 20);
		RecycleIcon.iconAnchor = new GPoint(18, 26);
		RecycleIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var CouncilIcon = new GIcon();
		CouncilIcon.image = "http://www.stratford.gov.uk/mapping/icons/councilLARGE.png";
		CouncilIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		CouncilIcon.iconSize = new GSize(40, 47);
		CouncilIcon.shadowSize = new GSize(40, 20);
		CouncilIcon.iconAnchor = new GPoint(18, 47);
		CouncilIcon.infoWindowAnchor = new GPoint(22, 0);
		
		var YouTubeIcon = new GIcon();
		YouTubeIcon.image = "http://www.stratford.gov.uk/mapping/icons/youtubeLARGE.png";
		YouTubeIcon.shadow = "http://www.stratford.gov.uk/mapping/icons/shadow.png";
		YouTubeIcon.iconSize = new GSize(40, 47);
		YouTubeIcon.shadowSize = new GSize(40, 20);
		YouTubeIcon.iconAnchor = new GPoint(18, 47);
		YouTubeIcon.infoWindowAnchor = new GPoint(22, 0);
				
		
      
      // An array of GIcons, to make the selection easier
      var icons = [];
      icons["parking"] = ParkingIcon;
	  icons["districtparking"] = DistrictParkingIcon;
	  icons["leisure"] = LeisureIcon;
	  icons["toilets"] = ToiletsIcon;
	  icons["hospital"] = HospitalIcon;
	  icons["school"] = SchoolIcon;
	  icons["taxi"] = TaxiIcon;
	  icons["bicycle"] = BicycleIcon;
	  icons["pitch"] = PitchIcon;
	  icons["train"] = TrainIcon;
	  icons["tip"] = TipIcon;
	  icons["recycle"] = RecycleIcon;
	  icons["council"] = CouncilIcon;
	  icons["youtube"] = YouTubeIcon;
  


      // A function to create the marker and set up the event window
      //function createMarker(point,name,html,category) {
		  function createMarker(point,name,htmlnew,category) {
        var marker = new GMarker(point,icons[category]);
        // === Store the category and name info as a marker properties ===
        marker.mycategory = category;                                 
        marker.myname = name;
        GEvent.addListener(marker, "click", function() {
		// orginal code below
          //marker.openInfoWindowHtml(html);
		  // new code below
          marker.openInfoWindowHtml(htmlnew);
        });
        gmarkers.push(marker);
        return marker;
      }
	  

      // == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].show();
          }
        }
        // == check the checkbox ==
        document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].hide();
          }
        }
        // == clear the checkbox ==
        //commented this out to try and fix show/hide display                 document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        map.closeInfoWindow();
      }

      // == a checkbox has been clicked ==
      function boxclick(box,category) {
        if (box.checked) {
          show(category);
        } else {
          hide(category);
        }
        // == rebuild the side bar
        //makeSidebar();
      }

      function myclick(i) {
        GEvent.trigger(gmarkers[i],"click");
      }


	  
	  
	  // == rebuilds the sidebar to match the markers currently displayed (with thumbnail images) ==
      //function makeSidebar() {
        //var html = "";
			
		
        //for (var i=0; i<gmarkers.length; i++) {
          //if (!gmarkers[i].isHidden()) {
           // html += '<img src="icons/' + xxCate + '.png" alt="TBC" width="10" height="12" style="padding:0px 5px 0px 0px;"/><a href="javascript:myclick(' + i + ')"  class="quicklinks">' + gmarkers[i].myname + '</a><br />';

         // }
        //}
        //document.getElementById("side_bar").innerHTML = html;
      //}
	  
	  

      // create the map
		var map = new GMap2(document.getElementById("googlemap"));
		
		
		
		// District Map Outlines
	  var DistrictTiles = function (a,b) {			    
			var f = "http://www.stratford.gov.uk/mapping/tiles/district/" + TileToQuadKey(a.x,a.y,b) + ".png";
			return f;
		}
		
		function MapActiveonCheck(){
			
		
		// Adding the District overlay control to 'Map'
				
		var districtLayer;
		var districtHybridLayer;
		var districtSatMap;
		var districtMap;

		districtHybridLayer = new Array();
		districtHybridLayer[0] = G_NORMAL_MAP.getTileLayers()[0];
	    districtHybridLayer[1] = new GTileLayer(new GCopyrightCollection('') , 10, 15);
		districtHybridLayer[1].getTileUrl = DistrictTiles;
		districtHybridLayer[1].getCopyright = function(a,b) {return "Stratford on Avon District Council 2009";}; 
		districtHybridLayer[1].getOpacity = function () {return 0.7;};//opacity of the non transparent part
		if(navigator.userAgent.indexOf("MSIE") == -1)
		districtHybridLayer[1].isPng = function() {return true;};

	    districtSatMap = new GMapType(districtHybridLayer, 
		G_NORMAL_MAP.getProjection(), 'District',{errorMessage:"", alt:"District Boundaries"}); 
		districtSatMap.getTextColor = function() {return "#000000";};
		map.addMapType(districtSatMap); 

	    var Boundaries = new GHierarchicalMapTypeControl();
		Boundaries.addRelationship(G_NORMAL_MAP, districtSatMap , "Stratford-on-Avon District Boundaries");
		
		
		map.addControl(Boundaries);

		map.addControl(new GScaleControl());

		map.setMapType(districtSatMap);
		
	  }
		
	// ====== Restricting the range of Zoom Levels =====
      // Get the list of map types      
      var mt = map.getMapTypes();
      // Overwrite the getMinimumResolution() and getMaximumResolution() methods
      for (var i=0; i<mt.length; i++) {
        mt[i].getMinimumResolution = function() {return 10;}
        mt[i].getMaximumResolution = function() {return 19;}
      }
		
		

		//var mapLargeMapControl = new GLargeMapControl();
		var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(220,36));
		//map.addControl(mapLargeMapControl, topLeft);
		
		
		


		map.addMapType(G_PHYSICAL_MAP);
		// Toggle on/off Google Earth Plugin
		map.addMapType(G_SATELLITE_3D_MAP);
		
		// Map type 0= Map. 1=Sat. 2=Sat w/Labels. 3= Terrain.
		map.setCenter(new GLatLng(52.173932, -1.630096), 11,map.getMapTypes()[0]);
		
		var extLargeMapControl = new ExtLargeMapControl();
        map.addControl(extLargeMapControl, topLeft);

		map.enableScrollWheelZoom();

		// Add Traffic
		//map.addOverlay(new GTrafficOverlay());


		
		
	// ==== The "More..." control simply accepts a mouseover to reveal the "Layer" control ===

      function MoreControl() {}
      MoreControl.prototype = new GControl();

      MoreControl.prototype.initialize = function(map) {
        var container = document.createElement("div");
        container.style.border = "2px solid black";
        container.style.fontSize = "12px";
        container.style.fontFamily = "Arial, sans-serif";
        container.style.width="90px";
        container.style.backgroundColor = "#ffffff";
        container.innerHTML = "<center><b>More Layers<\/b><\/center>";
      
        map.getContainer().appendChild(container);
        
        GEvent.addDomListener(container, "mouseover", function() {
          map.addControl(layerControl);
        });
        
        
        return container;
      }
      
      MoreControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(275, 7));
      }


      
      // ==== The "Layer" control displays the "More..." plus the checkboxes ====
      // ==== The checkbox info is passed in the "opts" parameter ====

      function LayerControl(opts) {
        this.opts = opts;
      }
      LayerControl.prototype = new GControl();

      LayerControl.prototype.initialize = function(map) {
        var container = document.createElement("div");
        
        container.style.border = "2px solid black";
        container.style.fontSize = "12px";
        container.style.fontFamily = "Arial, sans-serif";
        container.style.width="90px";
        container.style.backgroundColor = "#ffffff";
        container.innerHTML = '<center><b>More Layers<\/b><\/center>';
        for (var i=0; i<this.opts.length; i++) {
          if (layers[i].Visible) {
            var c = 'checked';
          } else {
            var c = '';
          }
        
          container.innerHTML += '<input type="checkbox" onclick="toggleLayer('+i+')" ' +c+ ' /> '+this.opts[i]+'<br>';
        }
          
      
        map.getContainer().appendChild(container);
        
        // === This doesn't do what I want. It kills the control if I mouseover a checkbox ===
        // === If you know how to do this better, let me know ===

        //GEvent.addDomListener(container, "mouseout", function() {
        //  map.removeControl(layerControl);
        //});
        
        setTimeout("map.removeControl(layerControl)",5000);
        
        
        return container;
      }
      
      LayerControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(275, 7));
      }



      // ==== toggleLayer adds and removes the layers ====
      function toggleLayer(i) {
        if (layers[i].Visible) {
          layers[i].hide();
        } else {
          if(layers[i].Added) {
            layers[i].show();
          } else {
            map.addOverlay(layers[i]);
            layers[i].Added = true;
          }
        }
        layers[i].Visible = !layers[i].Visible;
      }
		

		      // ==== Create the GLayer()s, and set them  Visible=false Added=false ====
      // If you want a GLayer open by default, addOverlay() it and set it  Visible=true Added=true

      var layers = [];      
          layers[0] = new GLayer("org.wikipedia.en");
          layers[0].Visible = false;
          layers[0].Added = false;
          
          
          layers[1] = new GLayer("com.panoramio.all");
          layers[1].Visible = false;
          layers[1].Added = false;
		  
		  // Adds Traffic Layer to toggle in 'more options' box
		  
		  //com.youtube.all adds youtube videos!
		  
		  layers[2] = new GTrafficOverlay();
          layers[2].Visible = false;
          layers[2].Added = false;
		  
		  // Adds Flickr Feed
		layers[3] = new GGeoXml("http://api.flickr.com/services/feeds/geo/?g=484016@N23&lang=en-us&format=rss_200");
		layers[3].Visible = false;
		layers[3].Added = false;
		
		// Adds Webcams
		layers[4] = new GLayer("com.google.webcams");
		layers[4].Visible = false;
		layers[4].Added = false;
		
		  
		  

      
      // === Create the layerControl, but don't addControl() it ===
      // = Pass it an array of names for the checkboxes =
      var layerControl = new LayerControl(["Wikipedia", "Panoramio", "Traffic", "Flickr", "Webcams"]);

      // === Create the MoreControl(), and do addControl() it ===
      map.addControl(new MoreControl());
		
		
		

      // Read the data
      GDownloadUrl("xml/data.xml", function(doc) {
        var xmlDoc = GXml.parse(doc);
        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 address = markers[i].getAttribute("address");
          var name = markers[i].getAttribute("name");
          var html = markers[i].getAttribute("html");
		  var htmlnew = markers[i].getAttribute("name");
          var category = markers[i].getAttribute("category");

		  // create the marker new
          var marker = createMarker(point,name,html,category);
		  
          map.addOverlay(marker);
        }
		

        // == show or hide the categories initially ==
        hide("districtparking");
        hide("parking");
		hide("leisure");
		hide("comven");
		hide("hospital");
		hide("school");
		hide("toilets");
		hide("taxi");
		hide("bicycle");
		hide("pitch");
		hide("train");
		hide("tip");
		hide("recycle");
		hide("council");
		hide("youtube");

        // == create the initial sidebar ==
        //makeSidebar();
      });
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
