﻿// === EDITABLE REGION ====

	// === Map options
	var MAP_CONTROL = "large";                  //large or small pan/zoom control used on Google Maps. Appears in the top left corner of the map by default. - options are (small,large, none)
	var ENABLE_SCROLL_WHEEL_ZOOM = false;       //zoom with mouse scroll wheel
	var ENABLE_MAP_TYPE_CONTROL = true;         //shows map type option on top right (map, satellite, hybrid, etc)
	var ENABLE_OVERVIEW_MAP_CONTROL = false;    //shows smaller
	var ENABLE_SMALL_ZOOM_CONTROL = true;       //a small zoom control (no panning controls) used in the small map blowup windows used to display driving directions steps on Google Maps.
	
	// === global variables
	var POINT = null;
	var MAXZOOM = 10;	
	var ADDRESS = "5800 Universal Blvd, Orlando, FL, 32819";
	var LOCATIONNAME = "Hard Rock Hotel Orlando";
	var LOCATIONNUMBER = "1.888.832.7155";
	var DEFAULTZOOM = 12;
	var MAPWIDTH = 600;
	var MAPHEIGHT= 300;
	var STARTADDRESS = "";
		 	
	var GOOGLE_DIRECTIONS_DIV_ID = "googleDirections";
	var GOOGLE_MAP_DIV_ID = "googleMap";
    
	
// === END EDITABLE REGION ====
	
	// === global objects used
	var geocoder;
	var map;
	var directions;
	var bounds;
	var reasons=[];
	var directionsInitTimerID = null;
	
	
	
	function loadDirections(startAddressID){
	    if(startAddressID != null &&  startAddressID != "")   
            STARTADDRESS = document.getElementById(startAddressID).value;
        else STARTADDRESS = "";
        loadMap();
    }
	
   function loadMap()
   {	
    
	var mapDiv = document.getElementById(GOOGLE_MAP_DIV_ID);
    mapDiv.style.height = MAPHEIGHT + "px";
    mapDiv.style.width = MAPWIDTH + "px";
  	mapDiv.innerHTML = "Loading Map .. Please wait";
  	  	     
      // === Create new map object
    map = new GMap2(mapDiv);
    
    if(ENABLE_SCROLL_WHEEL_ZOOM) map.enableScrollWheelZoom();
    if(ENABLE_MAP_TYPE_CONTROL) map.addControl(new GMapTypeControl());
    
    if(MAP_CONTROL.toLower == "large") map.addControl(new GLargeMapControl());
    else if(MAP_CONTROL.toLower == "small") map.addControl(new GSmallMapControl());    
    
    if(ENABLE_OVERVIEW_MAP_CONTROL) map.addControl(new GOverviewMapControl());
 
    if(ENABLE_SMALL_ZOOM_CONTROL) map.addControl(new GSmallZoomControl());
    
    geocoder = new GClientGeocoder(); 
    geocoder.getLocations(ADDRESS, setMap);			
    bounds = new GLatLngBounds(); 
       	
 } 
 
 
 // === function called after map is done being initialized
 function mapInitialized(){
     document.getElementById(GOOGLE_DIRECTIONS_DIV_ID).innerHTML = "";
    if(STARTADDRESS != "") {
        getDirections(); 
    }

 }
 
  // === function called after directions is done being initialized	 
 function directionsInitialized(){ 
    directionsStyle();    
    var directionsDiv = document.getElementById(GOOGLE_DIRECTIONS_DIV_ID);
    //directionsDiv.innerHTML = "Directions to " +LOCATIONNAME+" from "+ STARTADDRESS+" " + directionsDiv.innerHTML; 
    directionsDiv.innerHTML = "Directions to " +LOCATIONNAME+ directionsDiv.innerHTML;
    return true;	  
 }
 
 
 function setMap(response){
 
        var place = response.Placemark[0];
        POINT = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        map.setCenter(POINT, DEFAULTZOOM);
        
        //if getting directions, it already adds a marker to destination, so no need to add one
        if(STARTADDRESS == "") {
	        createMarker(POINT, ADDRESS,LOCATIONNAME,LOCATIONNUMBER); 
	    } 	    
	    mapInitialized();
 }
 
 
 // === function to add class names to google directions elements so that it is more customizable
 function directionsStyle(){
   var divs = document.getElementById(GOOGLE_DIRECTIONS_DIV_ID).getElementsByTagName('div');    
    for (var x=0; x<divs.length; x++){       
        if(divs[x].getAttribute('jsselect') == "Placemark"){     
          divs[x].firstChild.className = "headerTable";
        }
    }
    
    var imgs = document.getElementById(GOOGLE_DIRECTIONS_DIV_ID).getElementsByTagName('img'); 
      
    for (var y=0; y<imgs.length; y++){       
        if(imgs[y].src.indexOf("icon_greenA") != -1){ 
         
          imgs[y].src = "/images/icon_greenA.gif";
        }
        
        if(imgs[y].src.indexOf("icon_greenB") != -1){     
          imgs[y].src = "/images/icon_greenB.gif";
        }
    }
    
    
 }
 
 // === keep checking to see when directions is finished loading
function checkDirectionsLoaded(){ 
      if(directions.getStatus().code == 200){
               directionsInitialized()
          }else  { 
            directionsInitTimerID = setTimeout('directionsInitialized()',500);
            return false;    	  
          }
}
 
 function getDirections() {     
        var directionsDiv = document.getElementById(GOOGLE_DIRECTIONS_DIV_ID);
                     
        // === Create new directions object
        directions = new GDirections(map, directionsDiv);          
        
        directions.load("from: "+STARTADDRESS+" to: "+LOCATIONNAME+"@"+ POINT.lat() + "," + POINT.lng());
        directionsDiv.style.width = (MAPWIDTH - 10 )+ "px";   
        //directionsDiv.style.height = (MAPHEIGHT - 10) + "px";
        directionsDiv.style.display = "block";
        
        // === catch Directions errors ===
        GEvent.addListener(directions, "error", function() {
            var code = directions.getStatus().code;
            var reason="Code "+code;
            if (reasons[code]) {
                reason = reasons[code]
            } 
            
            // === show error ===
            //alert("Failed to obtain directions: "+reason);
             directionsDiv.innerHTML = directionsDiv.innerHTML + reason;
             
            if(directionsInitTimerID) {
                clearTimeout(directionsInitTimerID);
            }
            
        });
        
        // === Check when Directions is loaded ===
        checkDirectionsLoaded();
        
         // === Array for decoding the failure codes ===
         
          reasons[G_GEO_SUCCESS]            = "Success";
          reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
          reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
          reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
          reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
          reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
          reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
          reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
          reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
          reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
      	  
}

function createMarker(point, address, name, phone){
var infoHtml = "<div class='mapInfoWindow'><span class='mapInfoWindowTextTitle'>"+name+"</span><div class='colLeft'><span class='mapInfoWindowTextAddress'>" +address.replace(",","<br/>") +"</span><br/><span class='mapInfoWindowTextPhone'>" +phone+"</span></div><div class='colRight'><img src='/images/hardrockhotel_tn.jpg' /></div><br/></div>";   
var marker = new GMarker(point);
    GEvent.addListener(marker, "mouseover", function() {
          //marker.openInfoWindowHtml("<div class='mapInfoWindow'><span class='mapInfoWindowTextTitle'>"+name+"</span><br/><span class='mapInfoWindowTextAddress'>" +address.replace(",","<br/>") +"</span><br/><span class='mapInfoWindowTextPhone'>" +phone+"</span></div>");
          marker.openInfoWindowHtml("'"+infoHtml+"'");
    });

GEvent.addListener(marker, "click", function() {
         // marker.showMapBlowup();
          marker.openInfoWindowHtml("'"+infoHtml+"'");
          
    }); 

   bounds.extend(point);   
   map.addOverlay(marker);
return marker;

}


function centerMarkers(){
          // ==== determine the zoom level from the bounds =====
          var zoom = map.getBoundsZoomLevel(bounds) <= MAXZOOM ? map.getBoundsZoomLevel(bounds) : MAXZOOM ;
		  
		  map.setZoom(zoom);

          // ==== determine the center from the 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));
        //map.setCenter(bounds.getCenter()); 
}


function centerAddress(address, zoom) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {		  
      } else {  	     
	  map.panTo(point);     
      }
    }
  );
}

