/*! 
 * emaps.js
 */
var eMap = function(options){
	/*
	 * PRIVATE 	
	 */ 
	var map = null;
	var content = '';
	var defaultsMap = {
		info:'',
		id:"map",
		lat:40.00,
		lng:-4.0,
		zoom:5,
		varname:"emapa",
		/*mapType:G_NORMAL_MAP,*/
		searcheable:false,
		latSearchFieldId:"latitudDondeCrear",
		longSearchFieldId:"longitudDondeCrear",
		zoomSearchFieldId:"zoomDondeCrear",
		api_key:"ABDCEF",
		checkResizeAfterLoad:false,
		mapAPILoaded:false,
		mapDraggable:false,
		mapMoveEndFunction:null, 
		markHTMLType:1,
		afterLoadFuncion:null
	};
	
	var optionsEMap = $.extend(defaultsMap,options);
	
	var eventIco = null;
	var dragMarker = null;
	
	/* carga del mapa   */
	function load() {
		if (GBrowserIsCompatible()) {
			eventIco = new GIcon(G_DEFAULT_ICON);
			 var arrowIco = new GIcon(G_DEFAULT_ICON);
			arrowIco.image = "http://www.google.com/mapfiles/arrow.png";
	
			if(optionsEMap.info!='') content = eval('('+optionsEMap.info+')');
	    	map = new GMap2(document.getElementById(optionsEMap.id));
	    	//map.setMapType(optionsEMap.mapType); 
	    	map.setMapType(G_NORMAL_MAP);
	    	//map.addControl(new GSmallMapControl());
			//map.addControl(new GHierarchicalMapTypeControl());
			
	    	
	    	/* si hay contenido	*/
	    	if(content!='' && content.eventos.length>0) {
	    		// set caption
				var newCaption = "";
				if(content.que!="" && content.donde!="") newCaption = getText("emap.caption.events.both",{param1:content.que,param2:content.donde},"");
				else if(content.que!="") newCaption = getText("emap.caption.events.que",{param1:content.que},"");
				else if(content.donde!="") newCaption = getText("emap.caption.events.donde",{param1:content.donde},"");
				else  newCaption = getText("emap.caption.eventsAroudYou","","");
				var newRestoCaption = content.eventos.length+" "+getText("emap.caption.events","","");
				changeCaption(newCaption,newRestoCaption);
				
				// set center
	    		map.setCenter(new GLatLng(content.latitud,content.longitud), content.zoom);
	    		 
	    		// crea marcas 
	    		createMarkers(optionsEMap.markHTMLType); 
	    	} 
	    	
	    	/* si no hay contenido, mostrar un arrow */
	    	else {
	    		var point = new GLatLng(optionsEMap.lat,optionsEMap.lng);
	    		map.setCenter(point, optionsEMap.zoom);
	    		if(defaultsMap.searcheable){ createDragMarker(point); }
	    	}
	    	
	    	if(optionsEMap.mapDraggable && optionsEMap.mapMoveEndFunction!=null){
		    	GEvent.addListener(map, "moveend", optionsEMap.mapMoveEndFunction);
	    	}
	    	
	    	GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
	          	$("#zoomDondeCrear").val(newLevel);
	         });


			if(optionsEMap.checkResizeAfterLoad){
				map.checkResize();
			}
			
			
			// call afterload function
			optionsEMap.afterLoadFuncion();
	  	}
	}
		   

	/*
	 * 
	 */
	function createMarkers(type){	
		$.each(content.eventos,function(i,ev){
			var point = new GLatLng(ev.latitud, ev.longitud);
			var marker = new GMarker(point,{icon:eventIco });
			
			// construyo el html
			var temContent = "";
			$.each(ev.tematics,function(j,tematica){
				temContent += 	"<li><a href=\""+fixPath+"search\/"+tematica.purl+"\/"+ev.wherePurl+"\">"+tematica.label+"</a></li>";
			});
	
	
			var htmlGlobo = "";
			// listado			
			if(type==1){
				htmlGlobo = "<div class=\"eMapBox\"><h2><a href=\""+fixPath+"events\/"+ev.eventPurl+"\">"+ev.title+"</a></h2><p class=\"fecha\">Fecha: <span class=\"fechaGlobo\">"+ev.startDate+"</span></p><p class=\"tem\">Tem&aacute;ticas:</p><ul>"+temContent+"</ul></div>"
			}
			// ficha
			else {
				htmlGlobo = "<div class=\"eMapBox\"><h2><a href=\""+fixPath+"events\/"+ev.eventPurl+"\">"+ev.title+"</a></h2><p class=\"fecha\">Fecha: <span class=\"fechaGlobo\">"+ev.startDate+"</span></p><p class=\"tem\">Tem&aacute;ticas:</p><ul>"+temContent+"</ul></div>"
			}
			
			
			GEvent.addListener(marker, "click", function() {
	 			marker.openInfoWindowHtml(htmlGlobo);
	  		});
	  		
	  		//bindear el objeto del listado a su referenciaen el mapa
	  		$("#seeOnMap"+ev.idEvento).click(function(){
	  			map.setCenter(new GLatLng(ev.latitud, ev.longitud), ev.zoom);
	  			marker.openInfoWindowHtml(htmlGlobo);
	  		});
	  		
	  		map.addOverlay(marker);
		});	
	}
     
     function createDragMarker(point){
     	dragMarker = new GMarker(point, {draggable: true});
     	
		GEvent.addListener(dragMarker, "dragstart", function() {
		  map.closeInfoWindow();
		 });
		  
		GEvent.addListener(dragMarker, "dragend", function() {
		 	var p = dragMarker.getLatLng();
			map.panTo(p);
			fillFields(p);
			//console.log(p);
			//if(map.getZoom()<14) dragMarker.openInfoWindow("Seguro que todav\xEDa puedes afinar un poco m\xE1s.");
			map.setCenter(p,map.getZoom());
		  });
		
		//init fields
		fillFields(point);
		map.addOverlay(dragMarker);
		dragMarker.openInfoWindow("Arr\xE1strame hasta la posici\xF3n m\xE1s exacta.");
     }
	
	function fillFields(p){
		$("#"+optionsEMap.latSearchFieldId).val(p.y);
		$("#"+optionsEMap.longSearchFieldId).val(p.x);
		$("#"+optionsEMap.zoomSearchFieldId).val(map.getZoom());
	}
	
	/**
	 * Tama�o disponible 
	 *	para name: 28
	 * 	para resto: 28-name.length
	 * Esta funci�n setea el tooltip del caption
	 */
	function changeCaption(name,rest){
		rest = (rest==undefined) ? "" : rest;
		var maxBigChars = 28;
		var len = name.length;
		var resto = "";
		var full = name+' - '+rest;
		
		if(len>=maxBigChars){
			name = name.substring(0, maxBigChars);
			name = name.concat("...");
		}
		name = "<span class=\"titular\" style=\"float:left;\">"+name+"</span>";
		
		if(rest!=""){
		    resto += "<span style=\"font-size:10px;float:right; padding-top:5px;\">";
		    restTam = Math.ceil(maxBigChars-len+(maxBigChars-len)*0.20);
		    if(rest.length > restTam){
		    	resto += rest.substring(0,restTam);
		    	resto += "...";
		    } 
		    else {
		    	resto += rest;
		    }
		    resto += "</span>";
		}
		$("#captionEmap").html(name+resto);
		$("#captionEmapFull").text(full);
	}
	
	
	function apiLoader(targetId) {
	   if(optionsEMap.mapAPILoaded) {
		  //console.log("api no cargada");
		  load();
	   } 
	   else {
		   var script = document.createElement("script");
		   script.src = "http://maps.google.com/maps?file=api&v=2&async=2&key="+optionsEMap.api_key+"&callback="+optionsEMap.varname+".load";
		   script.type = "text/javascript";
		   if(targetId==undefined || targetId==null ){
		   	  document.body.appendChild(script);
		  	  //console.log("api cargada");
		  	  optionsEMap.mapAPILoaded = true;
		  }
		  else{
		  	$("#"+targetId).append($(script)); 
		  }
	  }
	}
	
	
	
	
	
	/**
	 * devolvemos este objeto a la creaci�n 
	 */
	return {
		constructor: function(){
			apiLoader();
		},
		setCenter: function(lat,lng,zoom){
	    	window.setTimeout(function() { 
	    		var point = new GLatLng(lat, lng);
	    		map.setCenter(point,parseInt(zoom));
	    	}, 100);
		},
		getMap:function(){
			return map;
		},
		addOverlay:function(marker){
			map.addOverlay(marker);
		},
		changeCaption: function(name,rest){
			changeCaption(name,rest);
		},
		checkResize: function(){
			map.checkResize();
		},
		load:function(){
			load();
		}
	};
};
