
 window.onload = cm_load;

var region = "default";
var side_bar_html= false;
var cm_map;
var cm_mapMarkers = [];
var cm_mapHTMLS = [];
	var gmarkers = [];
	var htmls = [];
	var ii = 0;
// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var cm_baseIcon = new GIcon();
cm_baseIcon.shadow = "googlemaps/guiasdeviaje/images/sombra_icono.png";
cm_baseIcon.iconSize = new GSize(30, 30);
cm_baseIcon.shadowSize = new GSize(39, 30);
cm_baseIcon.iconAnchor = new GPoint(21, 30);
cm_baseIcon.infoWindowAnchor = new GPoint(9, 2);
cm_baseIcon.infoShadowAnchor = new GPoint(18, 25);

// Change these parameters to customize map
var param_wsId = "";
var param_ssKey = "";
var param_useSidebar =true;
var param_useDescription = "";
var param_useRegion = "";
var param_imageColumn = "";
var param_titleColumn = "";
var param_descriptionColumn = "";
var param_latColumn = "";
var param_lngColumn = "";
var param_rankColumn = "";
var param_mapWidth;
var param_mapHeight;
var param_iconType = "";
var param_iconOverType = "";
var param_userGuia = "";
var param_userMedia ="";


 
 function cambiarregion(){

		/*side_bar_html="";*/
	
region = document.getElementById("region").value;
	 bubble.hide();
	 cm_load();
	 
	 }
 
 
function populateVars() {
 param_useSidebar= true;
	gmarkers = [];
	htmls = [];
	ii = 0;

/*	document.getElementById("datos").innerHTML = side_bar_html;*/

  param_wsId = "od5";
  param_ssKey= "pTSChRC1GdxzzIba0EmEVUQ";
/*param_useSidebar = document.getElementById("useSidebar").checked;*/

  param_titleColumn = "titulo";
  param_descriptionColumn = "descripcion";
  param_latColumn = "latitude";
  param_lngColumn = "longitude";
  param_rankColumn  = "rank";
  param_iconType = "green";
  param_iconOverType = "pink";
  param_useRegion ="region";
  param_userGuia = "link";
  param_userMedia = "media";


	param_mapWidth = 320;
  	param_mapHeight = 320;

	

  document.getElementById("cm_map").style.width = param_mapWidth + "px";
  document.getElementById("cm_map").style.height = param_mapHeight + "px";
}

/**
 * Loads map and calls function to load in worksheet data.
 */
function cm_load() {
	
	

  populateVars(region);
  if (GBrowserIsCompatible()) {
    // create the map
    cm_map = new GMap2(document.getElementById("cm_map"));
    cm_map.addControl(new GSmallMapControl());
    cm_map.addControl(new GMapTypeControl());
    cm_map.setCenter(new GLatLng(0,0), 0);
      bubble = new EBubble(cm_map, pp1+"googlemaps/guiasdeviaje/images/bubble2.png",new GSize(216,195), new GSize(175,155), new GPoint(14,4), new GPoint(135,193));      

	cm_getJSON();
	
  } else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  } 
}

function cm_markerClicked(markerNum) {
  //alert(markerNum)
  var marker = cm_mapMarkers[markerNum];
  
  marker.openInfoWindowHtml(cm_mapHTMLS[markerNum]);
 alert(cm_mapHTMLS[markerNum])
}

/// abrir la burbuja desde el sidebar///
function myclick(i) {
        //gmarkers[i].openInfoWindowHtml(htmls[i]);
          bubble.openOnMarker(gmarkers[i],htmls[i]);
	  }

       
function cm_loadMapJSON(json) {



  var bounds = new GLatLngBounds();	  
  var myVar = region;
//alert(myVar)

 if(json.feed.entry[0] && json.feed.entry[0]["gsx$" + param_rankColumn]) {
    usingRank = true;
    /*json.feed.entry.sort(cm_sortRows);*/
  }

  for (var i = 0; i < json.feed.entry.length; i++) {
    
	if (json.feed.entry[i]["gsx$" + param_useRegion].$t == myVar | myVar == "default"){
	
	var entry = json.feed.entry[i];

    if(entry["gsx$" + param_latColumn]) {
      var lat = parseFloat(entry["gsx$" + param_latColumn].$t);
      var lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
      var point = new GLatLng(lat,lng);
     var html = "<div class='cm_infoWindow2'>";
 
   html += "<div id='cm_infoWindowTitle'>" +
          entry["gsx$"+param_titleColumn].$t + "</div>";
/*  		 html += "<div id='cerrarventana'>"+'<a id="cerrar" href="javascript:bubble.hide()">'+"</a></div>"; 
		 html += "<div id='apDiv1'>" + '<img src="'+ pp1+ entry["gsx$"+param_userMedia].$t +'" />' + "</div>";
		html += "<div id='cm_icono'>" + '<a ><img src="'+pp1+'googlemaps/guiasdeviaje/images/'+ entry["gsx$"+param_useRegion].$t + 'b.png" /></a>' + "</div>";
		html += "<div id='buttons'>"+'<a id="download" title="guia de viaje"href="'+ pp1 + entry["gsx$"+param_userGuia].$t +'"/>'+"</a></div>";*/
		  var ellink= entry["gsx$"+param_userGuia].$t;
		
		  var eltipo = entry["gsx$"+param_useRegion].$t;
/*	      		html += "<div id='cm_icono'>" + '<a ><img src="'+ pp1 + 'googlemaps/guiasdeviaje/images/' + eltipo + 'b.png" /></a>' + "</div>";*/

      var label = entry["gsx$"+param_titleColumn].$t;
      var rank = "";

     if( usingRank && entry["gsx$" + param_rankColumn]) {
        rank = parseInt(entry["gsx$" + param_rankColumn].$t);
      }

      if( entry["gsx$" + param_descriptionColumn]) {
        html += "<div id='tabla_descripcion'>" +  entry["gsx$"+param_descriptionColumn].$t + "</div>";
      }

      html += "</div>";

      // create the marker
      var marker = cm_createMarker(point,label,html,rank, eltipo, ellink);
      
	  cm_map.addOverlay(marker);
      cm_mapMarkers.push(marker);
      
	  cm_mapHTMLS.push(html);
      bounds.extend(point);
	  
 
    }
  }
}
  cm_map.setZoom(cm_map.getBoundsZoomLevel(bounds));
  cm_map.setCenter(bounds.getCenter());
}


function cm_createMarker(point, title, html, rank, eltipo, ellink ) {
 
  var markerOpts = {};

  var nIcon = new GIcon(cm_baseIcon);

  if(rank > 0 && rank < 100){
    nIcon.imageOut = pp1 + "googlemaps/guiasdeviaje/images/" + eltipo + "i.png";
    nIcon.imageOver = pp1 + "googlemaps/guiasdeviaje/images/" + eltipo + "ii.png";
    nIcon.image = nIcon.imageOut; 
  } else { 
    nIcon.imageOut = "http://gmaps-samples.googlecode.com/svn/trunk/" +
        "markers/" + param_iconType + "/blank.png";
    nIcon.imageOver = "http://gmaps-samples.googlecode.com/svn/trunk/" +
        "markers/" + param_iconOverType + "/blank.png";
    nIcon.image = nIcon.imageOut;
  }

  markerOpts.icon = nIcon;
  markerOpts.title = title;
  var marker = new GMarker(point, markerOpts);

  GEvent.addListener(marker, "mouseover",function() {
    bubble.openOnMarker(marker,html);

  });
  

  
  GEvent.addListener(marker, "mouseover", function() {
    marker.setImage(marker.getIcon().imageOver);
    });
  GEvent.addListener(marker, "mouseout", function() {
    marker.setImage(marker.getIcon().imageOut);
  });
  GEvent.addListener(marker, "infowindowopen", function() {
    marker.setImage(marker.getIcon().imageOver);
  });
  GEvent.addListener(marker, "infowindowclose", function() {
    marker.setImage(marker.getIcon().imageOut);

  });
    GEvent.addListener(marker, "click", function() {
 /* alert("i")*/

 location.href = pp1 + ellink;

/*alert(pp1 + ellink)*/

  });
     GEvent.addListener(marker, "mouseout", function() {

bubble.hide();
  });  
 GEvent.addListener(cm_map, "click", function(marker,point) {
      	if (point) {
			
          
		 bubble.hide();
		 
        }
      });
 
 
  return marker;
}


function cm_getJSON() {

  // Retrieve the JSON feed.
  var script = document.createElement('script');

  script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list'
                         + '/' + param_ssKey + '/' + param_wsId + '/public/values' +
                        '?alt=json-in-script&callback=cm_loadMapJSON');
  script.setAttribute('id', 'jsonScript');
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}

////////////////////////////////expperimento//////////////////////////////////////

      function EBubble(map,image,size,insize,inset,anchor,noCloseOnClick) {
        // parameters
        var that=this;
        this.map = map;
        this.image=image;
        this.size=size;
        this.insize=insize;
        this.inset=inset;
        this.anchor=anchor;
        this.noCloseOnClick=noCloseOnClick;
        // internal variables
        this.visible = false;
        // browser - specific variables
        this.ie = false;
        var agent = navigator.userAgent.toLowerCase();
        if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}

        this.div1 = document.createElement("div");
        this.div1.style.position = "absolute";
		this.div1.style.zIndex="11";
        this.div1.style.display="none";
        document.body.appendChild(this.div1);


        if (this.ie && this.image.indexOf(".png")>-1) {
          var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.image+"', sizingMethod='scale');";
          this.div1.innerHTML = '<div style="height:' +this.size.height+ 'px; width:'+this.size.width+'px; ' +loader+ '" ></div>';
        } else {
          this.div1.innerHTML = '<img src="' + this.image + '" width="' + this.size.width +'" height="' + this.size.height +'">';
        }
        // === Close the bubble if the map moves ===
        GEvent.addListener(map, "dragstart", function() {
          that.hide();
        } );
        GEvent.addListener(map, "moveend", function() {
          that.hide();
        } );
        // === Listen for clicks and mousedowns ===
/*        GEvent.addDomListener(this.div1,"click", function() {
          if (!that.noCloseOnClick) that.hide();
          GEvent.trigger(that,"click");
        });
        GEvent.addDomListener(this.div1,"mousedown", function() {
          if (!that.noCloseOnClick) that.hide();
          GEvent.trigger(that,"click");
        });*/

        this.div2 = document.createElement("div");
        this.div1.appendChild(this.div2);
        this.div2.style.position = "absolute";
        this.div2.style.left = this.inset.x + "px"; 
        this.div2.style.top = this.inset.y + "px";
        this.div2.style.width = this.insize.width + "px";
        this.div2.style.height = this.insize.height + "px";

      } 
      

      EBubble.prototype.openOnMap = function(point, html, offset) {
        this.offset = offset||new GPoint(0,0);
        this.point = point;


        //div2.style.backgroundColor = "#0000ff"; 
        this.div2.innerHTML = html;

        // pixel relative to map world
        var p = this.map.fromLatLngToDivPixel(point);

        // map world relative to map container
        var dragObject = this.map.getPane(G_MAP_MAP_PANE).parentNode;
        var x = p.x + parseInt(dragObject.style.left);
        var y = p.y + parseInt(dragObject.style.top);

        // map container relative to the page
        y += this.map.getContainer().offsetTop;
        x += this.map.getContainer().offsetLeft;
        
        // offset by the requested anchor position
        y -= this.anchor.y;
        x -= this.anchor.x;

        // offset by the specified offset position
        y -= this.offset.y;
        x -= this.offset.x;


        // Apply those values 
        this.div1.style.left = x+"px";
        this.div1.style.top = y+"px";
        
        // make it visible
        this.visible = true;
        this.show();
      }
      
      EBubble.prototype.openOnMarker = function(marker,html) {
        var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
        var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
        this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
      }
      

      EBubble.prototype.show = function() {
        this.div1.style.display="";
        this.div2.style.display="";
        this.visible = true;
      }
      
      EBubble.prototype.hide = function() {
        this.div1.style.display="none";
        //this.div2.style.display="none";
        this.visible = false;
      }
      
      EBubble.prototype.isHidden = function() {
        return !this.visible;
      }
      
      EBubble.prototype.supportsHide = function() {
        return true;
      }
