// iframe.js - based on 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 ghostPins = Array(); // And the ghost pins as well
// var cLat = 43.171844983221604; // Default starting position for the map
// var cLng=-79.98823699951172; 
// var cZoom = 8; 
// var cCode = SART;
// var thisBlogTable
// var otherBlogTable

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 tableWidth = 4;

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");
// And an icon for ALL the entries NOT in the code defined
var mapIconsGhost = new GIcon(baseIcon, "/images/mapIconGhost.png", null, "/images/shadow12.png");
mapIconsGhost.iconSize=new GSize(12,20);
mapIconsGhost.iconAnchor=new GPoint(5,18);
mapIconsGhost.shadowSize=new GSize(22,20);
mapIconsGhost.infoWindowAnchor=new GPoint(5,0);

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");
  }
}
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);
	mouseend();	
}

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

function mouseend() {
	var mapbounds=gmap.getBounds();
	var ne=mapbounds.getNorthEast();
	var sw=mapbounds.getSouthWest();
	var neLng=ne.lng(); 
	var neLat=ne.lat(); 
	var swLng=sw.lng();
	var swLat=sw.lat();
	// And the center, for the comment
	var mapCenter=gmap.getCenter();
	var mapZoom=gmap.getZoom();
  document.getElementById('comment').innerHTML = "<!-- Zoom at " + mapZoom + " and center at " + mapCenter + " -->\n";
	updateStatusDiv("Checking for pins on the new section of the map...");
	// Need to get data from the server for the corresponding points
	// code, lat, lng, title, url, thumb
  
  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]
  // v1.1 - get ALL codes, parse later - 
  // if (typeof cCode != 'undefined' ) { getURL += "&code="+cCode; } 
  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;
      
       // 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);
       			// Remember that we've seen this code, so that the createMarker function can find the icon to use
       			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,reqData.pins[t1].minimaphover);
       			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 );
       			  }
       		  }       			
       			knownPins.push(reqData.pins[t1].ucode);
       	  }
       } 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,reqData.pins[w].minimaphover);
       				 gmap.addOverlay(marker);               
       				 add++;
            }            
          } // End of running through each value read from the database
          updateStatusDiv("Added an additional " + add + " pins.");
       }
  } 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,minititle) {
				// 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
				
				// Only want a real icon for the pCode entry,
				// and a ghost one for all the others
				if (code == cCode) {
					// var iconNum = codeList.getIconNum(code);
					var marker = new GMarker(point, {icon:mapIcons[1], title:title});			  
        	GEvent.addListener(marker, "click", function() {
          	marker.openInfoWindowHtml(html);
        	});
        } else {
        	// Assume this is a ghost
        	var marker = new GMarker(point, {icon:mapIconsGhost, title:minititle});			  
        	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) {
		// If there is an codeIcon specified?
		if (typeof codeIcon == 'undefined' ) {
			codeIcon = "mapIcon" + this.data.length + ".png";
		}
		// Now see if we already know of this code using codeListExists()
		if ( this.codeexists(codeName) ) {
		} else {
			var tempCodes = new Array(codeName, codeIcon, codeString,this.data.length);
			this.data[this.data.length] = tempCodes;
			// Remember which icon count we are using for the pin			
		}
	}
	function codeCodeExists(codeName) {
		// See if codeName is already in our list
		var dataLength = -1;
		if (typeof this.data != 'undefined') { dataLength = this.data.length; }
		for (i=0;i<dataLength;i++) {
			if (this.data[i][0] == codeName) {
				return 1;
				}
		}
			return 0;
	}

function codeShowIcon(codeName) {
	  for (i=0;i<this.data.length;i++) {
			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>";
	}
	return retS+"</table>";	
}

function addTableEntry(tDetails) {
	// Add this entry to the table of thumbnails
	
}


