// all-codes2.js
// 
// alert("DEBUG: Start of all-codes.js really");

// Global variables we will use:
// var map = document.getElementById("map");
// var knownPins = Array(); // Remember the ucode of pins we've already shown
// var cLat = 43.171844983221604; // Default starting position for the map
// var cLng=-79.98823699951172; 
// var cZoom = 8; 

var cAccuracy=4;
var parmCode = ""; 	// Store the Code parameter here, if it is defined, then use it for the where
var parmPin = ""; 	// Store the Pin parameter here, if it is defined
var showMap = true; // Are we ready to show the map? Assume so, unless we're waiting for intial pin data

var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(20,34);
baseIcon.shadowSize=new GSize(56,32);
baseIcon.iconAnchor=new GPoint(16,32);
baseIcon.infoWindowAnchor=new GPoint(16,0);
//Icons from http://brennan.offwhite.net/blog/2005/07/23/new-google-maps-icons-free/
var mapIcons = Array();          
mapIcons[0] = new GIcon(baseIcon, "/images/mapIcon0.png", null, "/images/shadow50.png");
mapIcons[1] = new GIcon(baseIcon, "/images/mapIcon1.png", null, "/images/shadow50.png");
mapIcons[2] = new GIcon(baseIcon, "/images/mapIcon2.png", null, "/images/shadow50.png");
mapIcons[3] = new GIcon(baseIcon, "/images/mapIcon3.png", null, "/images/shadow50.png");

mapIcons[4] = new GIcon(baseIcon, "/images/mapIcon4.png", null, "/images/shadow50.png");
mapIcons[5] = new GIcon(baseIcon, "/images/mapIcon5.png", null, "/images/shadow50.png");
mapIcons[6] = new GIcon(baseIcon, "/images/mapIcon6.png", null, "/images/shadow50.png");
mapIcons[7] = new GIcon(baseIcon, "/images/mapIcon7.png", null, "/images/shadow50.png");
mapIcons[8] = new GIcon(baseIcon, "/images/mapIcon8.png", null, "/images/shadow50.png");
mapIcons[9] = new GIcon(baseIcon, "/images/mapIcon9.png", null, "/images/shadow50.png");
mapIcons[10] = new GIcon(baseIcon, "/images/mapIcon10.png", null, "/images/shadow50.png");
mapIcons[11] = new GIcon(baseIcon, "/images/mapIcon11.png", null, "/images/shadow50.png");
mapIcons[12] = new GIcon(baseIcon, "/images/mapIcon12.png", null, "/images/shadow50.png");
mapIcons[13] = new GIcon(baseIcon, "/images/mapIcon13.png", null, "/images/shadow50.png");
mapIcons[14] = new GIcon(baseIcon, "/images/mapIcon14.png", null, "/images/shadow50.png");
mapIcons[15] = new GIcon(baseIcon, "/images/mapIcon15.png", null, "/images/shadow50.png");

mapIcons[999] = new GIcon(baseIcon, "/images/mapIcon999.png", null, "/images/shadow50.png");

var mapIcon0 = new GIcon(baseIcon, "/images/mapIcon0.png", null, "/images/shadow50.png");
var mapIcon1 = new GIcon(baseIcon, "/images/mapIcon1.png", null, "/images/shadow50.png");
var mapIconDefault = new GIcon(baseIcon, "/images/mapIconDefault.png", null, "/images/shadow50.png");
    

// An object to keep track of the codes we've seen and their icons
var codeList = new codeListObject();

// Life should be so simple: var req = new XMLHttpRequest();
if(window.XMLHttpRequest) { try { req = new XMLHttpRequest(); } catch(e) { req = false;	}    
} else if(window.ActiveXObject) {  // branch for IE/Windows ActiveX version
	try { req = new ActiveXObject("Msxml2.XMLHTTP");} catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; }  }
} // End of if Firefox or IE

function gotURLdata4Pin() {
	// The Ajax call has completed, and we should have the initial Pin data
	// {"onepin": [ {"cLat": "43.650112384926544","cLng": "-79.46059226989746", "cZoom": "4", "cAccuracy": "4"} ]}
	if (req.readyState == 4 /*complete*/) {
		var reqData = eval('(' + req.responseText + ')');
		updateStatusDiv("Initial pin data has been read");
    // Array size?
    // var reqDataLength = reqData.onepin.length;
    
		// if (reqData.onepin.length == 0) { cLat = 43.171844983221604; cLng=-79.98823699951172; cZoom = 8; cAccuracy=4; }
	  // else { alert("We found data in finishmap and will zoom to " + reqData.onepin[0].cZoom); cLat = reqData.onepin[0].cLat; cLng=reqData.onepin[0].cLng; cZoom = reqData.onepin[0].cZoom; cAccuracy=reqData.onepin[0].cAccuracy; }
	  
	  // Should really error check this I think...
	  // showMap = true;
  }
}
function bodyOnLoad() {
	// We have the HTML all loaded up
	// But are we ready to show the map yet? showMap
	var map = document.getElementById("map");
	gmap = new GMap2(map);
	gmap.addControl( new GLargeMapControl() );
  gmap.addControl( new GMapTypeControl()) ;
  gmap.addControl( new GOverviewMapControl(new GSize(100,100)) );
	
	gmap.setCenter( new GLatLng(cLat,cLng), cZoom );
	GEvent.addListener(gmap, 'moveend', mouseend);
	// GEvent.addListener(gmap, 'movestart', mousestart);
	
	mouseend();	
	setTimeout("hidePinListDiv();",4000);
}

function updateStatusDiv(update) {
	document.getElementById('status').innerHTML = update; // += "<br/>+ " + update;
}

function updatePermanentLink(update) {
	// See if this version of the map has a 'perm' span element, and if so, update
	// it with the details in update
	if ( document.getElementById("perm") ) { document.getElementById('perm').innerHTML = update; }
}


function mouseend() {
	var mapbounds=gmap.getBounds();
	var mapCenter=gmap.getCenter();
	var mapZoom=gmap.getZoom();
	var ne=mapbounds.getNorthEast();
	var sw=mapbounds.getSouthWest();
	var neLng=ne.lng(); 
	var neLat=ne.lat(); 
	var swLng=sw.lng();
	var swLat=sw.lat();
	var ceLat=mapCenter.lat();
	var ceLng=mapCenter.lng();
	
	updateStatusDiv("Checking for pins on the new section of the map...");
	
	updatePermanentLink("<a href='http://wholemap.com/map/llz.php?lat=" + ceLat + "&lng=" + ceLng + "&zoom=" + mapZoom+">Permanent link for this Wholemap location and zoom level.</a>");
	// Need to get data from the server for the corresponding points
	// code, lat, lng, title, url, thumb
  
  // var req = new XMLHttpRequest();
  // Start with the basics:
  var getURL = "../data/d1.php?maxLat=" + neLat + "&minLat=" + swLat + "&maxLng=" + neLng + "&minLng=" + swLng;
  // Also see if a code was specified (in parmCode ), and pass that as well "&code="+shVal[1]
  if (typeof cCode != 'undefined' ) { getURL += "&code="+cCode; } 
  // if (typeof parmPin  != 'undefined' ) { getURL += "&pin="+parmPin; } 
  
  // req.open("GET", "../data/d1.php?maxLat=neLat&minLat=swLat&maxLng=neLng&minLng=swLng", /*async*/true);
  // document.getElementById('lastload').innerHTML = getURL;
  req.open("GET", getURL, /*async*/true);
  count = 1;
  req.onreadystatechange = geoReadJSONmarkers;
  req.send(/*no params*/null);
	
}

function geoReadJSONmarkers() {
	// Called through the XMLHttpRequest as the state changes
	if (req.readyState == 4 /*complete*/) {
		   updateStatusDiv("Processing new set of pins");
       var reqData = eval('(' + req.responseText + ')');
       
       // Array size?
       var reqDataLength = reqData.pins.length;
       var ulmapLinks = document.getElementById("mapLinks");
       // var firstTitle = reqData.pins[1].title;
       // status("2nd title is " + firstTitle);
       
      
       // Now we have the new set of data, compare it to the exising set of
       // pins (knownPins), and in each case determine if the pin is alredy on the map
       // if NOT, display it and add it to the array       
       
       if (knownPins.length == 0) {
       		// If this is our 1st call just copy ALL across then add them all to the map
       		// knownPins = reqData.pins;
       		updateStatusDiv("Read " + reqData.pins.length + " pins");       		
       		
       		for (t1=0;t1<=reqData.pins.length-1;t1++) { 
       			// updateStatusDiv("Add the pin[" + count + "] for " + reqData.pins[t1].title + " at "+  reqData.pins[t1].lat + ", " + reqData.pins[t1].lng );
       			var point = new GLatLng(reqData.pins[t1].lat,reqData.pins[t1].lng);
       			// updateStatusDiv("Created the pin[" + count + "] for " + reqData.pins[t1].title + " at "+  reqData.pins[t1].lat + ", " + reqData.pins[t1].lng );
       			// Remember that we've seen this code, so that the createMarker function can find the icon to use
       			// alert("Add the code " + reqData.pins[t1].code + " for " + reqData.pins[t1].ucode );
       			codeList.addCode(reqData.pins[t1].code, reqData.pins[t1].codeString);
          	var marker = createMarker(point, reqData.pins[t1].mhtml,reqData.pins[t1].code,reqData.pins[t1].title);
       			gmap.addOverlay(marker);
       			// If the pin was passed as a parameter, then open it using marker.openInfoWindowHtml("Marker #<b>" + number + "</b>");
       			if (typeof cMarker != 'undefined' ) {
       			  if ( cMarker == reqData.pins[t1].ucode) {
       				  marker.openInfoWindowHtml( reqData.pins[t1].mhtml );
       			  }
       		  }       			
       		  // var thisCode = reqData.pins[t1].code;
       			// Remember this in the list of pins, too
       			knownPins.push(reqData.pins[t1].ucode);      			
       			
       			// And add this entry to the UL list...
       			var newLI = document.createElement("LI");
						ulmapLinks.appendChild(newLI);
						// newLI.innerHTML = "<a target='wb' href='" + reqData.pins[t1].url + "'>" + reqData.pins[t1].title + "</a>";       			
						newLI.innerHTML = reqData.pins[t1].ulCode;
						
       	  }
       	  updateStatusDiv("Added " + knownPins.length + " new pins to the map.");
       		
       } else {
          // The array already exists, so check each one
          var skp = 0;
          var add = 0;
          // Run through each item in reqData.pins and see if it is already in knownPins
          // If so, just skip it, otherwise add it to the map, and to the array
          // use ucode to check - we'll write a routine for this
          for (w=0;w<=reqData.pins.length-1;w++) {
          	// Does the ucode reqData.pins[w].ucode exist in the set of pins we already have displayed on the map?
          	if ( geoUcodeExist(knownPins, reqData.pins[w].ucode ) ) {
          	   // Already seen this one, ignore it
          	   skp++;
            } else {
               // This is new, so add it to the map
               knownPins.push(reqData.pins[w].ucode);
               codeList.addCode(reqData.pins[w].code, reqData.pins[w].codeString);
               var point = new GLatLng(reqData.pins[w].lat,reqData.pins[w].lng);
       				 // updateStatusDiv("Created the pin[" + count + "] for " + reqData.pins[w].title + " at "+  reqData.pins[w].lat + ", " + reqData.pins[w].lng );
          		 var marker = createMarker(point, reqData.pins[w].mhtml, reqData.pins[w].code,reqData.pins[w].title);
       				 gmap.addOverlay(marker);               
       				 add++;
       				 // And add this entry to the list...
       				 var newLI = document.createElement("LI");
							 ulmapLinks.appendChild(newLI);							 
							 newLI.innerHTML = reqData.pins[w].ulCode
							 
            }            
          } // End of running through each value read from the database
          updateStatusDiv("Added an additional " + add + " pins.");
       }
       // Now update the contents of the pinList
       document.getElementById('pinListDetails').innerHTML = "<!-- start -->";
       document.getElementById('pinListDetails').innerHTML += codeList.allCodesDetails();
  } else {
  updateStatusDiv("Reading pin number " + count );
  count++;
  }
}
function geoUcodeExist( existingArray, newUcode) {
	// Given a newUcode, see if it already exists in the given array
	for (q=0;q<=existingArray.length-1;q++) {
		if (existingArray[q] == newUcode ) { return true; }
  }
  return false;
}
function geoShowKnown() {
	alert(knownPins);
}
function createMarker(point,html,code,title) {
				// Want a different marker per code - just use iconB1 for now
				// But really, we should be able to read the icon being used at THIS point, which is really just
				// the count in the array...
				// Some blogs will have their own icon, like mapIconSART.png - 32x40
				var iconNum = codeList.getIconNum(code);
				var marker = new GMarker(point, {icon:mapIcons[iconNum], title:title});
				// if      (code == "PJUNKIE") { var marker = new GMarker(point, {icon:mapIcons[iconNum], title:title}); }
				// else if (code == "SART")    { var marker = new GMarker(point, {icon:mapIcons[iconNum], title:title}); }
			  // else                      { var marker = new GMarker(point, mapIcons[999]); } 
			  
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
}

function showMapDetails() {
	var cZoom = gmap.getZoom()
	var cCenter = gmap.getCenter()
	document.getElementById('mdetails').innerHTML = "( Map center at " + cCenter + " with a zoom of " + cZoom + " )";
mdetails
}

	function codeListObject() {
	  this.data = Array(); // An array of 2-cell arrays ["SART", "icon3.png",iconNumber]
	  this.addCode = codeListAdd;
	  this.icon = codeShowIcon; // Return the array value to use for the icon for the specified code
	  this.getIconNum = codeShowIconNum
	  this.codeexists = codeCodeExists;
	  this.allCodesDetails = codeListAllDetails;
	}
	function codeListAdd(codeName, codeString, codeIcon) {
		// alert("codeListAdd(): Consider a code of " + codeName);
		// Have we seen codeName before? in the this.data array?
		
		// If there is an codeIcon specified?
		if (typeof codeIcon == 'undefined' ) {
			// alert("codeListAdd(): codeIcon was not passed to the function, so we'll pick the next possible icon");
			codeIcon = "mapIcon" + this.data.length + ".png";
		}
		// Now see if we already know of this code using codeListExists()
		if ( this.codeexists(codeName) ) {
			// testAdd("codeListAdd(): Checked and we already know of this code");
		} else {
			// alert("codeListAdd(): Checked and we DON'T already know of this code");
			var tempCodes = new Array(codeName, codeIcon, codeString,this.data.length);
			this.data[this.data.length] = tempCodes;
			// alert("We've added " + codeName + " to the list");
			// Remember which icon count we are using for the pin			
		}
	}
	function codeCodeExists(codeName) {
		// See if codeName is already in our list
		// alert("codeCodeExists(): See if the code '" + codeName + "' is already known in the array that is this big: " + this.data.length);
		var dataLength = -1;
		if (typeof this.data != 'undefined') { dataLength = this.data.length; }
		for (i=0;i<dataLength;i++) {
			// testAdd("&nbsp;&nbsp;&nbsp;&nbsp;(" + i + ") Does " + this.data[i][0] + " == " + codeName);
			if (this.data[i][0] == codeName) {
				return 1;
				}
		}
			return 0;
	}
//	function codeShowList() {
//	  updateStatusDiv("codeShowList(): Here is the set of codes that are defined");
//	  for (k3=0;k3<this.data.length;k3++) {
//			updateStatusDiv("&nbsp;&nbsp;&nbsp;&nbsp;(" + k3 + ") " + this.data[k3]);			
//		}	  
//	}
function codeShowIcon(codeName) {
	  // testAdd("codeShowIcon(): return the icon defined for '" + codeName +"'");
	  for (i=0;i<this.data.length;i++) {
			// testAdd("&nbsp;&nbsp;&nbsp;&nbsp;(" + i + ") Is " + this.data[i][0] + " the code we want to show the icon name for " + codeName);
			if (this.data[i][0] == codeName) { return this.data[i][2]; }
		}
			return 999;
}

function codeShowIconNum(codeName) {
	for (i8=0;i8<this.data.length;i8++) { if (this.data[i8][0] == codeName) { return i8; } }
	return 999;
}
	
	
function codeListAllDetails() {
	// Return a string listing each code
	var retS = "<table border='0' width='228'><tr><td>Blogs shown on the map</td><td width='36'><img src='/images/show-arrow-left-34x20.png' width='34' height='20'></td></tr>";
	for (k3=0;k3<this.data.length;k3++) {                                      
		// Get the icon # being used
		retS += "<tr><td>" +  this.data[k3][2] + "</td><td width='36'><img class='CodeList' src='/images/mapIcon" + k3 + ".png'></td></tr>";
		// alert("Count is " + k3 + " this.data[x][0] is set to " + this.data[k3][0] + " this.data[x][1] is set to " + this.data[k3][1] + " this.data[x][2] is set to " + this.data[k3][2]+ " this.data[x][3] is set to " + this.data[k3][3]);
	}
	return retS+"</table>";	
}

function showPinListDiv() {
	document.getElementById('pinList').style.zIndex = '15';
	return 1;
}
function hidePinListDiv() {
	document.getElementById('pinList').style.zIndex = '-1';
	return 1;
}