// Copyright 2007 Google Inc. All Rights Reserved.



/*
** An internal data holding object that implements the Searchable interface
*/
var Placename = function() {}

Placename.prototype.makeSnippet = function(marker) { 
  /**
   * Ok, this is ugly because we have to consturct the snippet from scratch.
   *
   * It's even uglier because the link needs a handler to the marker, so it
   * can call an openInfoWindow.  Augh.
  */
  var me = this;
  var div = document.createElement("div");

  var link = window.document.createElement("A");
  var icon = marker.getIcon();
  if (gBrowser.alphaPngIsBroken()) {
    /* Yes, this is gross. No, it's not really an img, but cope */
    img = document.createElement("div");
    img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(' +
                       'sizingMethod=crop,src="' + icon.image + '")';
    img.style.width = icon.iconSize.width;
    img.style.height = icon.iconSize.height;
    img.innerHTML = "&nbsp;"
  } else {
    img = makeImage(document, icon.image);
    img.style.marginTop = px(3);
    img.style.marginRight = px(3);
  }

  var d3 = document.createElement("div");
  d3.innerHTML = me.name;
  link.appendChild(d3);
  link.setAttribute("href", "#");
  link.onclick = function() {
    // gMap.panTo(marker.getPoint());
    marker.openInfoWindowHtml(me.makeHTML(me));
  }
  /*
  div.appendChild(img);
  div.appendChild(link);
  div.appendChild(document.createElement("br"));
  var span = document.createElement("span");
  span.appendChild(document.createTextNode((me.brief)?(me.brief):(me.desc)));
  span.setAttribute("class", "snippet");
  div.appendChild(span);
  div.style.verticalAlign = "bottom";
  */

  var td1 = document.createElement("td");
  td1.style.backgroundColor = "#FFFFFF";
  td1.appendChild(img);

  var div2 = document.createElement("div");
  div2.appendChild(link);
  // div.appendChild(document.createElement("br"));
  var span = document.createElement("div");
  var html = me.brief ? (me.brief):(me.desc);
  span.innerHTML = html;
  span.setAttribute("class", "snippet");
  span.className = "snippet";
  span.style.paddingLeft = 0;
  span.style.whiteSpace = "normal";
  div2.appendChild(span);

  var td2 = document.createElement("td");
  td2.appendChild(div2);

  var tr = document.createElement("tr");
  tr.appendChild(td1);
  tr.appendChild(td2);
  var tbody = document.createElement("tbody");
  tbody.appendChild(tr);
  var table = document.createElement("table");
  table.appendChild(tbody);

  div.appendChild(table);
  div.style.width = "250px";

  return(div);
}

Placename.prototype.makeHTML = function(me) {
  var img = marker_icons["red"];

  var html =  "<div style='width: 250px;'><small>"
      + "<b>Feature:</b> " + me.name + "<br>"
      + ((me.type != "XX") ? ("<b>Type:</b> "
          + me.parent.typeToString(me.type)[0] + "<br>") : "")
      + "<b>Location:</b> " + me.point.lat() + "N, " + me.point.lng() + "<br>"
      + ((me.diam > 0) ? ("<b>Size:</b> " + me.diam + "km / "
          + Math.round(me.diam*0.621371192) + "mi<br>") : "")
      + ((me.type != "XX") ? "<b>Named for:</b> " : "") + me.desc
      + "</small></div>";
  return(html);
}

Placename.prototype.makeMarker = function() { 
  var me = this;
  var marker = new GMarker(me.point, marker_icons["red"]);
  GEvent.addListener(marker, "click", function() { 
    marker.openInfoWindowHtml(me.makeHTML(me));
  });

  return(marker);
}

var Placenames = Class.create();
Placenames.prototype.initialize = function(map, search) {
  var me = this;
  me.data_ = LUNAR_DATA;
  me.loaded_ = false;

  var markers = me.data_;

  var mS = Placename.prototype.makeSnippet;
  var mH = Placename.prototype.makeHTML;
  var mM = Placename.prototype.makeMarker;
  var gll = GLatLng;
  for (var i = markers.length-1; i >= 0; i--) {
     var e = markers[i];
     e.parent = me;
     e.point = new gll(e.y, e.x);
     e.makeSnippet = mS;
     e.makeHTML = mH;
     e.makeMarker = mM;
  }

  me.loaded_ = true;
  search.addSearchTermsLunar(me.data_);
}

Placenames.prototype.typeToString = function (type) {
  return(placenameTypes[type]);
}

placenameTypes = {
 "AL": ["Albedo Feature", "Geographic area distinguished by amount of reflected light"], 
 "AR": ["Arcus, arcūs", "Arc-shaped feature"], 
 "AS": ["Astrum, astra", "Radial-patterned features on Venus"], 
 "CA": ["Catena, catenae", "Chain of craters"], 
 "CB": ["Cavus, cavi", "Hollows, irregular steep-sided depressions usually in arrays or clusters"], 
 "CH": ["Chaos", "Distinctive area of broken terrain"], 
 "CM": ["Chasma, chasmata", "A deep, elongated, steep-sided depression"], 
 "CO": ["Colles", "Small hills or knobs"], 
 "CR": ["Corona, coronae", "Ovoid-shaped feature"], 
 "AA": ["Crater, craters", "A circular depression"], 
 "DO": ["Dorsum, dorsa", "Ridge"], 
 "ER": ["Eruptive center", "Active volcanic centers on Io"], 
 "FA": ["Facula, faculae", "Bright spot"], 
 "FR": ["Farrum, farra", "Pancake-like structure, or a row of such structures"], 
 "FE": ["Flexus, flexūs", "A very low curvilinear ridge with a scalloped pattern"], 
 "FL": ["Fluctus, fluctūs", "Flow terrain"], 
 "FM": ["Flumen, flumina", "Channel on Titan that might carry liquid"], 
 "FO": ["Fossa, fossae", "Long, narrow depression"], 
 "LA": ["Labes, labēs", "Landslide"], 
 "LB": ["Labyrinthus, labyrinthi", "Complex of intersecting valleys or ridges."], 
 "LC": ["Lacus", "'Lake' or small plain; on Titan, a 'lake' or small, dark plain with discrete, sharp boundaries"], 
 "LF": ["Landing site name", "Lunar features at or near Apollo landing sites"], 
 "LG": ["Large ringed feature", "Cryptic ringed features"], 
 "LE": ["Lenticula, lenticulae", "Small dark spots on Europa"], 
 "LI": ["Linea, lineae", "A dark or bright elongate marking, may be curved or straight"], 
 "LN": ["Lingula, lingulae", "Extension of plateau having rounded lobate or tongue-like boundaries"], 
 "MA": ["Macula, maculae", "Dark spot, may be irregular"], 
 "ME": ["Mare, maria", "'Sea'; large circular plain"], 
 "MN": ["Mensa, mensae", "A flat-topped prominence with cliff-like edges"], 
 "MO": ["Mons, montes", "Mountain"], 
 "OC": ["Oceanus", "A very large dark area on the moon"], 
 "PA": ["Palus, paludes", "'Swamp'; small plain"], 
 "PE": ["Patera, paterae", "An irregular crater, or a complex one with scalloped edges"], 
 "PL": ["Planitia, planitiae", "Low plain"], 
 "PM": ["Planum, plana", "Plateau or high plain"], 
 "PU": ["Plume", "Cryo-volcanic features on Triton"], 
 "PR": ["Promontorium, promontoria", "'Cape'; headland promontoria"], 
 "RE": ["Regio, regiones", "A large area marked by reflectivity or color distinctions from adjacent areas, or a broad geographic region"], 
 "RT": ["Reticulum, reticula", "reticular (netlike) pattern on Venus"], 
 "RI": ["Rima, rimae", "Fissure"], 
 "RU": ["Rupes, rupēs", "Scarp"], 
 "SF": ["Satellite Feature", "A feature that shares the name of an associated feature."], 
 "SC": ["Scopulus, scopuli", "Lobate or irregular scarp"], 
 "SI": ["Sinus, sinūs", "'Bay'; small plain"], 
 "SU": ["Sulcus, sulci", "Subparallel furrows and ridges"], 
 "TA": ["Terra, terrae", "Extensive land mass"], 
 "TE": ["Tessera, tesserae", "Tile-like, polygonal terrain"], 
 "TH": ["Tholus, tholi", "Small domical mountain or hill"], 
 "UN": ["Undae", "Dunes"], 
 "VA": ["Vallis, valles", "Valley"], 
 "VS": ["Vastitas, vastitates", "Extensive plain"], 
 "VI" : ["Virga, virgae", "A streak or stripe of color"],
 "XX" : [""] // Used for placemarks not from the gazetteer
}

/* Not really a unittest */
/*
 * Search results need to:
 *  Generate a snippet.
 *  Generate a marker.
 */
function testPlacenames(map, search) {
  var p = new Placenames(map, search);
  var snippets = [];
  var markers = [];

  var f = function() { 
    if (p.loaded_) {
      var result = search.textSearch("Dorsum");
      document.my_result = result;
      str = "Result length: " + result.length;
      for (var i = 0 ; i < result.length ; i++) {
        var marker = result[i].makeMarker();
        markers.push(marker);
        snippets.push(result[i].makeSnippet(marker));
      }

      var sidebar = document.getElementById("sidebar");
      for (var i = 0 ; i < snippets.length ; i++) {
        sidebar.appendChild(snippets[i]);
        map.addOverlay(markers[i]);
      }
    }

  }
  setTimeout(f, 1000);
}

