var map, polyLayer ;
var gmarkers= [] ;

//img preload
img0 = new Image(); img0.src = "images/nav/nav_nz.png";
img1 = new Image(); img1.src = "images/nav/nav_nor.png";
img2 = new Image(); img2.src = "images/nav/nav_auk.png";
img3 = new Image(); img3.src = "images/nav/nav_wai.png";
img4 = new Image(); img4.src = "images/nav/nav_eco.png";
img5 = new Image(); img5.src = "images/nav/nav_haw.png";
img6 = new Image(); img6.src = "images/nav/nav_tar.png";
img7 = new Image(); img7.src = "images/nav/nav_wel.png";
img8 = new Image(); img8.src = "images/nav/nav_nel.png";
img9 = new Image(); img9.src = "images/nav/nav_can.png";
img10 = new Image(); img10.src = "images/nav/nav_ota.png";
img11 = new Image(); img11.src = "images/nav/nav_sth.png";

function FlipImg(imgName,imgSrc) {
	eval('document.'+imgName+'.src = '+imgSrc);
return true;
}

function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(-41.0, 173.0), 5);
		
		var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,30));		
		map.addControl(new GSmallMapControl(), topLeft);
		
		map.addControl(new GMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		map.enableScrollWheelZoom();
		//map.addControl(new GScaleControl());
		
		showHide('mymenu1'); //show the navigation div
		// Create custom icon
	    var icon = new GIcon();
	    icon.shadow = "images/icons/shield_shadow.png";
	    icon.iconSize = new GSize(25, 25);
	    icon.shadowSize = new GSize(37, 25);
	    icon.iconAnchor = new GPoint(12, 24);
	    icon.infoWindowAnchor = new GPoint(12, 4);
		icon.transparent = "images/icons/transp.png";
		
		//download xml data
		GDownloadUrl("./include/wed_data.xml", function(data) {
			var xml = GXml.parse(data);
			tags = new Array();
			
			var markers = xml.documentElement.getElementsByTagName("marker");
			var bounds = new GLatLngBounds();
			
			for (var i = 0; i < markers.length; i++)
				{
				var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
					parseFloat(markers[i].getAttribute("lng")));
				
				//retrieve names and coords
				var strName = markers[i].getAttribute("plcName");
				var strTabs = GXml.value(markers[i].getElementsByTagName("tabs")[0]);
				var strHTML = GXml.value(markers[i].getElementsByTagName("html")[0]);
				//assign the marker an image
				icon.image = "images/icons/" + markers[i].getAttribute("org") + ".png";
				//create tabbed marker with the point, icon and marker xml details
				var marker = CreateTabbedMarker(latlng, eval(strHTML), eval(strTabs), icon, markers[i]);
				bounds.extend(latlng);
				map.addOverlay(marker);
				}
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
			
			CustomNav() ;
			
			//hack to get the stupid poly stuff working
			a = new GLatLng(0,0);b = new GLatLng(1,0);c = new GLatLng(0,1);
			polyLayer1 = new GPolygon([a,b,c,a], "#ffffff", 2, 0, "#ffffff", 0);
			map.addOverlay(polyLayer1);
			polyLayer2 = new GPolygon([a,b,c,a], "#ffffff", 2, 0, "#ffffff", 0);
			map.addOverlay(polyLayer2);
			
			});		
		}
    }

function CustomNav() {
	// create custom navigation object
      var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,30));
      pos.apply(document.getElementById("control"));
      map.getContainer().appendChild(document.getElementById("control"));
	  var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0,15));
      pos.apply(document.getElementById("logo_plant"));
      map.getContainer().appendChild(document.getElementById("logo_plant"));
}

//global var
menu_status = new Array();
function showHide(theid){
    if (document.getElementById) {
    var switch_id = document.getElementById(theid);

        if(menu_status[theid] != 'show') {
           switch_id.className = 'show';
           menu_status[theid] = 'show';
        }else{
           switch_id.className = 'hide';
           menu_status[theid] = 'hide';
        }
    }
}
	
// A function to create a tabbed marker and set up the event window
// This version accepts a variable number of tab headings, passed in the arrays htmls[ ... ] and labels[ ... ]
 function CreateTabbedMarker(point, htmls, labels, theIcon, mkrInfo) {
		//get attributes from xml
		var siteName = mkrInfo.getAttribute("plcName");
		var org = mkrInfo.getAttribute("org");
		var box = mkrInfo.getAttribute("box");
		var uri = mkrInfo.getAttribute("uri");		
        var marker = new GMarker(point, {title:siteName,icon:theIcon});
		//set the marker category
		marker.cat = mkrInfo.getAttribute("cats");
		 //  ======  The new marker "mouseover"  listeners  ======
        GEvent.addListener(marker,"mouseover", function() {
			if (box.length > 0)
				{DrawBox(box);}
        });
		//infowindow listener
        GEvent.addListener(marker, "click", function() {
          // adjust the width so that the info window is large enough for this many tabs
          if (htmls.length > 2) {
            htmls[0] = '<div style="width:'+htmls.length*88+'px">' + htmls[0] + '</div>';
          }
          var tabs = [];
          for (var i=0; i<htmls.length; i++) {
			
			// assemble onclick zoom to site command			
			ptLat = parseFloat(mkrInfo.getAttribute("lat"));
			ptLng = parseFloat(mkrInfo.getAttribute("lng"));
			if (box.length > 1) //if the box atttribute has coors
				{
				box+= "," + eval(ptLat + 0.02) + "," + ptLng + "," + eval(ptLat - 0.003) + "," + ptLng;;
				siteClick = 'onclick=\'ZoomTo("' + box + '",2)\' ';
				var box2 = box;
				box2+= "," + eval(ptLat + 0.25) + "," + ptLng + "," + eval(ptLat - 0.1) + "," + ptLng;
				regionClick = 'onclick=\'ZoomTo("' + box2 + '",1)\' ';
				}
			else //if there is only a point
				{
				var ptSite = ptLat + ',' + ptLng;
				ptSite+= "," + eval(ptLat + 0.015) + "," + ptLng + "," + eval(ptLat - 0.007) + "," + ptLng;
				siteClick = 'onclick=\'ZoomTo("' + ptSite + '",2)\' ';
				ptSite2 = ptSite;
				ptSite2+= "," + eval(ptLat + 0.25) + "," + ptLng + "," + eval(ptLat - 0.1) + "," + ptLng;
				regionClick = 'onclick=\'ZoomTo("' + ptSite2 + '",1)\' ';}
			
			//create each page content with site-specific header info - switch base on org attribute
			var strHeadTag = '_info.gif" width="20" height="20" hspace="5" border="0" align="absmiddle" '
			switch(org)
				{case "lc":
					logoHTML = '<h2><a href="http://www.landcareresearch.co.nz" target="_blank" >' 
					+ '<img src="images/icons/lc' + strHeadTag + 'alt="Go to Landcare Research site" /></a>' + siteName + '</h2>';
					break;					
				case "qe":
					logoHTML = '<h2><a href="http://www.openspace.org.nz" target="_blank" >'
					+ '<img src="images/icons/qe' + strHeadTag + 'alt="Go to QEII National Trust site" /></a>' + siteName + '</h2>';
					+ '<img src="images/icons/qe_info.gif" border="0"/></a>&nbsp;' + siteName + '</h2>';
					break;
				default:
					logoHTML = '<h2><img src="images/icons/' + org + '_info.gif"  border="0"  />&nbsp;' + siteName + '</h2>';
					;
				}
			logoHTML += '<p class="footer"><a href="#"' + siteClick + '>Show me the site</a>' //site zoom
				+ ' | <a href="#"' + regionClick + '>How do I get there?</a>' //region zoom
				+ ' | <a href="#" onclick=\'ZoomTo("-34.5,167.7,-47.3,178.5");map.closeInfoWindow()\'>Start over</a></p>' //national zoom
			
			//create the footer for each infowindow - this is the 'read more' link and the 'zoom to site | region | NZ' stuff
			if (uri.length > 7)  //if the link is longer than 7 chars (e.g. http://...) add a link
				{footer = '<p class="footer"><a href="' + uri + '" target="_blank">Read more</a></p>';}
			else //don't put one in
				{footer = "";}		
			tabs.push(new GInfoWindowTab(labels[i], logoHTML + htmls[i] + footer));
          }
          marker.openInfoWindowTabsHtml(tabs,{maxWidth:400});
        });
		
		//push the marker into gmarkers array
		gmarkers.push(marker);
        return marker;
      }
	
 function ZoomTo(strCoors,sat) {
	var bounds = new GLatLngBounds();
	//split the input string
	coors = strCoors.split(",");
	//loop through the coordinate pairs in multiples of 2
	for (var i = 0; i < coors.length; i=i+2)
		{//extract point pairs and add to bounds
		pt = new GLatLng(coors[i],coors[i+1]);
		bounds.extend(pt);
		}
	map.setZoom(map.getBoundsZoomLevel(bounds)); //set new bounds and centre
	map.setCenter(bounds.getCenter());		
	map.setMapType(G_PHYSICAL_MAP);	//if specified set map type
	if (sat == 1)
		{map.setMapType(G_NORMAL_MAP);}
	if (sat == 2)
		{map.setMapType(G_SATELLITE_MAP);}
	}

function DrawBox(box) {		
	map.removeOverlay(polyLayer1); map.removeOverlay(polyLayer2);//remove exisiting boxes
	//split the box into array of coordinates
	arrBox = box.split(",");	
	//establish  site box coordinates
	ul = new GLatLng(arrBox[0],arrBox[1]);	ur = new GLatLng(arrBox[0],arrBox[3]);
	lr = new GLatLng(arrBox[2],arrBox[3]);	ll = new GLatLng(arrBox[2],arrBox[1]);	
	//add site box (outline color, width, o_opacity, fill color, f_opacity)
	polyLayer1 = new GPolygon([ul,ur,lr,ll,ul], "#343526", 5, .3, "#ffffff", 0); 
		map.addOverlay(polyLayer1);
	polyLayer2 = new GPolygon([ul,ur,lr,ll,ul], "#ffffff", 2, .8, "#ffffff", 0.05); //385409
		map.addOverlay(polyLayer2);		
	}
	
function ZoomSite(lat1,lng1,lat2,lng2,topMargin,mapType) {
	var bounds = new GLatLngBounds();	
	
	//establish  upper-left/lower-right coordinates - I THINK THESE ARE THE WRONG WAY ROUND. CHECK!!!
	var low = new GLatLng((lat2 -(topMargin*.2)),lng1);
	var top = new GLatLng((lat1 +topMargin),lng2);
	//set boundary extents
	bounds.extend(top);
	bounds.extend(low);
	//zoom the map to these boundaries
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());	
	switch(mapType)
		{case 1:
			map.setMapType(G_NORMAL_MAP);
			//map.removeOverlay(polyLayer);
			break;
		case 2:
			map.setMapType(G_SATELLITE_MAP);
			break;
		case 3:
			map.setMapType(G_HYBRID_MAP);			
			break;
		default:
			;
		}	
	}
	
      // == 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].cat == category) {
            gmarkers[i].show();
          }
        }
        // == check the checkbox ==
        document.getElementById("chk" +category).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].cat == category) {
            gmarkers[i].hide();
          }
        }
        // == clear the checkbox ==
        document.getElementById("chk" +category).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);
        }	  
      }