
var gmarkers=[];
var map;
var request;
var cluster;

// used to update the view with number of items displayed
var counts = {};
var totalItems;
var totalOnMap;
var count = 0;

// themes
var themes = new Array();

if( typeof(siteBaseUrl)=='undefined' ) {
	var siteBaseUrl = '';
}

/* Set this up to specify what colours the markers may use */
var availableColours = new Array("red");

/* Used during map/marker generation */
var usedColours = new Array();
var icons = new Array();

var baseIcon = new GIcon();
baseIcon.image = siteBaseUrl+"/site/i/pins/pin.png";
baseIcon.shadow = siteBaseUrl+"/site/i/pins/shadow.png";
//baseIcon.iconSize = new GSize(30,30); // GSize(13, 41);
baseIcon.iconSize = new GSize(13,41); 
baseIcon.iconAnchor = new GPoint(1, 39); /// reference point of pin
baseIcon.shadowSize = new GSize(37, 41);
baseIcon.infoWindowAnchor = new GPoint(5, 1);
//baseIcon.imageMap = [4,0,  0,4,  0,7,  3,11,  4,19,  7,19,  8,11,  11,7,  11,4,  7,0]; 
baseIcon.transparent = siteBaseUrl+"/site/i/pins/mm_20_transparent.png";
var icons=[];

var themesShowing = [];

var cumulatives = [];

function Markers(color){
	
map.getInfoWindow().hide() 
 /*  if (document.getElementById('theme_'+color).checked==false) { 
      for (var i=0;i<gmarkers.length;i++) {
         if (gmarkers[i].type==color)  {
      //      map.removeOverlay(gmarkers[i]);
         }
      }
      
     if(typeof(counts[color]) != "undefined"){
      		totalOnMap = totalOnMap - counts[color];
      		
//      		updateTotal(totalOnMap);
     }
      
      
   } else { // show the marker again
      for (var i=0;i<gmarkers.length;i++) {
         if (gmarkers[i].type==color)  {
    //        map.addOverlay(gmarkers[i]);
         }
      }
      
      
       if(typeof(counts[color]) != "undefined"){
       		totalOnMap = totalOnMap + counts[color];
       		
//       		updateTotal(totalOnMap);
       }
   }
   */

    themesShowing[color] = !themesShowing[color];
   
	processXML();

}


function getIcon( id ) {

	var defaultColour = "red";
	var randEle = -1;
	var attempts = 0;
	var maxAttempts = 11;
	
	if (!icons[id]) {
		
		do {
			randEle = Math.floor(Math.random() * (availableColours.length));
			attempts++;
			if( attempts>=maxAttempts) {
				break;
			}
		} while( 	(availableColours[randEle]=='undefined' ) && 
					(usedColours[randEle]!='undefined' ) );
		
		if( availableColours[randEle]!='undefined' ) {
			usedColours[ randEle ] = 1;
			
			var icon = new GIcon(baseIcon);
			icon.image = siteBaseUrl+"/site/i/pins/mm_20_"+ availableColours[randEle] +".png";
			icons[ availableColours[randEle] ]=icon
			return icons[ availableColours[randEle] ];
		}
		
	}
}



function addMarker(lng, lat, html, theme, img, category, story) {

   var point = new GLatLng(lat, lng);   
   var icon = new GIcon(baseIcon);
   icon.image = siteBaseUrl+"/site/i/pins/pin.png";
   
   if (icon) {
	   	var marker = new GMarker(point, icon);
	   	gmarkers.push(marker);
	   	
	   	marker.type = theme;
	   	GEvent.addListener(marker, "click", function(){		
		
//			text = "<div class='map-bubble'><div class='img' style='background-image:url(i/" + img + ");'></div><h4>" + story + "</h4><h5>" + category + "</h5><p>" + html + "</p></div>";
			marker.openInfoWindowHtml(html);
		});
		
		
//		console.log(marker.type);
		
		// if there's a theme in querystring, only add the overlay for that theme
		var qStr = new Querystring();
		var qStrTheme = qStr.get('theme');

		if(qStrTheme == null || themes[marker.type] == qStrTheme) {
			
		//	map.addOverlay(marker);

			count++;
			
			totalOnMap = count;
			
//			console.log("counting " + totalOnMap);
			
//			updateTotal();
		}
	}
	else {
		alert('Failed to generate marker!');
	}
}


function processXML() { 
   if (request.readyState == 4) {
      if (request.status != 200) {
        // alert("file not found:"+request.status);
         //return;
      }

      var xmlDoc = request.responseXML;
		if (!xmlDoc) {
			alert('We could not load map data at this time, please try again later.')
			return;
		}
		else {
			
			gmarkers=[];

			cumulatives = [];

			markers = xmlDoc.documentElement.getElementsByTagName("marker");
			
			totalItems = markers.length;
			totalOnMap = markers.length;
//			updateTotal();
			
			for (var i=0; i < markers.length; i++) {
			
				var theme = markers[i].getElementsByTagName("theme")[0];
				var themeId = GXml.value(theme);

				if (themesShowing[themeId] == null)
				{
					themesShowing[themeId] = true;
				}

				if (themesShowing[themeId])
				{

					var y = GXml.value(markers[i].getElementsByTagName("lat")[0]);

					if(typeof(cumulatives[y]) != "undefined")
					{
						 cumulatives[y] ++;
					} else {

						 cumulatives[y] = 1;
					}


				
					addMarker(
						parseFloat(GXml.value(markers[i].getElementsByTagName("long")[0])),
						parseFloat(y),
						GXml.value(markers[i].getElementsByTagName("html")[0]),
						GXml.value(markers[i].getElementsByTagName("theme")[0]),
						GXml.value(markers[i].getElementsByTagName("category")[0]),
						GXml.value(markers[i].getElementsByTagName("story")[0])
					);

					if(typeof(counts[themeId]) != "undefined"){
						//console.log("its set, adding" + themeId);
						counts[themeId]++;
					}else{
						//console.log("not set")
						counts[themeId] = 1;
					}
				}
			}
			
		}

		cluster.removeMarkers();
			
		cluster.addMarkers(gmarkers);
		
		cluster.refresh(true);
   
   }
} 			  


function makeMap( domElement, xmlLocation ) {
	
	if( GBrowserIsCompatible ) {

		/* Handles the querystring, if there is one. */
		var qStr = new Querystring();
		var qStrLat = qStr.get('lat');
		var qStrLong = qStr.get('long');
		var qStrZoom = qStr.get('zoom');
		var qStrTheme = qStr.get('theme');
		
		if(qStrTheme!=null) {

			// get array key for the value at qStrTheme to give us the id of the checkbox to check
			for ( themeId in themes ) {
				
				if(themes[themeId] == qStrTheme){
					
					$("#form1").unCheckCheckboxes(":not(#theme_"+themeId+")");
					
				}

			}
			
		}
		
		if( (qStrLat!=null) && (qStrLong!=null)  ) {
			if( qStrZoom==null ) {
				qStrZoom = 6; // default zoom level
			}
			map = new GMap(document.getElementById( domElement ));
			map.addControl(new GLargeMapControl());
			/* We get strings off the querystring, so we need to make 'em real numbers... */
			map.setCenter(new GLatLng( parseFloat(qStrLat), parseFloat(qStrLong) ), parseInt(qStrZoom) );
			reCentre = false;
			
			map.setMapType(G_PHYSICAL_MAP);
			
		}
		else {
			map = new GMap(document.getElementById( domElement ));
			map.addControl(new GLargeMapControl());
			map.setCenter(new GLatLng(54.30000, -3.97729), 6);
			reCentre = true;
			
			map.setMapType(G_PHYSICAL_MAP);
		}
		
		cluster=new ClusterMarker(map, { markers:gmarkers } );
		
		cluster.intersectPadding=-2;

		request = GXmlHttp.create(); 
		request.open("GET", xmlLocation, true); 
		request.onreadystatechange = processXML;
		request.send(null);
   }
   else {
		document.getElementById( domElement ).innerHTML='Unfortunately, your browser is not compatible with this page. This page requires a modern, Javascript-enabled browser. We recommend using <a href="http://www.getfirefox.com">Mozilla Firefox 2</a>, <a href="http://www.microsoft.com/windows/ie">Internet Explorer 7</a>, or better.';
   }
   
}	


function updateTotal(){
	
	document.getElementById("storycount").innerHTML = "showing (" + totalOnMap + " of " + totalItems + ")";
	
}

function populateThemes(){
	
	// get all lis within div.stories
	var lis = $("div.stories li");
	
	// index themes array by check box ids
	
	lis.each(function() { 
		
		// convert the li vals to lower and remove spaces e.g.
		var text = $(this).text().toLowerCase().replace(/ /g, "");
		
		// get the numeric id
		var id = $(this).find("input").attr("id").substr(6);
		
		themes[id] = text;
	});
	
	
}

populateThemes();

makeMap('map_display',siteBaseUrl+'/gmapxml_all.xml');


