//Copyright CartoSoft, LLC
//http://www.cartosoft.com
//Last updated 01/27/2008
//You may use any of the code in this script as long as the above copyright notice is left in place

 //<![CDATA[

if (GBrowserIsCompatible())
{
	var sidePoints = [];
	var gmarkers = [];
    var htmls = [];
	var nodes = [];
	var nodehtmls = [];
	var dirTo = [];
	var dirFrom = [];
	var dirNearby = [];
	var i = 0;
	var c = 0;
	var cnulls = 0;
	var sidehtml="";
	var sidenulls='<tr><td>&nbsp;</td><td style="padding-top:5px;"><span class="nullRecords">Records that could not be geocoded</span5></td></tr>';
	var map = null;
	var xmlDoc = null;
	var iconImage = null;
	var loader = null;
	var geoSwitch;
	var bounds = new GLatLngBounds();
	var clickId;
	var lastClick = -1;
	//Set a hash table and sort out the multiple listings
	var keycounts = [];	
	
	//Highlight the table row in the sidepanel...activated from the click inside the marker info window
	function highlight(a) {
		if (lastClick != -1) {
		document.getElementById(lastClick).style.background = "none";
		}
	document.getElementById(a).style.background = "#C6DAFF";
	document.getElementById(a).scrollIntoView(false);
	lastClick = a;
	}
	
	//Define the hash function
	function hash(lng, lat)	{
	return(lng + ":" + lat);
	}

	//Add overlays to map (called by loader)
	function addPoints (marker) {
	map.addOverlay(marker);
	}
	
	// This function picks up the click and opens the corresponding info window
	function findMarker(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
	}
	
	//This function shows/hides the directions divs
	function showDir(idir, dirStr) {
		if (dirStr == "to") {
			gmarkers[idir].openInfoWindowHtml('<div class="infowindow">'+dirTo[idir]+'</div>');
		}
		else {
			gmarkers[idir].openInfoWindowHtml('<div class="infowindow">'+dirFrom[idir]+'</div>');
		}
	}
	
	//This function shows/hides the nearby div
	function nearby(idir) {
			gmarkers[idir].openInfoWindowHtml('<div class="infowindow">'+dirNearby[idir]+'</div>');
	}
	
	//Call this function from body onLoad event in html output
	function load(){

		map = new GMap2(document.getElementById("map"));

		//Load MLoader with document elements
		loader = new MLoader(map, document.getElementById("loading"), document.getElementById("loadingText"),
		document.getElementById("bar"), document.getElementById("fill"), document.getElementById("loadingButton"),
		document.getElementById("tally"));
		loader.show("Loading Data", true);
		
		//Set the initial center point (this will be adusted at the end to the max bounds of the data points selected)
		var centerPoint = new GLatLng(10,0);
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());
			map.addControl(new GOverviewMapControl());
			map.enableDoubleClickZoom();
			map.setCenter(centerPoint, 2);
			
		//Google Ads Manager
		var publisher_id = "pub-9489596900474244";
		
		var adPos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 90));
	
		adsManagerOptions = {
		maxAdsOnMap : 3,
		style: 'adunit',
		background: '#ff0000',
		position: adPos
		};
		
		adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
		adsManager.enable();
			
		//Add custom controls
		if (document.getElementById("link-control")) {
			var addControl = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,63));
		document.getElementById("link-control").style.display="block";
		addControl.apply(document.getElementById("link-control"));
		map.getContainer().appendChild(document.getElementById("link-control"));
		}
		if (document.getElementById("search-control")) {
			var addControl = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,29));
		document.getElementById("search-control").style.display="block";
		addControl.apply(document.getElementById("search-control"));
		map.getContainer().appendChild(document.getElementById("search-control"));
		}
		if (document.getElementById("getClicky")) {
			var addControl = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(3,35));
		document.getElementById("getClicky").style.display="block";
		addControl.apply(document.getElementById("getClicky"));
		map.getContainer().appendChild(document.getElementById("getClicky"));
		}
		
		getXmlFile();
	}
				
			//-------------------------------------------------------------------------------------------------------------------------------------
			//Set the icons for each type of point
			var baseIcon = new GIcon();
				baseIcon.infoWindowAnchor = new GPoint(12, 12);	
			//End icon declarations
			//-------------------------------------------------------------------------------------------------------------------------------------

			//This function creates the map markers.  createMarker(point as GPoint, telephone as String, calltime as String, ihtml as String, icon as String)
			function createMarker(point, titleValue, mhtml, ihtml, cId, simtitle, loc, postdate) {
				var key  = hash(point.lng(), point.lat());
				
				mhtml = '<div style="overflow:auto; height:220px; width:260px">'+mhtml+'</div>';
				ihtml = '<div style="overflow:auto; max-height:250px; width:260px">'+ihtml+'</div>';
						
				//Create the Google icon based on the iconType (company, competition, customer)
				var icon = new GIcon(baseIcon);
				icon.image = "http://lab-cartosoft.appspot.com/gjc/icons/gjc"+c+".png";
				icon.iconSize = new GSize(25,25);
				icon.iconAnchor = new GPoint(12, 25);

				if (keycounts[key] == 1)
					{
						//Single Listing.  The marker is created with the GPoint (first variable passed to function) and the icon created above.
						//This generates the tooltip and graphic representation of the marker (i.e., icon)
						var marker = new GMarker(point, {title:simtitle, icon:icon});
						
			       		//Attach an event listener to the marker.  Show information in the info window.
						GEvent.addListener(marker, "click", function() {
						marker.openInfoWindowHtml('<div class="infowindow">'+ihtml+'</div>');
						highlight(cId);
			        	});	

			       		//Remove highlight of the table rows in the side panel when the info window is closed.
						GEvent.addListener(marker, "infowindowclose", function(){
							document.getElementById(cId).style.background="none";
						});
					}
					else
					{
						//Multiple Listings.  The marker is created with the GPoint (first variable passed to function) and the icon created above.
						//This generates the tooltip and graphic representation of the marker (i.e., icon)
						icon.image = "http://lab-cartosoft.appspot.com/gjc/icons/gjcm.png";
						var imgclass = "Multiple Points";
						var marker = new GMarker(point, {title:imgclass, icon:icon});
						
						
			       		//Attach an event listener to the marker.  Show information in the info window.
						GEvent.addListener(marker, "click", function() {
						marker.openInfoWindowHtml('<div class="infowindow"><b>This point has ' + keycounts[key] + ' listings.</b><br>'+mhtml+'</div>');
			        	});	
						
						//Remove highlight of the table rows in the side panel when the info window is closed.
						GEvent.addListener(marker, "infowindowclose", function(){
							if (lastClick != -1) {
							document.getElementById(cId).style.background="none";
							}
						});
					}
					
				var ic = c-1;


				//mhtml for the INFO PANEL (i.e,, the list on the left that contains the titles, etc.).
				sidePoints[cId] = point;
				gmarkers[cId] = marker;
				htmls[cId] = '<div class="infowindow">' + ihtml + '</div>';
				sidehtml += '<tr id="'+cId+'" onMouseOver="headerOver(\''+cId+'\')" onMouseOut="headerOut(\''+cId+'\')"><td valign="top" width="35" align="center" style="padding-bottom:10px; padding-top:10px; border-bottom: 1px solid #999999"><div class="header" title="'+imgclass+'">'+c+'.</div></td>';
				sidehtml += '<td style="padding-bottom:10px; padding-top:10px; border-bottom: 1px solid #999999" valign="top">';
				sidehtml += '<b>'+titleValue+'</b> <img src="new-window.gif" alt="Open in New Window" title="Open in New Window" /><br>';
				sidehtml += '<span style="color:#555555;font-weight:normal">Location: '+loc+'</span><br>';
				sidehtml += '<a href="javascript:highlight(\''+cId+'\');findMarker(\''+cId+'\')" title="Map It" style="float:right">Map It</a>';
				sidehtml += '<span style="color:#555555;font-weight:normal">(posted: '+postdate+')</span><br>';
				sidehtml += '</td></tr>';	
				i++;
	        	return marker;
	      	}
	
	function getXmlFile() {
	document.getElementById("loadingText").innerHTML = "Please Wait...<br>Parsing Data from Web Service";
	document.getElementById("bar").style.display = "none";
	document.getElementById("fill").style.display = "none";
	document.getElementById("tally").style.display = "none";
	document.getElementById("loadingButton").style.display = "none";
	
	GDownloadUrl("gjcmap.php?records="+setRecords, function(data, responseCode) {
			xmlDoc = GXml.parse(data);
			processXMLfile();
	});
	}

	//This function processes the KML file and calls the createmarker function...
	function processXMLfile() {
	sidePoints = [];
	gmarkers = [];
    htmls = [];
	nodes = [];
	nodehtmls = [];
	dirTo = [];
	dirFrom = [];
	dirNearby = [];
	i = 0;
	c = 0;
	cnulls = 0;
	sidehtml="";
	sidenulls='<tr><td>&nbsp;</td><td style="padding-top:5px;"><span class="nullRecords">Records that could not be geocoded</span5></td></tr>';
	geoSwitch = null;
	bounds = new GLatLngBounds();
	clickId = null;
	lastClick = -1;
	//Set a hash table and sort out the multiple listings
	keycounts = [];	
	
	map.clearOverlays();

	  if (xmlDoc) {
		document.getElementById("loadingText").innerHTML = "Loading Data";
		document.getElementById("bar").style.display = "block";
		document.getElementById("fill").style.display = "block";
		document.getElementById("tally").style.display = "block";
		document.getElementById("loadingButton").style.display = "block";

	    if (!xmlDoc) {
	       alert("invalid xml file - no xmlDoc");
	    }
	    if (!xmlDoc.documentElement) {
	       alert("invalid xml file - no documentElement");
	    }
			
				//Update Body title and page title in mhtml
				var bodytitle = xmlDoc.documentElement.getElementsByTagName("Document")[0].getElementsByTagName("name")[0];
				//document.getElementById("bodytitle").innerHTML = bodytitle.firstChild.nodeValue;
				//document.title = bodytitle.firstChild.nodeValue;
				
				var coords = xmlDoc.documentElement.getElementsByTagName("coordinates");

				var recCount = coords.length;
				
					//Populate the hash table
					for (var i = 0; i < recCount; i++) {
						var points = coords[i].firstChild.nodeValue;
						var pointsArray = points.split(",");
						var key = hash(parseFloat(pointsArray[0]), parseFloat(pointsArray[1]));
						keycounts[key] = 0;
					}
					for (var i = 0; i < recCount; i++)	{
						var points = coords[i].firstChild.nodeValue;
						var pointsArray = points.split(",");
						var key = hash(parseFloat(pointsArray[0]), parseFloat(pointsArray[1]));
						if (keycounts[key]) keycounts[key]++;
						else (keycounts[key]) = 1;
					}
				
				var places = xmlDoc.documentElement.getElementsByTagName("Placemark");
				
					for (var i = 0; i < recCount; i++) {
						var points = coords[i].firstChild.nodeValue;
						var pointsArray = points.split(",");
						//Check to see if the lat/lng are set.  If the point element has a lat/lng, then process the data and create the marker...
						if (pointsArray[0] != 0 && pointsArray[1] != 0) {
							var lng = parseFloat(pointsArray[0]);
							var lat = parseFloat(pointsArray[1]);
							//Send the lat/lng to the hash table
							var key  = hash(lng, lat);
							
							//Create the point using lat/lng
							var point = new GLatLng(lat, lng);
							 
							// Variables for html from xml
							var title = places[i].getElementsByTagName("name")[0].firstChild.nodeValue;
							var desc  = places[i].getElementsByTagName("description")[0].firstChild.nodeValue;
							var pretitle = places[i].getElementsByTagName("name")[0].getAttribute("_gxtitle");
							var simtitle = places[i].getAttribute("_gxbasetitle");
							var loc = places[i].getAttribute("_gxlocation");
							var postdate = places[i].getAttribute("_gxpostdate");
							var recid = places[i].getAttribute("_gxid");
							
							desc = desc.replace("<table>", "");
							desc = desc.replace("</table>", "");
							
							// html for the info window
							var ihtml = '<table border="0" cellspacing="0" cellpadding="4" class="infoWindow">';
							ihtml +=    '<tr><td class="title"><b>' + pretitle + ':</b></td><td class="title"><b>' + title +'</b></td></tr>';
							ihtml +=    desc;
							ihtml +=    '</table>';
					
							var mhtml = "";
					
							clickId = recid;
							
							//If there are multiple listings at the same location then add the key to the nodes array and the ihtml string to the nodehtmls array.
							if (keycounts[key] != 1) {
								nodes.push(key);
								nodehtmls.push('<div onClick = highlight("' + clickId + '") style="cursor: pointer; padding:3px; margin:3px; border: 1px solid #999999;">'+ ihtml +'</div>');
							}
						
							//Add the mhtml string from the array to the mhtml variable.  The mhtml variable will be reset after each iteration of the items.length for loop;
							for (var q = 0; q < nodes.length; q++) {
								if (nodes[q] == key) {
								mhtml += nodehtmls[q];	
								} 
							}
							
							//Increase the counter by 1
							c=c+1;
							
							//Create a marker for each item and pass the process to the loader...
							var marker = createMarker(point, title, mhtml, ihtml, clickId, simtitle, loc, postdate);
							
							//Send data to loader
							loader.add(i, addPoints, marker);
							
							//Add point to bounds object
							bounds.extend(point);
							}
							else {
							cnulls=cnulls+1;
							clickId = 'click' + i;
								// Variables for html from xml
								var title = places[i].getElementsByTagName("name")[0].firstChild.nodeValue;
								var desc  = places[i].getElementsByTagName("description")[0].firstChild.nodeValue;
								var pretitle = places[i].getElementsByTagName("name")[0].getAttribute("_gxtitle");
								var simtitle = places[i].getAttribute("_gxbasetitle");
								var loc = places[i].getAttribute("_gxlocation");
								var postdate = places[i].getAttribute("_gxpostdate");
								
								desc = desc.replace("<table>", "");
								desc = desc.replace("</table>", "");
								sidenulls += '<tr id="'+clickId+'" onMouseOver="headerOver(\''+clickId+'\')" onMouseOut="headerOut(\''+clickId+'\')"><td valign="top" width="35" align="center" style="padding-bottom:10px; padding-top:10px; border-bottom: 1px solid #999999"><div class="header">'+cnulls+'.</div></td>';
								sidenulls += '<td style="padding-bottom:10px; padding-top:10px; border-bottom: 1px solid #999999" valign="top">';
								sidenulls += '<b>'+title+'</b> <img src="new-window.gif" alt="Open in New Window" title="Open in New Window" /><br>';
								sidenulls += '<span style="color:#555555;font-weight:normal">Location: '+loc+'</span><br>';
								sidenulls += '<span style="color:#555555;font-weight:normal">(posted: '+postdate+')</span><br>';
								sidenulls += '</td></tr>';	
							}
						}	
						  	//Upon finishing, show the total number of records and the clickable telephone number in the infopanel
							document.getElementById("infopanel").innerHTML = '<h2 style="padding-left:0px; padding-top:0px">Jobs</h2>Click on an item below to see data on the map:<br>('+ c +' total records are mapped and '+cnulls+' records were not mapped)<br><table class="title" cellspacing="0" style="width:95%">' + sidehtml + sidenulls +'</table>';
							
							//Start progress bar
							loader.execute();
							
							if (setLat != 0 && setLng != 0 && setZoom > -1) {
								var userCenter = new GLatLng(setLat,setLng);
									map.setCenter(userCenter,setZoom);
							}
							else {
								//Set the map bounds based on the data that have been added...this guarantees that all points and the appropriate zoom are displayed every time
								map.setZoom(map.getBoundsZoomLevel(bounds));
								var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
								var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
								map.setCenter(new GLatLng(clat,clng));			
							}
		
	  }
	  else {
	  alert("XML Feed Not Found");
	  return;
	  }
	} 
}

//If the browser is not Javascript enabled/capable, then let the user know that the map cannot be displayed....
else {
document.getElementById("map").innerHTML = 'Sorry, your browser does not support the mapping API';
}

// Toggle the Info Panel
function togglePanel(dir) {
var a = document.getElementById("infopanel");
var b = document.getElementById("mainmap");
var c = document.getElementById("hidearrow");
var d = document.getElementById("showarrow");
var e = document.getElementById("map_overview");

	//If the map hides the infopanel on the LEFT...
	if (dir == "left") {
		if (a.style.display != 'none') {
			a.style.display = 'none';
			b.style.left = '0px';
			c.style.display = 'none';
			d.style.display = 'block';
			map.checkResize();
		}
		else {
			a.style.display = 'block';
			b.style.left = '35%';
			c.style.display = 'block';
			d.style.display = 'none';
			map.checkResize();
		}
	}
	
	//If the map hides the infopanel on the RIGHT...
	if (dir == "right") {
		if (a.style.display != 'none') {
			a.style.display = 'none';
			b.style.right = '0px';
			c.style.display = 'none';
			d.style.display = 'block';
			map.checkResize();
		}
		else {
			a.style.display = 'block';
			b.style.right = '35%';
			c.style.display = 'block';
			d.style.display = 'none';
			map.checkResize();
		}
	}
}

function addGeocode() {
var gxAddress = document.getElementById("addInput").value;
var geocoder = new GClientGeocoder();

  geocoder.getLatLng(
    gxAddress,
    function(point) {
      if (!point) {
        alert(gxAddress + " not found");
      } else {
        map.setCenter(point, 11);
        //var marker = new GMarker(point);
        //map.addOverlay(marker);
        //marker.openInfoWindowHtml(address);
      }
    }
  );
}

var rncolor = '';

function getLink() {
var colors = new Array('#ff0000', '#99cc33', '#00b1f3', '#cc00ff', '#336666', '#ff6666');
var rn = Math.floor(Math.random()*5)
var point = map.getCenter();
var lat = point.lat();
var lng = point.lng();
var zoom = map.getZoom();
var linkInput = document.getElementById("link-text");
linkInput.value = 'http://www.cartosoft.com/lab/gjc/index.php?lat='+lat+'&lng='+lng+'&zoom='+zoom;
linkInput.style.color = '#ffffff';
linkInput.style.display = 'inline';
linkInput.style.background = colors[rn];
}

function headerOver(selId) {
	if (lastClick != selId) {
	document.getElementById(selId).style.background = "#F1F6FF";
	}
}

function headerOut(selId) {
	if (lastClick != selId) {
	document.getElementById(selId).style.background = "none";
	}
}

function tHelp(hType) {
	if (hType == "show") {
		document.getElementById('help-wrapper').style.display = "block";
	}
	else {
		document.getElementById('help-wrapper').style.display = "none";
	}
}

//]]>
