//<![CDATA[
// global arrays to hold copies of the markers and html used by the sidebar
var gmarkers = [];
var htmls = [];
var markersitios = []; // The places with a marker
var markercountries = []; //The countries of the markers

// This function picks up the sidebar click and opens the corresponding info window
function myclick(i) {
  gmarkers[i].openInfoWindowHtml(htmls[i]);
}

function replaceByNBSP(text) {
  var words = text.split(' ');
  var newtext = words[0];
  for (var i = 1; i < words.length; i++) {
    newtext += '&nbsp;';
    //newtext += '-';
    newtext += words[i];
  }
  return newtext;
}

function load(inputpath, ciudadesxml) {
  //GLog.write(">> Start loading..." + inputpath+ " y " + ciudadesxml);
  if (GBrowserIsCompatible()) {
    //GLog.write(">> Browser is compatible...");
    var map = new GMap2(document.getElementById("map"));
    //map.setMapType(G_DEFAULT_MAP_TYPES);
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    map.addControl(new GOverviewMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(5, 150), 2);
    //map.setMapType( G_HYBRID_TYPE );
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    //Deal with input path
    if (! inputpath)
      inputpath = '.';
    // Create our "south park javi" sitio icon
    var iconjavi = new GIcon();
    iconjavi.image = inputpath+"/javi.png";
    //iconjavi.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    //iconjavi.iconSize = new GSize(25, 45);
    //iconjavi.iconAnchor = new GPoint(12, 45);
    //iconjavi.infoWindowAnchor = new GPoint(12, 22);
    iconjavi.iconSize = new GSize(20, 36);
    iconjavi.iconAnchor = new GPoint(10, 36);
    iconjavi.infoWindowAnchor = new GPoint(10, 18);

    //////// Function ///////////////////////////////////////////////
    // Creates the HTML
    function createHTML(position) {
      //GLog.write("  ==> createHTML...");
      var city = markersitios[position];
      var pais   = markercountries[position];
      var ciudad = city.getAttribute("ciudad");
      var thumb  = city.getAttribute("thumb");
      var fotos  = city.getAttribute("fotos");
      var blog   = city.getAttribute("blog");
      var con    = city.getAttribute("con");
      //GLog.write("  - pais = " + pais + ", ciudad = " + ciudad);
      //GLog.write("  - thumb = " + thumb + ", fotos = " + fotos);
      //GLog.write("  - blog = " + blog);                
      //Div and table
      var htmltext = '<div><table border="0" cellpadding="5"><tr valign="top">';
      
      //Adding image
      if (thumb) {
        htmltext += '<td width="90px" height="120px">';
        //Link to pictures if existing
        if (fotos)
          htmltext += '<a href="' + fotos + '">';
        htmltext += '<img width="90px" align="left" style="border-width: 1px"';
        htmltext += 'src="' + thumb + '"/>';
        //End link tag
        if (fotos)
          htmltext += '</a>';
        htmltext+='</td><td align="left">';
      }
      else
        htmltext+='<td colspan="2"  align="left">';
      //Step position
      htmltext += ' <span class="title">' + position + '.- ';
      //City and country
      htmltext += ciudad;
      htmltext += ' (' + pais + ')</span>';

      //Accompaning, pictures and blogger
      if (con && con != "nadie") {
        htmltext += '<br/><img title="I met these people..." src="'+inputpath+'/gente.png" style="vertical-align:text-bottom; margin-top:8px; margin-right:4px" width="16px"/>'+ con;
      }
      if (fotos) 
        htmltext += '<br/><img title="Pictures..." src="'+inputpath+'/fotos.png" style="vertical-align:text-bottom; margin-top:8px; margin-right:4px" width="16px"/><a href="' + fotos + '">Pictures/Fotos</a>';
      if (blog)
        htmltext += '<br/><img title="Blog..." src="'+inputpath+'/bloggerlogo.gif" style="vertical-align:text-bottom; margin-top:8px; margin-right:4px" width="16px"/><a href="' + blog + '">Blog</a>';
        
      //Close row
      htmltext += '</td></tr><tr><td colspan="2">';
		
		  //Next and Previous
      htmltext += '<div style="float:left">';
		  if (position > 1) {
		    var prevcity = markersitios[position-1].getAttribute("ciudad");
		    prevcity = replaceByNBSP(prevcity);
		    htmltext += '&larr;&nbsp;<a href="javascript:myclick(' + (position - 1) + ')">' + prevcity + '</a>&nbsp;';
      }
      htmltext += '</div><div style="float:right">';
		  if (position < markersitios.length - 1) {
		    var nextcity = markersitios[position+1].getAttribute("ciudad");
		    nextcity = replaceByNBSP(nextcity);
		    htmltext += '&nbsp;<a href="javascript:myclick(' + (position + 1) + ')">' + nextcity + '</a>&nbsp;&rarr;';
      }
		  htmltext+= '</div>';
      //Close table and div
      htmltext += '</td></tr></table></div>';

      //GLog.write("  <== createHTML...");
      return htmltext;
    }
    //
    //////////////////////////////////////////////////////////////////

    //////// Function ///////////////////////////////////////////////
    // Creates a sitio at the given point with the given number label
    function createMarker(point, position, city) {
      //GLog.write("  ==> createMarker...");
      //var sitio = new GMarker(point, iconjavi);
      var sitio = new GMarker(point, {icon:iconjavi, title:city.getAttribute("ciudad")});
      gmarkers[position] = sitio;
      //GLog.write("  <== createMarker...");
      return sitio;
    }
    //
    //////////////////////////////////////////////////////////////////

    //////// Function ///////////////////////////////////////////////
    // Creates a sitio at the given point with the given number label
    function addListenerToMarker(position) {
      //GLog.write("  ==> addListenerToMarker...");
      var html = createHTML(position);
      GEvent.addListener(gmarkers[position], "click", function() {
        //Draw the window
        //GLog.write("  ==> Inside listener...");
        gmarkers[position].openInfoWindowHtml(html);
        //GLog.write("  <== Outside listener...");
      });
      htmls[position] = html;
      //GLog.write("  <== addListenerToMarker...");
      return html;
    }
    //
    //////////////////////////////////////////////////////////////////

    //////// Function ///////////////////////////////////////////////
    // Creates the path (polyline) based on mean of transport
    function createPath(points, transport) {
      var color = "#007700"; //green (bus y tren)
      if (transport == "avion")
        color = "#ff0000"; //red (avion)
      else if (transport == "barco" || transport=="ferry")
        color = "#0000aa"; //blue (barco)
      map.addOverlay(new GPolyline(points, color));
    }
    //
    /////////////////////////////////////////////////////////////////

    GDownloadUrl(inputpath + '/' + ciudadesxml, function(data) {
      //GLog.write("==> Inside download url function");
      var xml = GXml.parse(data);
      var continentes = xml.documentElement.getElementsByTagName("continente");
      var points = [];
      var oldtransport = "none";
      var position = 1;
      for (var i = 0; i < continentes.length; i++) {
        var contname = continentes[i].getAttribute("name");
        //GLog.write("   Got continent " + contname);

        var paises = continentes[i].getElementsByTagName("pais");
        for (var c = 0; c < paises.length; c++) {
          var paisname = paises[c].getAttribute("name");
          //GLog.write("   * Country: " + paisname);
          
          var sitios = paises[c].getElementsByTagName("sitio");
          for (var s = 0; s < sitios.length; s++) {
            var ciudad = sitios[s].getAttribute("ciudad");
            //GLog.write("     - Place: " + ciudad);
            //Get the place position
            var point = new GLatLng(parseFloat(sitios[s].getAttribute("lat")),parseFloat(sitios[s].getAttribute("lng")));

            //Find out if we have to place a marker and place it if needed
            var drawmarker = sitios[s].getAttribute("drawmarker");
            //GLog.write("xml sitio = " + drawmarker);
            if ( drawmarker != "false") {
              markersitios[position] = sitios[s];
              markercountries[position] = paisname;
              map.addOverlay(createMarker(point, position, sitios[s]));
              position++;
            }
            //The path
            var transport = sitios[s].getAttribute("transporte");
            if (transport == oldtransport) {
              //GLog.write("Continue... adding point!");
              points.push(point);
            }
            else {
              //GLog.write("New place!");
              createPath(points, oldtransport);
              var startingpoint=points[points.length-1];
              points = [];
              points.push(startingpoint);
              points.push(point);  
            }
            oldtransport = transport;


          } //for var s
        } //for var c
       } //for var i
       //Last path
       createPath(points, oldtransport);
       
       //Add listeners to markers
       for (var i = 1; i < position; i++) {
         addListenerToMarker(i);
       }

      //myclick(position-1);
      myclick(1);
       //GLog.write("<== Outside download url function");
    });
  }
  //GLog.write('<< End loading...');
}

//]]>
