//<![CDATA[
    
if (GBrowserIsCompatible()) { 

	var addressLocality = ", Queensland";

	var map;
	var bounds;
	var centerPoint = new GLatLng(-20, 145); // initial center point for QLD map
	var oZoom = 5; // initial zoom for QLD map
	var geo;
	var reasons=[];

	var normalProj = G_NORMAL_MAP.getProjection();	

	var siteUrl = "http://www.ecq.qld.gov.au/elections/state/state2008/redistributions/finalReport/";
	var semsUrl = "http://www.ecq.qld.gov.au/elections/local/lg2008/";
	var thisKml = thisDiv.replace(/ /g, "_");
	var thisLink = thisDiv.replace(/ /g, "");
	var kmlPath_boundary = siteUrl + "kml_final/" + thisKml + ".kml?" + Math.random();
	var localPath_boundary = siteUrl + "kml_final/" + thisKml + ".kml";
	var xmlPath_exist;
	var xmlPath_local;
	//read xml data and store them in the following variables
	//var xmlPath = siteUrl + "data/divisionMBRS.xml";
	var xmlPath = siteUrl + "data/thisDivision.xml?" + Math.random();
	var pdfUrl = "../PDFmaps/A4 " + thisDiv + ".pdf";
	var reportUrl = "../reports/" + thisDiv + ".pdf";
	var districtName=[];
	var distName=[];
	var maxLat=[];
	var maxLng=[];
	var minLat=[];
	var minLng=[];
	var sw=[];
	var ne=[];
	var kmlName=[];
	var pdfName=[];
	var kmlLabel=[];
	var pdfLabel=[];
	var kmlBooth=[]; 
	var semsName=[];
	var sName=[];
	var semsDir=[];
	var semsDiv=[];
	var semsLink=[];
	var Qkml;
	var QkmlPath = siteUrl + "kml/Queensland.KML";
	var existDiv=[];
	var affectedDiv=[];
	var affectedLength;
	
	var kmlOverlay=[];
	var chkID=[];
	
//	var linkMain = '<a href="http://www.ecq.qld.gov.au/elections/2008/info.html">Back to Information Page</a><br />';
//	var linkInfo = '<a href="http://www.ecq.qld.gov.au/elections/2008/mainindex.html">Go to Main Index Page</a><br />';
	var linkMain = '<a href="../refPage.html">Back to Information Page</a><br />';
	var linkInfo = '<a href="../indexPage.html">Go to Main Index Page</a><br />';
	var linkSmap = '<a href="' + pdfUrl + '" target="_blank">' + thisDiv + ' PDF map</a><br />';
	var linkReport = '<a href="' + reportUrl + '">' + thisDiv +  " Report" + '</a>';
	var linkTitle;
	var linkSpace = '<p></p>';
	var siteLinks;
	var colourCode="";

	var marker = null;
//	var Pmarker;
	var Mmarker=[];
	var points=[];
	var dataLength;
	var Lpp;	//number of polling places
	var Lpolygon;	//number of polygons
	var Lcoords=[];	//number of coordinates in a polygon
	var Ppoints;	//polygon points
	var counter;
	var kml;
	var kml_pp;
	var icon = new GIcon();
	var ctLabel = new GIcon();; //Charters Towers
	var ctMarker;
	
    // this variable will collect the html which will eventually be placed in the Polling Places List
    var pollingPlaces_html = "";
    
    // arrays to hold copies of the markers used by the Polling Places because the function closure trick doesnt work there
	var htmls = [];
	var names = [];
	var imgLinks =[];
	var i = 0;
	var j = 0;
	
	var bar = 0;
	
    function load() {
		bounds = new GLatLngBounds(minLatLng, maxLatLng);
		map = new GMap2(document.getElementById("map"));
		map.enableDoubleClickZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP); 
		map.addControl(new GScaleControl());
		map.addControl(new GOverviewMapControl());
		
		centerPoint = bounds.getCenter();
		oZoom = map.getBoundsZoomLevel(bounds); //map zoom
    	map.setCenter(centerPoint,oZoom); //map centre
		//kml = new GGeoXml(kmlPath_boundary);
		//map.addOverlay(kml); //Add kml overlay
      
      // ====== Create a Client Geocoder ======
      geo = new GClientGeocoder(); 
	  
      // ====== Array for decoding the failure codes ======
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

	ctLabel.image = "../images/charters_towers.png";
	ctLabel.iconSize = new GSize(53,28);
	ctLabel.iconAnchor = new GPoint(26,5);
	
	  initData();
	  boundaryData();
	}
				
	function initData() {
	  siteLinks = linkInfo + linkMain + linkSmap + linkSpace;
	  document.getElementById("links").innerHTML = siteLinks + linkSpace;
      // Read council/division/ward information from districtMBR.xml
      var request = GXmlHttp.create();
      request.open("GET", xmlPath, true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
         var xmlDoc = GXml.parse(request.responseText);
         // obtain the array of markers and loop through it
         var placeMark = xmlDoc.documentElement.getElementsByTagName("marker");
		 var myDiv=[];
		 dataLength = placeMark.length;
         for (var i = 0; i < dataLength; i++) {
            // obtain the attribues of each marker
            maxLat[i] = parseFloat(placeMark[i].getAttribute("maxlat"));
            maxLng[i] = parseFloat(placeMark[i].getAttribute("maxlng"));
            minLat[i] = parseFloat(placeMark[i].getAttribute("minlat"));
            minLng[i] = parseFloat(placeMark[i].getAttribute("minlng"));
			semsDiv[i] = placeMark[i].getAttribute("Division");
			myDiv[i] = placeMark[i].getAttribute("Divs");
			if (thisDiv == semsDiv[i]) {
				existDiv = myDiv[i].split(",");
				i = dataLength;
			}
		 }
		//load proposed and existing divisions boundaries
		var kmlExist=[];
		var listExist = "";
		for(var j = 0; j < existDiv.length; j++) {
			kmlExist[j] = existDiv[j].replace(/ /g, "_"); // kml names
			chkID[j] = "chk" + j;
			kmlOverlay[j] = new GGeoXml(siteUrl + "kml_previous/" + kmlExist[j] + ".kml");
			listExist += '<label><input name="checkbox2" type="checkbox" id="' + chkID[j] + '" onclick="selectMap('+j+')" />' +  existDiv[j] + '</label><br />';
		 }
         document.getElementById("existing").innerHTML = "<span class=" + "heading2" + "><strong>1999 Redistribution</strong>" + "</span><br />" + listExist + '<br /><hr width="90%" />';
		//kmlPath_boundary = siteUrl + "kml_final/" + kmlLabel[i] + ".kml";
		var p = 9; //assign index to proposed division to call "selectMap(p)". It could be any number as long as it is outside affectedDiv[i].length
	ctMarker = new GMarker(new GLatLng(-20.077722, 146.259403), ctLabel); // Marker for Charters Towers
	map.addOverlay(ctMarker);
		kmlOverlay[p] =  new GGeoXml(kmlPath_boundary);
		map.addOverlay(kmlOverlay[p]);
		document.getElementById("proposed").innerHTML = "<span class=" + "heading2" + "><strong>2008 Redistribution</strong>" + "</span><br />" + '<label><input name="checkbox1" type="checkbox" id="' + chkID[p] + '" checked="checked" onclick="selectMap('+p+')" />' +  thisDiv + '</label><br /><br /><hr width="90%" /><br />';
		colourCode += "<span class=" + "heading2" + "><strong>Colour Code</strong>" + "</span><br />";
		colourCode += '<label><img src="../images/red.png" alt="2008 Electoral District" width="15" height="15" hspace="3" /></label>2008 Electoral District<br />';
		colourCode += '<img src="../images/blue.png" alt="1999 Electoral Districts" width="15" height="15" hspace="3" />1999 Electoral District(s)<br />';
		colourCode += '<img src="../images/redblue.png" alt="Overlapping Area" width="15" height="15" hspace="3" />Overlapping Area </p>';
		document.getElementById("info").innerHTML = colourCode;
		}
	  }
	  request.send(null);
	}
	
	function boundaryData(){
      // Read the boundary coordinates data file
	  Ppoints=new Array();
      var request = GXmlHttp.create();
      request.open("GET", kmlPath_boundary, false);
	  //document.getElementById("existing").innerHTML += kmlPath_boundary + '<br />'; //?????? why read??
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
         var xmlDoc = GXml.parse(request.responseText);
         // obtain the array of markers and loop through it
         var polygon = xmlDoc.documentElement.getElementsByTagName("coordinates");
         Lpolygon = polygon.length; 
         for (var i = 0; i < Lpolygon; i++) {
         var xyz = xmlDoc.getElementsByTagName("coordinates")[i].firstChild.nodeValue;	//call coordinate-x
		 var Slatlng = xyz.replace(/,0/g, ",");
		 var latlng = Slatlng.split(",");
		 var temp = [];
		 Lcoords[i] = (latlng.length-1)/2;
				 var x = [];
				 var y = [];
				 var coords = [];
			 for (var j=0; j<Lcoords[i]; j++){
				 x[j] = parseFloat(latlng[2*j]);
				 y[j] = parseFloat(latlng[2*j+1]);
				 coords[j] = new GLatLng(y[j],x[j]);
			 } //end for j=0
			 Ppoints.push(coords);
         } //end for i=0
        }
      }
	  
     request.send(null);
	}

	function selectMap(i) {
	if (document.getElementById(chkID[i]).checked == true) {
		map.addOverlay(kmlOverlay[i]);
		}
    else {
	      map.removeOverlay(kmlOverlay[i]);
    	 }
	}
	
      // ====== Geocoding ======
      function showAddress(Asearch) {
//        var Asearch = document.getElementById("Asearch").value + addressLocality;
        geo.getLocations(Asearch, function (result)
          {
            if (Asearch != addressLocality && result.Status.code == G_GEO_SUCCESS) {
              // ===== If there was more than one result, "ask did you mean" on them all =====
              if (result.Placemark.length > 1) { 
				document.getElementById("info").innerHTML = "<p class=" + "heading4" + "><strong>Did you mean: </strong>" + "</p>";
                // Loop through the results
				var c=0;
				
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates;
				  if (p[1]>=minLatLng.y && p[1]<=maxLatLng.y && p[0]>=minLatLng.x && p[0]<=maxLatLng.x) {
				  for (var k=0; k<Lpolygon; k++){	//test whether a point is inside multiple polygons
					  var oddNodes = pointInPolygon(k, p[1], p[0]);	//oddNodes=0/false - the point is outside the polygon; oddNodes=1/true - the point is inside the polygon
					  if (oddNodes == true) {
					  c++;
					  document.getElementById("info").innerHTML += c+": <a href='javascript:place(" +p[1]+","+p[0]+",&quot;"+result.Placemark[i].address+"&quot;"+")'>"+ result.Placemark[i].address+"</a>" + "<br>";
					  k = Lpolygon;
					  }
				  }
				  
				  }
                }				
				  if (c == 0) {
                  //document.getElementById("info").innerHTML = "";
				  alert('"' + Asearch + '"' + " is not found inside the boundary. \n\nFor further enquiry, please call the Voter's Helpline on 1 300 881 665.");
				  }
              }
              // ===== If there was a single marker =====
              else {
                //document.getElementById("info").innerHTML = "";
                var p = result.Placemark[0].Point.coordinates;
				
				
				  if (p[1]>=minLatLng.y && p[1]<=maxLatLng.y && p[0]>=minLatLng.x && p[0]<=maxLatLng.x) {
				  for (var k=0; k<Lpolygon; k++){	//test whether a point is inside multiple polygons
				  	  //var Cnodes = false;
					  var oddNodes = pointInPolygon(k, p[1], p[0]);	//oddNodes=0/false - the point is outside the polygon; oddNodes=1/true - the point is inside the polygon
					  if (oddNodes == true) {
					  	place(p[1],p[0],Asearch);
						k=Lpolygon;
					  }
				  }				  
					  if (oddNodes == false) {
						  alert('"' + Asearch + '"' + " is not found inside the boundary! \n\nFor further enquiry, please call the Voter's Helpline on 1 300 881 665.");
					  }
				  }
				  else {
					  alert('"' + Asearch + '"' + " is not found inside the boundary. \n\nFor further enquiry, please call the Voter's Helpline on 1 300 881 665.");
				  }								
              }
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
			  if (Asearch == ", Queensland") {
				  alert("Please enter your address.");
				  }
			  else {
				//document.getElementById("info").innerHTML = "";
                reason = reasons[result.Status.code]
              	alert('Could not find "'+Asearch+ '" ' + "\n\n" + reason);
              } 
            }
          }
        );
      }


      // ====== Plot a marker after positive reponse to "did you mean" ======
      function place(lat,lng,Asearch) {
		//map.clearOverlays();
        var point = new GLatLng(lat,lng);
		//kml = new GGeoXml(kmlPath_boundary);
		//map.addOverlay(kml);
		var aZoom = map.getZoom();
		if (marker) {
			map.removeOverlay(marker);
			marker = new GMarker(point);
			map.addOverlay(marker);
		}
		else {
			marker = new GMarker(point);
			map.addOverlay(marker);
		}
        //map.setCenter(point,aZoom); 
        document.getElementById("info").innerHTML = colourCode;
      }

	function pointInPolygon(k, lat, lng){ //Ncoords = number of points in a polygon = Lcoords[i]
		var oddNodes = false;
		var Nintersect = 0;
		var j = 0;
		for (var i=0; i<(Lcoords[k]-1); i++){
			j++;
			if (j == Lcoords[k]){j=0;}
			if (((Ppoints[k][i].y<lat && Ppoints[k][j].y>=lat) || (Ppoints[k][j].y<lat && Ppoints[k][i].y>=lat)) && (Ppoints[k][i].x+(lat-Ppoints[k][i].y)/(Ppoints[k][j].y-Ppoints[k][i].y)*(Ppoints[k][j].x-Ppoints[k][i].x))<lng) {
				oddNodes = !oddNodes;
				Nintersect++;
			}
		}
		return oddNodes;
	}

	function resetRoute() {
		map.clearOverlays();
		document.addressSearch.Asearch.value = "";
		colourCode="";
		document.getElementById("info").innerHTML = colourCode;
		marker = null;
		
		load();
	}


}
    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    //]]>
