/* Javascript used by the map.html (map search) template */

$(document).ready(function() {
    initialize_spotmap();
    spotmap.enableScrollWheelZoom();
    //spotmap.setMapType(G_HYBRID_MAP);
    spotmap.setMapType(G_NORMAL_MAP);
    var customUI = spotmap.getDefaultUI();
    customUI.controls.maptypecontrol = true;
    customUI.maptypes.physical = false;
    spotmap.setUI(customUI);
    // var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
    // spotmap.addControl(new GNavLabelControl(), bottomRight);
    GEvent.addListener(spotmap, "zoomend", updateSpots);
    GEvent.addListener(spotmap, "dragend", updateSpots);
    GEvent.addListener(spotmap, "maptypechanged", 
					   function(){  
						 window.location.hash = encodeMapState();
						 createCookie("mapstate",encodeMapState());});
    GEvent.addListener(spotmap, "infowindowopen", function() {$('#pre_name').focus();});
    GEvent.addListener(spotmap, "infowindowclose", function() {$('#i_location').focus();});
    GEvent.addListener(spotmap, "singlerightclick", newSpotWindow);
    if(form_location) {
      $('#i_location').val(form_location);
	  $('#go_button').click();
	} else {
	  var last_search = readCookie('lastsearch');
	  if(last_search) {
		$('#i_location').val(last_search);
	  }
	  if(!setMapStateFromURL() && !setMapStateFromCookie()) {
		$('#go_button').click();
	  }
	}
  });

function newSpotWindow(point, src, overlay) {
  var latlng = spotmap.fromContainerPixelToLatLng(point);
  var html = '<div class="add_spot_infowindow">';
  html += "<h3>Add a Spot</h3>";
  html += '<form action="/newspot" method="GET">';
  html += '<b>Spot Name: </b>';
  html += '<input id="pre_name" name="pre_name"></input>';
  html += '<input type="hidden" name="pre_coordinates" value="';
  html += latlng.lat() + ',' + latlng.lng();
  html += '"></input> ';
  html += '<input type="submit" value="Add Spot"> ';
  html += '</form>';
  html += "</div>";
  spotmap.openInfoWindowHtml(latlng, html);
}

function encodeMapState() {
  return spotmap.getCenter().lat() + "," + spotmap.getCenter().lng() + 
	"," + spotmap.getZoom() + "," + spotmap.getCurrentMapType().getName();
}

function setMapState(state_str) {
	  var a = state_str.split(",");
	  spotmap.setCenter(new GLatLng(parseFloat(a[0]), parseFloat(a[1])), 
						parseInt(a[2]));
      if(a[3] == "Map")
		spotmap.setMapType(G_NORMAL_MAP);
	  if(a[3] == "Satellite")
		spotmap.setMapType(G_SATELLITE_MAP);
	  if(a[3] == "Hybrid")
		spotmap.setMapType(G_HYBRID_MAP);
	  updateSpots();
}

function setMapStateFromURL() {
	if(window.location.hash && window.location.hash.length > 1) {
	  setMapState(window.location.hash.substr(1,500));
	  return(true);
	}
}

function setMapStateFromCookie() {
  var map_state = readCookie("mapstate");
  if( map_state ) {
	setMapState(map_state);
	return(true);
  }
}

function updateSpots() {
  /* update visible spots on map based on current bounding box and facets */
  var bb = spotmap.getBounds();
  window.location.hash = encodeMapState();
  createCookie("mapstate",encodeMapState());
  $.getJSON("rpc?method=locality_search"+
			"&slat=" + bb.getSouthWest().lat() +
			"&wlon=" + bb.getSouthWest().lng() +
			"&nlat=" + bb.getNorthEast().lat() +
			"&elon=" + bb.getNorthEast().lng(),
			processSpots
			);
}

/* Target of "Go" button */
var tabAccuracy = new Array(2,5,6,9,11,13,16,16,17);

function submitFacets() {
  address = $('#i_location').val();
  createCookie('lastsearch', address);
  if (geocoder) {
    geocoder.getLocations(address,
    function(response) {
      if(response.Status.code!=200){
        alert('Address "' + address + '" not found');
      } else {
        place = response.Placemark[0];
        accuracy = place.AddressDetails.Accuracy;
        spotmap.setCenter(new GLatLng(place.Point.coordinates[1],
             place.Point.coordinates[0]), tabAccuracy[accuracy]);
        updateSpots();
      }
    }
    );


/*	geocoder.getLatLng(address,
					   function(point) {
						 if (!point) {
						   alert("Address " + address + " not found");
						 } else {
						   spotmap.setCenter(point, 11);
						   updateSpots();
						 }
					   }
					   );
*/
  }
}

spot_data = {};  // all spots on map, indexed by ID
highlighted_spot = null;
/* Spot object, represents a spot currently being displayed on the map */
function Spot(id) {
  this.id = id;

  this.infoWindowHtml = function() {
    var html = '<div class="spot_info">'
    html += '<div class="title"><a href="/spot/'+this.id+'">'; 
	html += this.name + '</a></div>';
    html += '<div class="address">' + this.address + '</div>'
	html += '<div class="thumbnail">';
	html += '<a href="/spot/'+this.id+'"><img src="'+this.thumbnail+'"></a></div>';
    html += '<div class="features">';
	html += this.features;
    html += '</div>';
	return(html);
  };

  this.spotListHtml = function() {
	var html = '<div class=\"spot_marker\"><img src=\"'+marker_url("blue")+'\"></div>';
    html += '<div class=\"spot\">';
    html += '<div class="title"><a href="spot/' + id + '">'+this.name+'</a></div>';
    html += '<div class="address">' + this.address + '</div>'
    html += '<div class="rating"><div class="stars">' + this.rating + '</div></div>';
    html += '</div>';
	return(html);
  };

  this.openInfoWindow = function() {
	this.marker.openInfoWindow(this.infoWindowHtml());
  };

  this.highlightMarker = function() {
	this.marker.setImage(marker_url("orange"));
	var div = $('div#spot_'+this.id);
	div.addClass("highlight");
	div.find(".spot_marker img").attr('src', marker_url("orange"));
  };

  this.unhighlightMarker = function() {
	this.marker.setImage(marker_url("blue"));
	var div = $('div#spot_'+this.id);
	$('div#spot_'+this.id).removeClass("highlight");
	div.find(".spot_marker img").attr('src', marker_url("blue"));
  };
}


function addSpotToMap(spot) {
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.image = marker_url("blue");
  spot.icon = icon;
  var markerOptions = { icon:spot.icon };
  spot.marker = new GMarker(spot.latlng, markerOptions);
  GEvent.addListener(spot.marker, "mouseover", function() { highlightSpot(spot.id) });
  spot.marker.bindInfoWindowHtml(spot.infoWindowHtml());
  spotmap.addOverlay(spot.marker);
  if(highlighted_spot && highlighted_spot.id == spot.id)
	highlightSpot(spot.id);
  return(spot.marker);
}

function highlightSpot(id) {
  clearHighlight();
  spot_data[id].highlightMarker();
  highlighted_spot = spot_data[id];
}

function clearHighlight() {
  if(highlighted_spot) {
    highlighted_spot.unhighlightMarker();
	highlighted_spot = null;
  }
}



function processSpots(data){
  $("div#list").empty();
  var results_info = "";
  if(data.length == 0) {
    var loc = $('#i_location').val();
    results_info = "No matching spots found in search area";
	results_info += "<p><b>Right click on the map to add a spot</b>";
  }
  else {
    if(data.length > 49) {
      spot_count = 50;
      results_info = "Showing top "+spot_count+" of "+data.length+" matching spots.";
      results_info += "<br>(zoom in to see more)";
    }
    else {
      spot_count = data.length;
      results_info = "Showing "+spot_count+" matching spots.";
	}
  }
  $("div#list").append('<div id=\"result_info\">'+results_info+'</div>');
  var points = [ spotmap.getCenter() ];
  spot_data = { };  // Map: spot id -> spot object 
  for (var i = 0; i < spot_count; i++) {
    id = data[i].id;
    var spot = new Spot(id);
    spot.name = data[i].name;
    spot.rating = data[i].rating;
    spot.lat = data[i].lat;
    spot.lon = data[i].lon;
	spot.features = data[i].features;
	spot.address = data[i].address;
    spot_data[id] = spot;
    spot.thumbnail = data[i].thumbnail;
	var spothtml = spot.spotListHtml();
    $('div#list').append('<div class="previewcontainer" id="spot_'+ id + '">'+spothtml+'</div>');
	spot.latlng = new GLatLng(spot.lat, spot.lon);
    addSpotToMap(spot);
    points.push(spot.latlng);
  }
  $('.previewcontainer').hover( function(){ highlightSpot($(this).attr('id').substr(5,64)); }, function() {});
  $('.previewcontainer>.spot_marker').click( function(){
	  id = $(this).parent().attr('id').substr(5,64);
	  spot_data[id].openInfoWindow();
	});
  render_ratings();
  $('#i_location').focus();
  $('#i_location').select();
}


 
