// JavaScript Document
var map;
var toggleState = 0;
var trafficInfo;

var gdir;
var geocoder = null;
var addressMarker;

var gLocalSearch;
var gSelectedResults = [];
var gCurrentResults = [];
var gSearchForm;
	
    // Create our "tiny" marker icon
    var gSmallIcon = new GIcon();
    gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
    gSmallIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    gSmallIcon.iconSize = new GSize(12, 20);
    gSmallIcon.shadowSize = new GSize(22, 20);
    gSmallIcon.iconAnchor = new GPoint(6, 20);
    gSmallIcon.infoWindowAnchor = new GPoint(5, 1);	
	
function load() {
	if (GBrowserIsCompatible()) {
	  
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(32.71016, -117.161915), 14);
	
	trafficInfo = new GTrafficOverlay();
	var point = new GLatLng(32.70936, -117.161915);
	var info = '<div style="color:#330000; font-weight:bold;">2008 CNY Fair</div>';
	map.addOverlay(createMarker(point, info));
	
	gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);

	// Initialize the local searcher
	gLocalSearch = new GlocalSearch();
	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);

	}
}//end load()


function doSearch() {
	var zip = 92101;
	var cat = "parking";
	gLocalSearch.setCenterPoint(zip);
	gLocalSearch.execute(cat);
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
	if (!gLocalSearch.results) return;
	var directions = document.getElementById("directions");
	
	// Clear the map and the old search well
	directions.innerHTML = "";
	for (var i = 0; i < gCurrentResults.length; i++) {
		if (!gCurrentResults[i].selected()) {
			map.removeOverlay(gCurrentResults[i].marker());
		}
	}
	gCurrentResults = [];
	for (var i = 0; i < gLocalSearch.results.length; i++) {
		gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
	}
	
	var attribution = gLocalSearch.getAttribution();
	if (attribution) {
		document.getElementById("directions").appendChild(attribution);
	}
	
	// move the map to the first result
	var first = gLocalSearch.results[0];
	map.recenterOrPanToLatLng(new GPoint(parseFloat(first.lng), parseFloat(first.lat)));
	
	}
	
// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) {
	this.result_ = result;
	this.resultNode_ = this.unselectedHtml();
	document.getElementById("directions").appendChild(this.resultNode_);
	map.addOverlay(this.marker(gSmallIcon));
}



// Set up the map and the local searcher.
function OnLoad() {
	
	// Initialize the local searcher
	gLocalSearch = new GlocalSearch();
	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
	
	// Execute the initial search
}







//------------------------- search prototypes

    // Returns the GMap marker for this result, creating it with the given
    // icon if it has not already been created.
    LocalResult.prototype.marker = function(opt_icon) {
      if (this.marker_) return this.marker_;
      var marker = new GMarker(new GLatLng(parseFloat(this.result_.lat),
                                         parseFloat(this.result_.lng)),
                               opt_icon);
      GEvent.bind(marker, "click", this, function() {
        marker.openInfoWindow(this.selected() ? this.selectedHtml() :
                                                this.unselectedHtml());
      });
      this.marker_ = marker;
      return marker;
    }

    // "Saves" this result if it has not already been saved
    LocalResult.prototype.select = function() {
      if (!this.selected()) {
        this.selected_ = true;

        // Remove the old marker and add the new marker
        map.removeOverlay(this.marker());
        this.marker_ = null;
        map.addOverlay(this.marker(G_DEFAULT_ICON));

        // Add our result to the saved set
        document.getElementById("selected").appendChild(this.selectedHtml());

        // Remove the old search result from the search well
        this.resultNode_.parentNode.removeChild(this.resultNode_);
      }
    }

    // Returns the HTML we display for a result before it has been "saved"
    LocalResult.prototype.unselectedHtml = function() {
      var container = document.createElement("div");
      container.className = "unselected";
      container.appendChild(this.result_.html.cloneNode(true));
	  
	  /*
      var saveDiv = document.createElement("div");
      saveDiv.className = "select";
      saveDiv.innerHTML = "Save this location";
      GEvent.bindDom(saveDiv, "click", this, function() {
        map.closeInfoWindow();
        this.select();
        gSelectedResults.push(this);
      });
      container.appendChild(saveDiv);
	  */
      return container;
    }

    // Returns the HTML we display for a result after it has been "saved"
    LocalResult.prototype.selectedHtml = function() {
      return this.result_.html.cloneNode(true);
    }

    // Returns true if this result is currently "saved"
    LocalResult.prototype.selected = function() {
      return this.selected_;
    }

    GSearch.setOnLoadCallback(OnLoad);

//------------------------- end search prototypes







	
// Creates a marker at the given point with the given number label
function createMarker(point, info) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(info);
	});
	return marker;
}//end createMarker()

function toggleTraffic() {
	if (toggleState == 1) {
		map.removeOverlay(trafficInfo);
		toggleState = 0;
	} else {
		map.addOverlay(trafficInfo);
		toggleState = 1;
	}
}

    function setDirections(fromAddress, locale) {
		
	  document.getElementById("directions").innerHTML="";
      gdir.load("from: " + fromAddress + " to: " + "3rd Ave & J St, 92101",
                { "locale": locale });
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}