//<![CDATA[
/* A lot of the code is taken from other tutorials. */

// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";

// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there`
var gmarkers = [];
var htmls = [];
var id = [];
var i = 0;
var display_count =0;

// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];

// A function to create the marker and set up the event window

function createMarker(point,html,myicon,name,itemID) {
		display_count++;
        var marker = new GMarker(point,myicon);

        // The info window version with the "to here" form open
        to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
           '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + "(" + name + ")" + '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() + "(" + name + ")" + '"/>';
        // The inactive version of the direction info
        html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';

        GEvent.addListener(marker, "click", function() {
		  var moreinfo = "<div style='padding-left:8px; padding-top:3px; font-size:14px; font-weight: bolder; color:#996633'>Are you the owner?</DIV><table border=0 cellPadding=3><tr><td><div style='width:50px; height:50px;border:thin solid; border-width:3px;border-color: #CC9E47'><img src='images/person_blank.gif' align='left' width=50 height=50></div></td><td width='310' valign=top>&nbsp;You can add your business information such as pictures, coupons or menu here. <BR> Click <a href='Suggest.php?requestID="+itemID+"'>here </a> to submit.</td></table>";	
          marker.openInfoWindowTabsHtml([new GInfoWindowTab("Details",html), new GInfoWindowTab("More info",moreinfo)]);
        });
        // save the info we need to use later for the side_bar
		id[i]=itemID;        
        gmarkers[i] = marker;
        htmls[i] = html;
        // add a line to the side_bar html
        side_bar_html += '<li><a href="javascript:myclick(' + i + ')">' + name + '</a></li>';
	    
        i++;
        return marker;
}
// ==================================================
  
// This function picks up the click and opens the corresponding info window
function myclick(i) {
var moreinfo = "<div style='padding-left:8px; padding-top:3px; font-size:14px; font-weight: bolder; color:#996633'>Are you the owner?</DIV><table border=0 cellPadding=3><tr><td><div style='width:50px; height:50px;border:thin solid; border-width:3px;border-color: #CC9E47'><img src='images/person_blank.gif' align='left' width=50 height=50></div></td><td width='310' valign=top>&nbsp;You can add your business information such as pictures, coupons or menu here. <BR> Click <a href='Suggest.php?requestID="+id[i]+"'>here </a> to submit.</td></table>";	
gmarkers[i].openInfoWindowTabsHtml([new GInfoWindowTab("Details",htmls[i]), new GInfoWindowTab("More info",moreinfo)]);
}

// functions that open the directions forms
function tohere(i) {
gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}

function getMarks(url) { /* pass url during the call. */
	map.closeInfoWindow(); /*close any InfoWindows that happen to be open  */
	map.clearOverlays();
  	var request = GXmlHttp.create(); /* use the XML methods  */
    	request.open("GET", url, true);
    	request.onreadystatechange = function() {
     	if (request.readyState == 4) {	
		var xmlDoc = request.responseXML; /* php returns 'XML' */
		var markers = xmlDoc.documentElement.getElementsByTagName("marker"); 
		for (var loop1=0;loop1<markers.length;loop1++){
			var lat = parseFloat(markers[loop1].getAttribute("lat"));  /* data is string. */
			var lng = parseFloat(markers[loop1].getAttribute("lng")); 
			var point = new GLatLng(lat,lng);
			var county = markers[loop1].getAttribute("county");
			var html = markers[loop1].getAttribute("html");
			var icon = new GIcon();
            icon.image = "http://www.desitools.com/images/markers/marker1.png";
            icon.iconAnchor = new GPoint(6, 20);
            icon.infoWindowAnchor = new GPoint(5, 1);
            icon.iconSize = new GSize(32, 32); 

			var marker = createMarker(point,html,icon);
			map.addOverlay(marker);
			}
		}
		};
	request.send(null);
}

function showInfoWin(point) {
    map.openInfoWindowHtml(point,"Some html windows");
}

function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
		map.clearOverlays();
        map.setCenter(point, 11);
        }
      }
    );
  }
}

function showIndex($index) {
	getMarkers("index",$index);
}

function getMarkers(action,val) { /* pass url during the call. */
	map.closeInfoWindow(); /*close any InfoWindows that happen to be open  */
	document.getElementById("mystat").innerHTML ="Loading Please Wait...";
	var res= "<FONT class='news_box'>";
	map.clearOverlays();
	var url = "marksx.php?"+action+"="+val;
	mapbounds=map.getBounds();
		var mapne=mapbounds.getNorthEast();
		var mapsw=mapbounds.getSouthWest();
		var mapSWLat=mapsw.lat();
		var mapSWLng=mapsw.lng();
		var mapNELat=mapne.lat();
		var mapNELng=mapne.lng();
		url = url+"&nelat="+mapNELat+"&nelng="+mapNELng+"&swlat="+mapSWLat+"&swlng="+mapSWLng;

	//alert(url);
	var bounds = new GLatLngBounds();

	side_bar_html="<ol>";
	display_count=0;
  	var request = GXmlHttp.create(); /* use the XML methods  */
    	request.open("GET", url, true);
    	request.onreadystatechange = function() {
     	if (request.readyState == 4) {	
		var xmlDoc = request.responseXML; /* php returns 'XML' */
		var markers = xmlDoc.documentElement.getElementsByTagName("marker"); 
		//document.getElementById("div_results").innerHTML = "<b><u>"+markers.length + " results found</u></b>";
		var first = true;
		for (var loop1=0;loop1<markers.length;loop1++){
			var lat = parseFloat(markers[loop1].getAttribute("lat"));  /* data is string. */
			var lng = parseFloat(markers[loop1].getAttribute("lng")); 
			var point = new GLatLng(lat,lng);
			if (action =="index"){
		        //map.setZoom(map.getBoundsZoomLevel(bounds));
		        // ===== determine the centre from the bounds ======
		        //map.setCenter(bounds.getCenter());
				map.setCenter(point, 16);
				return;
			}
			/*
			if (first){
				if ((markers.length>0) &&(markers.length <=5) )
					map.setCenter(point, 12);
				else if ((markers.length>5) &&(markers.length <=10) )
					map.setCenter(point, 12);
				else if ((markers.length>10) &&(markers.length <=20) )
					map.setCenter(point, 11);
				else if (markers.length>20)
					map.setCenter(point, 10);	
				first = false;
			}*/

			var cnt = loop1 +1;
			var county = markers[loop1].getAttribute("county");
			var html = markers[loop1].getAttribute("html");
			var itemID = markers[loop1].getAttribute("ItemID");
			var icontype = markers[loop1].getAttribute("icontype");
			
			if (loop1 < 33){
				if (county != ""){
						res = res + "<BR>" +cnt +". "+ county;
				}else{
						res = res + "<BR>" +cnt +". Religious place -Click "+cnt;
				}
			}
			var icon = new GIcon();
			icon.image = "http://www.desitools.com/images/"+icontype+"markers/marker"+cnt+".png";
			
            icon.iconAnchor = new GPoint(6, 20);
            icon.infoWindowAnchor = new GPoint(5, 1);
            icon.iconSize = new GSize(20, 34); 
			var marker = createMarker(point,html,icon,county,itemID);
			map.addOverlay(marker);
			bounds.extend(point);
			}
			if (markers.length ==0){
				document.getElementById("mystat").innerHTML ="No results found, try using other methods";
				document.getElementById("div_feed").innerHTML = "";
			}
			else{	
				res= res + "</FONT>";
				var inner ="<b><u>"+markers.length + " results found</u></b>&nbsp;&nbsp;" +
				"<input type=\"Submit\" VALUE=\"Back\" style=\"font-family:Arial, Verdana; font-size:11px; color:#FFFFFF; font-weight:bold; background-color:#336699; border-color:#6699FF\" onclick='clearAll();';> &nbsp;"+
				side_bar_html;
				document.getElementById("div_feed").innerHTML =inner;
				document.getElementById("mystat").innerHTML = "Click on the marker to see more details and driving directions";		
			}
			// ===== determine the zoom level from the bounds =====
			
	        side_bar_html="</ol>";
		}
		};
      
	request.send(null);
}

    function updateMarkersZoom (oldLevel, newLevel){
		//alert('zoom changed from : ' + oldLevel + ' to ' + newLevel);
      /* we do not update on first zoom, as we get a pan right after
		that anyway
       * oldLevel == null is first zoom
       */
      if (oldLevel != null && oldLevel != newLevel && newLevel >5){
        zoom = newLevel;
        getMarkers('cityid','1');
      }
    }

    function updateMarkersMove(){
      //alert('map moved to ' + map.getBounds());
      
	  if(map.getZoom() >5){
	      getMarkers('cityid','1');
	   }
    } 
    
/* http://econym.googlepages.com/example_map4.htm */
//]]>

