	//$(window).load(function(){
		//initializeDynamicMap();
	//});
	$(window).unload(GUnload);
	$(document).ready(function() {
		initializeDynamicMap();
		$("#leftNav").corner("10px");
		//$("#searchForm").attr("action","javascript:showAddress();");
		
	});





var map;
var markerArray=new Array();
// Create our "tiny" marker icon

var restaurantIcon=base_url+"img/icon_restaurant.png";
var pubIcon = base_url+"img/icon_pub.png";
var discotequeIcon = base_url+"img/icon_discoteque.png";
var sportsIcon = base_url+"img/icon_sports.png";
var culturalIcon = base_url+"img/icon_cultural.png";
var tripIcon = base_url+"img/icon_trip.png";

var icon = new GIcon();
icon.iconSize = new GSize(32, 32);
icon.shadow=base_url+"img/icon_shadow.png";
icon.shadowSize=new GSize(49,32);
icon.iconAnchor = new GPoint(14, 31);
//icon.infoWindowAnchor = new GPoint(14, 0);

function Marker(gMarker,infoWindow){
	this.gMarker=gMarker;
	this.infoWindow=infoWindow;
}

function initializeDynamicMap(){
	if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new TextualZoomControl());
		map.enableScrollWheelZoom();
        GEvent.addListener(map, "moveend", dragListener);
		showAddress();
      }
}

function dragListener(){
	//Escribimos la cookie de la pos actual
	$.cookie("lat", map.getCenter().lat(), { path: '/', expires: 0 });
	$.cookie("lng", map.getCenter().lng(), { path: '/', expires: 0 });
	$.cookie("zoom", map.getZoom(), { path: '/', expires: 0 });
	
	var bounds = map.getBounds();
  	var southWest = bounds.getSouthWest();
  	var northEast = bounds.getNorthEast();
  	var postRequest="swlat="+southWest.lat()+"&swlong="+southWest.lng()+"&nelat="+northEast.lat()+"&nelong="+northEast.lng();
  	var postRequest=postRequest+"&sort="+$("#sortSelect").val();
  	if ($("#checkRestaurants").attr("checked")==true) postRequest=postRequest+"&place_types[]=Restaurant";
  	if ($("#checkPubs").attr("checked")==true) postRequest=postRequest+"&place_types[]=Pub";
  	if ($("#checkDiscoteques").attr("checked")==true) postRequest=postRequest+"&place_types[]=Discoteque";
  	if ($("#checkSports").attr("checked")==true) postRequest=postRequest+"&place_types[]=Deportes";
  	if ($("#checkCultural").attr("checked")==true) postRequest=postRequest+"&place_types[]=Cultural";
  	if ($("#checkTrips").attr("checked")==true) postRequest=postRequest+"&place_types[]=Paseo";
  	$.ajax({
        type: "POST",
        url: site_url+"/places/ajax_get_places_by_location",
        data: postRequest,
		dataType: "json",
        success: function(response){
					//alert(response[0].name);
					//$.each(response.items, function(i,item){
					//	alert(item.name);
					//});
			
        			//Borro los marcadores antiguos
        			for(var i=0; i<markerArray.length;i++)
        				map.removeOverlay(markerArray[i].gMarker);
        			markerArray=new Array();
        			
       				//Borro lo que hay en el listado de lugares
					//$("#restaurantList").fadeOut();
       				$("#restaurantList").empty();
       				
       				//var nodes=$("unknownNode", response);
       				for (var i=0; i<response.length; i++){
       					var infoWindow="<b>"+response[i].name+"</b><br />"+response[i].address+"<br /><a href='"+site_url+"/places/detail/"+response[i].id+"'>Ver detalles</a>";
						if(response[i].type=="Restaurant") icon.image=restaurantIcon;
						if(response[i].type=="Pub") icon.image=pubIcon;
						if(response[i].type=="Discoteque") icon.image=discotequeIcon;
						if(response[i].type=="Deportes") icon.image=sportsIcon;
						if(response[i].type=="Cultural") icon.image=culturalIcon;
						if(response[i].type=="Paseo") icon.image=tripIcon;
						var markerPos=addMarker(response[i].latitude, response[i].longitude, infoWindow,icon);
						
						$("#restaurantList").append("<div style='margin-top:10px;'>");
       					$("#restaurantList").append("<a style='color:#393733;' href='"+site_url+"/places/detail/"+response[i].id+"'><img class='pngfix' style='float: left; margin-right: 5px;' src='"+icon.image+"' /><h2 style='display: inline;'>"+response[i].name+"</a></h2>");
       					$("#restaurantList").append("<p>");
						if (response[i].evaluations_avg!=null)
       						$("#restaurantList").append("Evaluacion: "+1*response[i].evaluations_avg+"/5<br />");
       					$("#restaurantList").append("Precio por persona: De "+response[i].price_min+" a "+response[i].price_max+" pesos<br />");
						if (response[i].address!="")
       						$("#restaurantList").append("Direccion: "+response[i].address+"<br />");
       					$("#restaurantList").append("Agregado el: "+response[i].created+"<br />");
       					$("#restaurantList").append("<a href='javascript:showMarker("+markerPos+")'>Mostrar en mapa</a> | ");
       					$("#restaurantList").append("<a href='"+site_url+"/places/detail/"+response[i].id+"'>Ver detalles</a>");
       					$("#restaurantList").append("</p>");
						$("#restaurantList").append("</div>");
       				}
					//$("#restaurantList").fadeIn();
      			}
		});
	}

function renderMap(latitude, longitude, zoom) {
	  if (zoom==null) var zoom=13;
	  
      if (GBrowserIsCompatible()) {
      	map.clearOverlays();
      	if (map.isLoaded())
        	map.panTo(new GLatLng(latitude, longitude));
        else
        	map.setCenter(new GLatLng(latitude, longitude), zoom);
      }
    }
    
function addMarker(latitude, longitude, infoWindow, placeIcon) {
      	var markerPos=markerArray.length;
        var point = new GLatLng(latitude, longitude);
        markerArray[markerPos]= new Marker(new GMarker(point,{ icon:placeIcon }),infoWindow);

        //markerArray[markerPos].gMarker.bindInfoWindow(infoWindow);
        GEvent.addListener(markerArray[markerPos].gMarker, "click", function() {
    		showMarker(markerPos);
  			});
        map.addOverlay(markerArray[markerPos].gMarker);
        return markerPos;
    }
    
function showMarker(markerPos){
	map.openInfoWindow(markerArray[markerPos].gMarker.getLatLng(),markerArray[markerPos].infoWindow,{pixelOffset: new GSize(0,-31)});
	//markerArray[markerPos].gMarker.openInfoWindow(markerArray[markerPos].infoWindow);
}
    
function showAddress() {
	var query = $("#searchText").val();
	
	if((query=="¿Que Comuna o Lugar?" || query=="") && $.cookie("lat") && $.cookie("lng") && $.cookie("zoom")){
		renderMap(1*$.cookie("lat"), 1*$.cookie("lng"), 1*$.cookie("zoom"));
		return;
	}
	else if(query=="¿Que Comuna o Lugar?" || query=="")
		query="Santiago";
		
	var country="chile";
	var location=query+", "+country;
	var geocoder = new GClientGeocoder();
  	geocoder.getLatLng(location,
    					function(point) {
							if (point) {
								renderMap(point.lat(),point.lng());
							}
						}
					);
}













// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).

// We define the function first
function TextualZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  container.style.borderLeft = "1px solid black";
  container.style.borderBottom = "1px solid black";
  container.style.backgroundColor="#4093EE"
  container.style.color="white"
  container.style.padding = "4px";

  $(container).html("<input id='checkRestaurants' class='typeCheck' type='checkbox' /> Restaurantes <input id='checkPubs' class='typeCheck' type='checkbox' /> Pubs <input id='checkDiscoteques' class='typeCheck' type='checkbox' /> Discoteques <input id='checkSports' class='typeCheck' type='checkbox' /> Deportes <input id='checkCultural' class='typeCheck' type='checkbox' /> Cultura <input id='checkTrips' class='typeCheck' type='checkbox' /> Paseos" );

  map.getContainer().appendChild(container);

  if ($("#place_type").val()=="" || $("#place_type").val()=="all")
	$(".typeCheck").attr("checked",true);
  else if ($("#place_type").val()=="restaurant")
  	$("#checkRestaurants").attr("checked",true);
  else if ($("#place_type").val()=="pub")
  	$("#checkPubs").attr("checked",true);
  else if ($("#place_type").val()=="discoteque")
  	$("#checkDiscoteques").attr("checked",true);
  else if ($("#place_type").val()=="sports")
  	$("#checkSports").attr("checked",true);
  else if ($("#place_type").val()=="cultural")
  	$("#checkCultural").attr("checked",true);
  else if ($("#place_type").val()=="trip")
  	$("#checkTrips").attr("checked",true);
  
  $(".typeCheck").click(dragListener);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 0 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 0));
}

