// Scenepeek Google Maps Wrapper v1.0
// For use on Scenepeek Website Only
//
// Notes:
// Zoom 0 - 19 (0 = far out, 19 = zoomed in)

function spmap(id, options) {
  this.obj_name = 'map';
  
  // Base Objects
  this.id = id;
  this.options = options || { };
  this.map_obj = new GMap2(spjs_get('map_'+this.id));
  
  // Initialize Map
  this.current_lat  = this.options.lat ? this.options.lat : 0;
  this.current_lon  = this.options.lon ? this.options.lon : 0;
  this.current_zoom = this.options.zoom ? this.options.zoom : 15;
  this.map_obj.setCenter(new GLatLng(this.current_lat, this.current_lon), this.current_zoom);
  this.map_obj.setUIToDefault();
  
  // *** Markers ***
  this.marker_obj = new MarkerManager(this.map_obj);        // Marker Manager
  this.markers = new sphash();                              // Marker Hash (sp_marker_objects)
  this.marker_groups = new sphash();                        // Marker Groups (name to hash of id -> marker)
  this.default_markergroup = 'default_group';
  
  // *** Directions ***
  this.directions_obj = new GDirections(this.map_obj, spjs_get('mapdirections_'+this.id));
  GEvent.addListener(this.directions_obj, "error", this.direction_error_handler.bind(this)); 
  GEvent.addListener(this.directions_obj, "load", this.direction_load_handler.bind(this)); 
}

spmap.prototype.iden = function() {
  alert(this.obj_name);
}

spmap.prototype.set_center = function(lat, lon) {
  var zoom = this.map_obj.getZoom();
  this.map_obj.setCenter(new GLatLng(lat, lon), zoom);
}

spmap.prototype.get_center = function() {
  var latlonobj = this.map_obj.getCenter();
  return {lat: latlonobj.lat(), lon: latlonobj.lng()};
}

spmap.prototype.set_zoom = function(zoom) {
  var latlonobj = this.map_obj.getCenter();
  this.map_obj.setCenter(latlonobj, zoom);
}

spmap.prototype.get_zoom = function() {
  return this.map_obj.getZoom();
}

spmap.prototype.refresh = function() {
  
}

///////////////////////////////////////////////////////////////
// Marker Group Functions

spmap.prototype.has_marker_group = function(name) {
  if(this.marker_groups.exist(name))
    return true;
  return false;
}

spmap.prototype.add_marker_group = function(name) {
  if(this.has_marker_group(name))
    return;
  this.marker_groups.set(name, new sphash());
}

spmap.prototype.remove_marker_group = function(name) {
  if(!this.has_marker_group(name))
    return;
  this.marker_groups.remove(name);
}

spmap.prototype.add_marker_to_group = function(group_name, sp_marker) {
  if(!this.has_marker_group(group_name))
    this.add_marker_group(group_name);
  hash = this.marker_groups.get(group_name);
  hash.set(sp_marker.id, sp_marker);
}

spmap.prototype.remove_marker_from_group = function(group_name, sp_marker) {
  if(!this.has_marker_group(group_name))
    return false;
  hash = this.marker_groups.get(group_name);
  hash.remove(sp_marker.id);
}

spmap.prototype.show_marker_group = function(group_name) {
  if(!this.marker_groups.exist(group_name)) {
    alert('unknown group ' + group_name);
    return false;
  }
  
  hash = this.marker_groups.get(group_name);
  keys = hash.keys();
  num = hash.size();
  for(var i=0;i<num;i++) {
    marker = hash.get(keys[i]);
    this.add_marker(marker);
  }
}

spmap.prototype.hide_marker_group = function(group_name) {
  if(!this.marker_groups.exist(group_name)) {
    alert('unknown group ' + group_name);
    return false;
  }
  
  hash = this.marker_groups.get(group_name);
  keys = hash.keys();
  num = hash.size();
  for(var i=0;i<num;i++) {
    marker = hash.get(keys[i]);
    this.remove_marker(marker.id);
  }
}

///////////////////////////////////////////////////////////////
// Marker Functions

spmap.prototype.has_marker = function(marker_id) {
  if(this.markers.exist(marker_id))
    return true;
  return false;
}

spmap.prototype.add_marker = function(marker) {

  if(this.has_marker(marker.id)) {
    base_debug("spmap error::add_marker marker id exists already: " + marker.id);
    return;
  }
  
  this.markers.set(marker.id, marker);
  this.marker_obj.addMarker(marker.g_marker, 3);
  this.marker_obj.refresh();
}

spmap.prototype.remove_marker = function(marker_id) {
  
  if(!this.has_marker(marker_id)) {
    base_debug("spmap error::remove_marker marker id does not exist: " + marker_id);
    return;
  }
    
  var marker = this.markers.get(marker_id);
  this.markers.remove(marker_id);
  this.marker_obj.removeMarker(marker.g_marker);
}

spmap.prototype.goto_marker = function(marker_id) {
  if(!this.has_marker(marker_id)) {
    base_debug("spmap error::goto_marker marker id does not exist: " + marker_id);
    return;
  }

  var marker = this.markers.get(marker_id);
  this.map_obj.panTo(marker.g_latlonobj);
}

spmap.prototype.goto_marker_set_center = function(marker_id) {
  if(!this.has_marker(marker_id)) {
    base_debug("spmap error::goto_marker marker id does not exist: " + marker_id);
    return;
  }

  var marker = this.markers.get(marker_id);
  this.map_obj.setCenter(marker.g_latlonobj);
}

spmap.prototype.remove_all_marks = function() {
  this.markers.clear();
  this.marker_obj.clearMarkers();
}

///////////////////////////////////////////////////////////////
// Direction Functions

// General Get Directions Function
spmap.prototype.get_directions = function(str, options) {
  if(options == null) options = {};
  var direction_options = {};
  
  // Determine Travel Mode (TODO: get mass transit)
  var travel_mode = options.travel_mode ? options.travel_mode : 'car';
  if(travel_mode == 'car')
    direction_options.travelMode = G_TRAVEL_MODE_DRIVING;
  else if(travel_mode == 'walk')
    direction_options.travelMode = G_TRAVEL_MODE_WALKING ;
  
  // Get Directions
  this.directions_obj.load(str, direction_options);
}

spmap.prototype.get_directions_from = function(from_str, options) {
  if(options == null) 
    options = {};

  var str = "from: " + from_str + " ";
  var keys = this.markers.keys();
  var first_marker = this.markers.get(keys[0]);
  
  if(first_marker.address != "")
    str += "to: " + first_marker.address;
  else
    str += "to: " + first_marker.lat + "," + first_marker.lon;

  this.get_directions(str, options);
  this.marker_obj.hide();
}

spmap.prototype.clear_directions = function(str) {
  this.directions_obj.clear();
  this.marker_obj.show();
}

spmap.prototype.direction_load_handler = function() {
  map_resetdirections(this.id);
}

spmap.prototype.direction_error_handler = function() {
  if (this.directions_obj.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: " + this.directions_obj.getStatus().code);  
  else if (this.directions_obj.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: " + this.directions_obj.getStatus().code);  
  else if (this.directions_obj.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: " + this.directions_obj.getStatus().code);  
  else if (this.directions_obj.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: " + this.directions_obj.getStatus().code);  
  else if (this.directions_obj.getStatus().code == G_GEO_BAD_REQUEST)  
    alert("A directions request could not be successfully parsed.\n Error code: " + this.directions_obj.getStatus().code);  
  else alert("An unknown error occurred.");
  
  map_resetdirections(this.id);
}  


/////////////////////////////////////////////////////////////////////////////////////////////
// SP Marker

function gmaps_create_marker_baseicon() {
  // Base Icon
  var baseIcon = new GIcon(G_DEFAULT_ICON);
  baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
  return baseIcon;
}

function gmaps_create_marker_icon(num) {
  var icon = new GIcon(gmaps_create_marker_baseicon());
  
  if(num < 0)
    return icon;
  
  var letter = String.fromCharCode("A".charCodeAt(0) + num);
  
  icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
  return icon;
}

function spmarker(id, name, lat, lon, options, num) {
  // Base Variables
  this.id = id;
  this.name = name;
  this.lat = lat;
  this.lon = lon;
  this.options = options || { };

  // Extra Variables
  this.address = this.options.address ? this.options.address : "";
  this.icon_label = this.options.icon_label !== undefined ? this.options.icon_label : -1;

  // Get Icon
  var g_icon = gmaps_create_marker_icon(this.icon_label);
  
  var g_marker_options = {icon: g_icon};
  
  // Initialize Google Objects
  this.g_latlonobj = new GLatLng(lat, lon);
  this.g_marker = new GMarker(this.g_latlonobj, g_marker_options);
  
  // Register callback
  // TODO: delete binding to free memory
  GEvent.bind(this.g_marker, "click", this, function() {
   this.g_marker.openInfoWindowHtml(this.popup_html());
  });
}

spmarker.prototype.popup_html = function() {
  html  = '<div style="font-weight:bold;font-size:14px">';
  html += this.name;
  html += '</div>';
  return html;
}
