// global variables

var map;  
var infowindow;
var request;
var bounds = new GLatLngBounds(); 
var lastmarker = null;




var gmarkers = [];
var idmarkers = [];


// This function picks up the click on the links in the sidebar and opens the corresponding info window

      function myclick(i) {
         GEvent.trigger(gmarkers[i], "click");
      }
	  
	  
	    function idclick(id) {
         GEvent.trigger(idmarkers[id], "click");
      }

// clear all markers
		function zapMap() {
			map.clearOverlays();
		}


// Replaces the in-page window onload function
GEvent.addDomListener(window, "load", load);
GEvent.addDomListener(window, "unload", GUnload); 




function load() {
if (GBrowserIsCompatible()) {
	

	
      // a new empty string variable to hold the sidebar HTML
      var side_bar_html = "";
       
// define the markers	   
var icons = new Array();

// for tan sand
icons["tan"] = new GIcon(); 
icons["tan"].image = "images/markertan.png"; 
icons["tan"].iconSize=new GSize(27, 34); 
icons["tan"].iconAnchor=new GPoint(10, 34); 
icons["tan"].infoWindowAnchor=new GPoint(10, 8);

// for yellow sand
icons["yellow"] = new GIcon(); 
icons["yellow"].image = "images/markeryellow.png"; 
icons["yellow"].iconSize=new GSize(27, 34); 
icons["yellow"].iconAnchor=new GPoint(10, 34); 
icons["yellow"].infoWindowAnchor=new GPoint(10, 8); 

// for black sand
icons["black"] = new GIcon(); 
icons["black"].image = "images/markerblack.png"; 
icons["black"].iconSize=new GSize(27, 34); 
icons["black"].iconAnchor=new GPoint(10, 34); 
icons["black"].infoWindowAnchor=new GPoint(10, 8); 

// for grey sand
icons["grey"] = new GIcon(); 
icons["grey"].image = "images/markergrey.png"; 
icons["grey"].iconSize=new GSize(27, 34); 
icons["grey"].iconAnchor=new GPoint(10, 34); 
icons["grey"].infoWindowAnchor=new GPoint(10, 8); 

// for white sand
icons["white"] = new GIcon(); 
icons["white"].image = "images/markerwhite.png"; 
icons["white"].iconSize=new GSize(27, 34); 
icons["white"].iconAnchor=new GPoint(10, 34); 
icons["white"].infoWindowAnchor=new GPoint(10, 8); 

// for green sand
icons["green"] = new GIcon(); 
icons["green"].image = "images/markergreen.png"; 
icons["green"].iconSize=new GSize(27, 34); 
icons["green"].iconAnchor=new GPoint(10, 34); 
icons["green"].infoWindowAnchor=new GPoint(10, 8); 

// for red sand
icons["red"] = new GIcon(); 
icons["red"].image = "images/markerred.png"; 
icons["red"].iconSize=new GSize(27, 34); 
icons["red"].iconAnchor=new GPoint(10, 34); 
icons["red"].infoWindowAnchor=new GPoint(10, 8);

// for purple sand
icons["purple"] = new GIcon(); 
icons["purple"].image = "images/markerpurple.png"; 
icons["purple"].iconSize=new GSize(27, 34); 
icons["purple"].iconAnchor=new GPoint(10, 34); 
icons["purple"].infoWindowAnchor=new GPoint(10, 8); 

// for thank you heart
icons["heart"] = new GIcon(); 
icons["heart"].image = "images/heart.png"; 
icons["heart"].iconSize=new GSize(66, 57); 
icons["heart"].iconAnchor=new GPoint(10, 34); 
icons["heart"].infoWindowAnchor=new GPoint(30, 8); 

// for apollo11
icons["apollo"] = new GIcon(); 
icons["apollo"].image = "images/apollo.png"; 
icons["apollo"].iconSize=new GSize(66, 57); 
icons["apollo"].iconAnchor=new GPoint(10, 34); 
icons["apollo"].infoWindowAnchor=new GPoint(30, 8); 

// for on notice
icons["onnotice"] = new GIcon(); 
icons["onnotice"].image = "images/onnotice.png"; 
icons["onnotice"].iconSize=new GSize(87, 33); 
icons["onnotice"].iconAnchor=new GPoint(10, 34); 
icons["onnotice"].infoWindowAnchor=new GPoint(30, 8); 

// for on pixel
icons["pixel"] = new GIcon(); 
icons["pixel"].image = "images/pixel.png"; 
icons["pixel"].iconSize=new GSize(60, 60); 
icons["pixel"].iconAnchor=new GPoint(10, 34); 
icons["pixel"].infoWindowAnchor=new GPoint(30, 8); 



function get_icon(iconColor) {
   if ((typeof(iconColor)=="undefined") || (iconColor==null)) { 
      // iconColor = "red";
      return;
   }
   if (!icons[iconColor]) {
      icons[iconColor] = new GIcon(icons["red"]);
      icons[iconColor].image = "mapIcons/marker_"+ iconColor +".png";
   } 
   return icons[iconColor];
}


      // ==================================================
      // A function to create a tabbed marker and set up the event window
      // This version accepts a variable number of tabs, passed in the arrays htmls[] and labels[]
	  
      function createTabbedMarker(point,label,tabs,icon,id) {
        var marker;
        if (icon) {
           marker = new GMarker(point,get_icon(icon));
        } else {
           marker = new GMarker(point);
        }
        var marker_num = gmarkers.length;
        //marker.marker_num = marker_num;
        marker.tabs = tabs;
		//marker.abbr = abbr;
		marker.id = id;
		marker.index = gmarkers.length;
        gmarkers[marker_num] = marker;
		idmarkers[id] = marker;
				
        GEvent.addListener(gmarkers[marker_num], "click", function() {											   
        marker.openInfoWindowTabsHtml(gmarkers[marker_num].tabs);
		
		});
		  
		GEvent.addListener(idmarkers[id], "click", function() {
        marker.openInfoWindowTabsHtml(idmarkers[id].tabs);
		
		
        });
		
		
		
        // add a link in the sidebar html to open the infowindow for this marker
		// call the myclick() function and assign the marker number in the loop variable
        side_bar_html += '<li>' + '<a href="javascript:myclick(' + marker_num + ')">' + label + '</a></li>';
        return marker;
		
      }
      // ==================================================
     
      
	  
	  

function getNodeValue(Element) {
if ((Element.length>0) && Element[0] && Element[0].firstChild && Element[0].firstChild.nodeValue)
   return Element[0].firstChild.nodeValue;
}


      // create and define the global map
      var map = new GMap2(document.getElementById("sandmap"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
	  new GKeyboardHandler(map);
	  //map.setCenter(new GLatLng(21.94304553343818, -123.75), 2);
      map.setCenter(new GLatLng(21.769025, -110.039062), 2, G_SATELLITE_MAP);
	  //map.addOverlay(new GLayer("org.wikipedia.en"));
	  
  

GMap2.prototype.centerAndZoomOnBounds = function(bounds) {
   var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0;
   var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0;
   // var center = new GLatLng(center_lat,center_lng)
   var center = new GLatLng(21.769025, -110.039062);
   // map.setZoom(map.getBoundsZoomLevel(bounds)); 
   map.setCenter(center, 2);
   // map.setCenter(center, map.getBoundsZoomLevel(bounds)); - override 10/23/2010
   //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
   
   
}



	// Read the data from the xml file
   request = GXmlHttp.create();
   // open file and fake a data refresh 
   request.open("GET","sanddata.xml"+"?NoCache="+escape(Date()), true);
   request.onreadystatechange = processTabbedXML;
   request.send(null); 
   

    }
	

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
	
	

function processTabbedXML() {
   if (request.readyState == 4) {
      if ((request.status != 200) && (request.status != 304)) {
         alert("file not found");
         return;
      }
      // var xmlDoc = request.responseXML;
      var xmlDoc = GXml.parse(request.responseText);
      // obtain the array of markers and loop through it
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");

     
      
      gmarkers = new Array();
	  
	 // a loop iterator variable called i that starts with an initial value of 0. 
	 // The loop continues as long as i is less than the length of the records array.
	 // Finally, on each pass through the loop, i is incremented by 1.
      for (var i = 0; i < markers.length; i++) {
         // obtain the attributes of each marker
         var lat = parseFloat(markers[i].getAttribute("lat"));
         var lng = parseFloat(markers[i].getAttribute("lng"));
         var label = markers[i].getAttribute("label");
         var icon = markers[i].getAttribute("icon");
		 //var abbr = markers[i].getAttribute("abbr");
		 var id = markers[i].getAttribute("id");
		 var markerurl = markers[i].getAttribute("markerurl");
		 var displayurl = 'http://www.sandrific.com/index.php?id='
		// var id = 'zuma';
		

        // create a new LatLng object
         var point = new GLatLng(lat,lng);
         // get the tab info
         tabInfo = markers[i].getElementsByTagName("tab");
         tabs = new Array();
         if (tabInfo.length > 0) {

            for (var j = 0; j < tabInfo.length; j++) {
               var tabLabel = getNodeValue(tabInfo[j].getElementsByTagName("label"));
               var tabHtml = getNodeValue(tabInfo[j].getElementsByTagName("contents"));
              
               if ((j==0) && (tabInfo.length > 2)){ //  adjust the width so that the info window is large enough for this many tabs
                  tabHtml = '<div>' + tabHtml + '<div class="sharebar">' + '<a href="index.php?id='+id+'"><img src="images/link.jpg">' + displayurl+id + '</a></div>' + '</div>'; 
				  // html structure for the tab
				 
				  
               }
               tabs.push(new GInfoWindowTab(tabLabel,tabHtml)); // add the newly created marker to the end of the array
            }
         } else { 
            // alert("no tabs point "+i);
            var tabLabel = "Nothing";
            var tabHtml = markers[i].getAttribute("html");
            tabs.push(new GInfoWindowTab(tabLabel,tabHtml)); // add the newly created marker to the end of the array
			
			
         }      


         // create the marker
         var marker = createTabbedMarker(point,label,tabs,icon,id);
         bounds.extend(point);
		
		
	  // ============================ floats a div with specified ID over the map. 
      var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,0));
      pos.apply(document.getElementById("twitwidget"));
      map.getContainer().appendChild(document.getElementById("twitwidget"));
	  
	  //var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(124,0));
     //pos.apply(document.getElementById("button"));
      //map.getContainer().appendChild(document.getElementById("button"));
      // ============================

         map.addOverlay(marker);
		 
	

		 
		 
		// ========= If a parameter was passed, open the info window ==========
          //if (id) {
           // if (idmarkers[id]) {
             //GEvent.trigger(idmarkers[id],"click");
            //} else {

             // alert("id "+id+" does not match any marker");
            //}
          //}
          //if (index > -1) {
            //if (index < gmarkers.length) {
             // GEvent.trigger(gmarkers[index],"click");
            //} else {
              //alert("marker "+index+" does not exist");
            //}

        // }//end parameters
		
      }
	  	  
		
		
      map.centerAndZoomOnBounds(bounds);
	  
	  // put the assembled contents into the sidebar div
      document.getElementById("side_bar").innerHTML = side_bar_html;
      side_bar_html = "";
	  
	  //document.getElementById(idmarkers[id]).innerHTML = '<a href="' +url+ '" id=url target=_new>Link directly to this page by id</a> (id in xml file also entry &quot;name&quot; in sidebar menu)';
	  
       //document.getElementById("indexlink").innerHTML = '<a href="' +b+ '" id=url target=_new><img src=images/link.gif>- Link directly to this page by index</a> (position in gmarkers array)';
	  
	  
	  //function makeLink() {
       // var mapinfo = "lat=" + map.getCenter().lat().toFixed(6)
                   // + "&lng=" + map.getCenter().lng().toFixed(6)
                   // + "&zoom=" + map.getZoom()
                    //+ "&type=" + MapTypeId2UrlValue(map.getMapTypeId());
       // if (lastmarker) {
         // var a="http://umaitechdev/sand/index.php?id=" + lastmarker.id + "&" + mapinfo;
          //var b="http://umaitechdev/sand/index?marker=" + lastmarker.index + "&" + mapinfo;
      // } else {
          //var a = "http://umaitechdev/sand/index.php?"+mapinfo;
          //var b = a;
      // }}
	  
	  // Make the link the first time when the page opens
      //makeLink();

      // Make the link again whenever the map changes
     //GEvent.addListener(map, 'maptypeid_changed', makeLink);
      //GEvent.addListener(map, 'center_changed', makeLink);
      //GEvent.addListener(map, 'bounds_changed', makeLink);
      //GEvent.addListener(map, 'zoom_changed', makeLink);

 //GEvent.addListener(map, 'click', function() {
       // lastmarker = null;
       // makeLink();
       // infowindow.close();
        //});
 
 
 
// Marker ID / link to marker code. 
// This is called after the XML processing has completed. 
// Otherwise there aren't any markers to click!
		 	
//var id;
//var index = -1;
//var query = location.search.substring(1);
//var pairs = query.split(",");
//for (var i=0; i<pairs.length; i++) {
//var pos = pairs[i].indexOf("=");
//var argname = pairs[i].substring(0,pos).toLowerCase();
//var value = pairs[i].substring(pos+1).toLowerCase();
//if (argname == "marker") {
 //         var mymarker = parseInt(unescape(value));
 //         myclick(mymarker);
  //      }
//if (argname == "id") {
  //          var mymarker = parseInt(unescape(value));
  //         myclick(mymarker);
   //       }	  	  
//}//


// Marker ID / link to marker code. 
// This is called after the XML processing has completed. 
// Otherwise there aren't any markers to click!
// Before we go looking for the passed parameters, set some defaults
      // in case there are no parameters
      var id;
      var index = -1;

      // If there are any parameters at eh end of the URL, they will be in  location.search
      // looking something like  "?marker=3"

      // skip the first character, we are not interested in the "?"
      var query = location.search.substring(1);

      // split the rest at each "&" character to give a list of  "argname=value"  pairs
      var pairs = query.split("&");
      for (var i=0; i<pairs.length; i++) {
        // break each pair at the first "=" to obtain the argname and value
	var pos = pairs[i].indexOf("=");
	var argname = pairs[i].substring(0,pos).toLowerCase();
	var value = pairs[i].substring(pos+1).toLowerCase();

        // process each possible argname  -  use unescape() if theres any chance of spaces
        if (argname == "id") {id = unescape(value);}
        if (argname == "marker") {index = parseFloat(value);}
      }


// This is called at the end of marker processing
// If a parameter (marker ID) is passed, open the infowindow

			if (id) {
				if (idmarkers[id]) {
					GEvent.trigger(idmarkers[id],"click");
				} else {
					alert("id "+id+" does not match any marker");
				}
			}//end
      
   }
   
   
}


} // end of onLoad function

