var geocoder = new GClientGeocoder();
//geocoder.setBaseCountryCode(".ca");
var map = null;
var vancouverCenterPoint = new GLatLng(49.263588,-123.138565);
var markers = new Array();
var yourRegionMarker = null;

// ====== Array for decoding the failure codes ======
var reasons=[];
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[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";


function initMap(elementId, initialFocusAddress, zoom) {
    if (map === null) {
        map = new GMap2(document.getElementById(elementId));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
    }
    if (geocoder) {
      geocoder.getLatLng(
        initialFocusAddress,
        function(point) {
          if (!point) {
            log.error("initial focus address for map not found " + initialFocusAddress);
          } else {
            map.setCenter(point, zoom);
          }
        });
    } // END if (geocoder)  
}

// No custom icon provided
function showAddress(address, description, elementId) {
	showAddressWithCustomMarker(address, description, elementId, null);
}

// Custom icon provided
function showAddressWithCustomMarker(address, description, elementId, iconURL) {
	if (map === null) {
		map = new GMap2(document.getElementById(elementId));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
    }
	if (geocoder) {
	  geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	        alert(address + " was not found.\n\n Please check the address and resubmit.");
	      } else {
	        map.setCenter(point, 15);
	        var marker = null;
	        
	        // Has a custom icon been provided
	        if (iconURL === null) {
	        	marker = new GMarker(point);
	        } else {
	        	// Set up custom icon
		      	var customIcon = new GIcon(G_DEFAULT_ICON);
				customIcon.image = iconURL;
				// Set up our GMarkerOptions object
				markerOptions = { icon:customIcon };

	        	marker = new GMarker(point, markerOptions);
	        }
	        
	        map.addOverlay(marker); // Set maker
	        
	        // Determine what to display
		    if (description === null) {
		        marker.openInfoWindowHtml(address);
	        } else {
	        	marker.openInfoWindowHtml(description);
	        } // END if (description == null)
	        	        
	      } // END if (!point)
	    }
	  );
	}
}

/**
*/
function focusOnMarker(markerNumber) {
    if (markerNumber < markers.length) {
        GEvent.trigger(markers[markerNumber], "click");
        map.setCenter(markers[markerNumber].getPoint(), 15);
    } 
}

function focusOnRegion(region) {

    var updatedRegion = region.toLowerCase();
    if ((updatedRegion.indexOf("bc") < 0 ) && (updatedRegion.indexOf("british columbia"))) {
        updatedRegion += ", BC";
    }
    
    if (updatedRegion.indexOf("canada") < 0 ) {
        updatedRegion += ", canada";
    }

    if (geocoder) {
      geocoder.getLatLng(
        updatedRegion,
        function(point) {
        
          // Hide existing you are here marker if it exists
          if (yourRegionMarker !== null) { 
            yourRegionMarker.hide(); //
          }
          
          if (!point) {
            log.error(region + " was not found.\n\n Please check the address and resubmit." + point.Status.code);
          } else {
            map.setCenter(point, 12);
                        
            var iconOptions = {};
			iconOptions.primaryColor = "#FFFF00";
			iconOptions.strokeColor = "#000000";
			iconOptions.label = "";
			iconOptions.labelColor = "#000000";
			iconOptions.addStar = false;
			iconOptions.starPrimaryColor = "#FFFF00";
			iconOptions.starStrokeColor = "#0000FF";
            var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
            
            yourRegionMarker = new GMarker(point, {icon: icon, draggable:false});
            map.addOverlay(yourRegionMarker); // Set "You are here" maker
            yourRegionMarker.openInfoWindowHtml("<b>You are here</b>");
            
          } // END if (!point)
        }
      );
    }

}


// No custom icon provided
function addAddress(markerIndex, address, description, elementId, markerId) {
    // Create the map if it does not already exist
    if (map === null) {
        map = new GMap2(document.getElementById(elementId));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        map.enableScrollWheelZoom();
        
    }
    
    if (geocoder) {
      geocoder.getLatLng(
        address,
        function(point) {
          if (!point) {
            log.error(address + " was not found.\n\n Please check the address and resubmit.");
          } else {
            log.info(address + " - " + point.toString());
            
            var marker = null;
                        
            var iconOptions = {};
            iconOptions.primaryColor = "#FF3333";
            iconOptions.strokeColor = "#000000";
            iconOptions.label = markerIndex + "";
            iconOptions.labelColor = "#ffffff";
            iconOptions.addStar = false;
            iconOptions.starPrimaryColor = "#FFFF00";
            iconOptions.starStrokeColor = "#0000FF";
            var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
            
            marker = new GMarker(point, {icon: icon, draggable:false});
            
            map.addOverlay(marker); // Set maker
            
            // Determine what to display
            if (description == null) {
                marker.bindInfoWindowHtml(address);
            } else {
                marker.bindInfoWindowHtml(description);
            } // END if (description == null)
            
            //markers.push(marker); // Keep track of the marker
            markers[markerIndex] = marker;
            // Update external link marker
            if (markerId != null) {
                document.getElementById(markerId).innerHTML = "";
                var img = document.createElement("img");
                img.setAttribute("src", icon.image);
                img.setAttribute("border", 0);
                document.getElementById(markerId).appendChild(img);
            }
          } // END if (!point)
        }
      );
    } // END if (geocoder)
    
    /*
    if (geocoder) {
      geocoder.getLocations(
        address,
        function(result) {
          if (result.Status.code != G_GEO_SUCCESS) {
            log.error(address + " was not found.\n\n Please check the address and resubmit." + reasons[result.Status.code]);
          } else {
            var point = result.Placemark[0].Point;
            log.info(address + " - " + point.toString());

            var marker = null;
			var iconOptions = {};
			iconOptions.primaryColor = "#FF3333";
			iconOptions.strokeColor = "#000000";
			iconOptions.label = iconLabel;
			iconOptions.labelColor = "#ffffff";
			iconOptions.addStar = false;
			iconOptions.starPrimaryColor = "#FFFF00";
			iconOptions.starStrokeColor = "#0000FF";
			var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
			
            marker = new GMarker(point, {icon: icon, draggable:false});
			
            map.addOverlay(marker); // Set maker
            
            // Determine what to display
            if (description === null) {
                marker.bindInfoWindowHtml(address);
            } else {
                marker.bindInfoWindowHtml(description);
            } // END if (description == null)
            
            markers.push(marker); // Keep track of the marker
            
            // Update external link marker
            if (markerId !== null) {
			    document.getElementById(markerId).innerHTML = "";
			    var img = document.createElement("img");
			    img.setAttribute("src", icon.image);
			    img.setAttribute("border", 0);
			    document.getElementById(markerId).appendChild(img);
		    }
          } // END if (!point)
        }
      );
    } // END if (geocoder)
    */
}



function addPoint(markerIndex, lat, long, address, description, markerId) {

		// Create the map if it does not already exist
		if (map === null) {
		    map = new GMap2(document.getElementById(elementId));
		    map.addControl(new GLargeMapControl());
		    map.addControl(new GMapTypeControl());
		    map.addControl(new GScaleControl());
		    map.enableScrollWheelZoom();
		    
		}
	  var point = new GLatLng(lat, long);
      var marker = null;
                  
      var iconOptions = {};
      iconOptions.primaryColor = "#FF3333";
      iconOptions.strokeColor = "#000000";
      iconOptions.label = markerIndex + "";
      iconOptions.labelColor = "#ffffff";
      iconOptions.addStar = false;
      iconOptions.starPrimaryColor = "#FFFF00";
      iconOptions.starStrokeColor = "#0000FF";
      var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
      
      marker = new GMarker(point, {icon: icon, draggable:false});
      map.setCenter(vancouverCenterPoint, 10);
      map.addOverlay(marker); // Set maker
      
      // Determine what to display
      if (description == null) {
          marker.bindInfoWindowHtml(address);
      } else {
          marker.bindInfoWindowHtml(description);
      } // END if (description == null)
      
      //markers.push(marker); // Keep track of the marker
      markers[markerIndex] = marker;
      // Update external link marker
      if (markerId != null) {
          document.getElementById(markerId).innerHTML = "";
          var img = document.createElement("img");
          img.setAttribute("src", icon.image);
          img.setAttribute("border", 0);
          document.getElementById(markerId).appendChild(img);
      }
}