//Contructor
function Map(_id,_lat,_long,_zoom,opts) {
	if (GBrowserIsCompatible()) {
		
		this.id=_id
		this.center=new GLatLng(_lat,_long)
		this.zoom=_zoom
		this.pan=200
		this.opts=null
		this.btns=new Array()
		
		this.map = null;
		this.route = null; //Variable de los recorridos
		this.lastRoute = new Array();//Último Recorrido
		this.markers =new Array(); //TODOS LOS MARKES SOBRE LOS QUE QUEREMOS TENER UN CONTROL
		this.icons=new Array()//Iconos
		
		this.map = new GMap2(document.getElementById(this.id));
		this.map.setCenter(this.center, this.zoom);
		
		//this.map.disableDoubleClickZoom()
		this.map.classObject=this
		this.type=null
		this.types=new Array();
		
		//Aplicamos las opciones
		if(typeof opts!="undefined"){
			if(typeof opts.controls_skin=="undefined"){
				//this.map.addControl(new GLargeMapControl());
				this.map.addControl(new GSmallMapControl());
				this.map.addControl(new GMapTypeControl());
			}else this.setSkin(opts.controls_skin)
			
			if(typeof opts.info_window!="undefined"){
				
				var btn_cerrar=$("#"+opts.info_window+" .cerrar").get(0)
				btn_cerrar.classObject=this
				btn_cerrar.onclick=function(){
					this.classObject.closeWindow()	
				}
				
				GEvent.addListener(this.map, "dragstart", function (){this.classObject.closeWindow()});
			}
			
			this.opts=opts
		}
		this.refreshMargins()
		this.setZoom(this.zoom)
	}
} 



//Crea una categoria con su icono correspondiente
Map.prototype.setCategory=function (_name,_src,_anchorx,_anchory,opts){
	var icon = new GIcon();
		icon.image = _src;
		icon.iconAnchor = new GPoint(_anchorx, _anchory);
		icon.infoWindowAnchor = new GPoint(_anchorx, _anchorx);	
		
		
	
	this.markers[_name]=new Array();
	this.markers[_name].points=new Array();
	this.markers[_name].icon=icon;
	this.markers[_name].hidden=true
	
	
	//Aplicamos las opciones
	if(typeof opts!="undefined"){
		if(typeof opts.min_zoom!="undefined") this.markers[_name].min_zoom=opts.min_zoom
		if(typeof opts.max_zoom!="undefined") this.markers[_name].max_zoom=opts.max_zoom
				
	}
	//SETEAMOS EL BOTON DE LA CATEGORIA
	if(typeof this.opts.legend!="undefined") {
		if(typeof $("#"+this.opts.legend+" ."+_name).get(0)!="undefined"){
			var btn=$("#"+this.opts.legend+" ."+_name).get(0)
			btn.classObject=this
			btn.cat=_name
			btn.onclick=function(){
				this.classObject.toggleMarkers(this.cat)
				return false;
			}
			this.btns["legend_"+_name]=btn
		}
	}
}



//Añade un punto a una categoria (sin mostralo)
Map.prototype.addPoint=function (name,lat,long,opts){
	if(typeof opts=="undefined"){opts={}}
	var cat=this.markers[name];
	var point=new GLatLng(lat,long);
	var marker_opts={icon:cat.icon,hide:true}
	if(typeof opts.title!="undefined") marker_opts.title=opts.title
	if(typeof opts.text!="undefined") marker_opts.text=opts.text
	

	var marker = new GMarker(point,marker_opts);
	marker.map=this.map;
	marker.classObject=this;
	if(typeof opts.onclick!="undefined") marker.onclick=opts.onclick

	this.map.addOverlay(marker);
	
	this.markers[name].points.push(marker);
	
	//SETEMAOS LA VENTANA DE INFO
	if(typeof opts.text!="undefined"){
		if(typeof this.opts.info_window!="undefined"){
			var funccion=function(latlng){
				this.map.panTo(latlng);
				this.classObject.openWindow(marker,opts.text)
				
			}
		}else{
			var funccion=function() {
				marker.openInfoWindowHtml("<div'>"+unescape(opts.text)+"</div>");
			}
		}
	
	}else{
		var funccion=function(latlng){
			if(typeof this.onclick =="undefined")this.map.panTo(latlng);
			else this.onclick(this.classObject,this)
		}
	}

	GEvent.addListener(marker, "click", funccion);
}


Map.prototype.openWindow=function (marker,text){
	$("#"+this.opts.info_window).fadeIn()
	$("#"+this.opts.info_window+" .text").get(0).innerHTML=unescape(text);
}

Map.prototype.closeWindow=function (marker,text){
	$("#"+this.opts.info_window).fadeOut()
}

Map.prototype.zoomIn=function (){
	var zoom=this.map.getZoom()
	this.map.zoomIn()
	this.refreshMarkers(zoom)
	return this.map.getZoom();
}

Map.prototype.zoomOut=function (){
	var zoom=this.map.getZoom()
	this.map.zoomOut()
	this.refreshMarkers(zoom)
	return this.map.getZoom();
}


Map.prototype.setZoom=function (newzoom){
	var zoom=this.map.getZoom()
	this.map.setZoom(Number(newzoom))
	this.refreshMarkers(zoom)
	return this.map.getZoom();
}

//Controla que se vean los puntos o no segun el zoom
Map.prototype.refreshMarkers=function (lastzoom){
	var zoom=this.map.getZoom()
	/*for(var cat in this.markers){
		if(typeof this.markers[cat].min_zoom !="undefined"){
			if(zoom>=this.markers[cat].min_zoom) this.showMarkers(cat)
			if(zoom<this.markers[cat].min_zoom) this.hideMarkers(cat)
		}
		if(typeof this.markers[cat].max_zoom !="undefined"){
			if(zoom<=this.markers[cat].max_zoom) this.showMarkers(cat)
			if(zoom>this.markers[cat].max_zoom) this.hideMarkers(cat)
		}
	} 
	*/
	if(typeof this.opts.cursor_off!="undefined" && typeof this.btns["cursor"+lastzoom]!="undefined"){
		this.opts.cursor_off(this.btns["cursor"+lastzoom])
	}
	if(typeof this.opts.cursor_on!="undefined" && typeof this.btns["cursor"+zoom]!="undefined"){
		this.opts.cursor_on(this.btns["cursor"+zoom])

	}
	
}






//Muestra todos los puntos de una categoria
Map.prototype.toggleMarkers=function (cat){
	if(this.markers[cat].hidden==false) this.hideMarkers(cat)
	else this.showMarkers(cat)
		
}


//Muestra todos los puntos de una categoria
Map.prototype.showMarkers=function (cat){
	if(typeof this.markers[cat].points!="undefined"){
		for(i=0;i<this.markers[cat].points.length;i++){
			this.markers[cat].points[i].show()
		}
		this.markers[cat].hidden=false
		if(typeof this.opts.legend_on!="undefined" && typeof this.btns["legend_"+cat]!="undefined"){
			this.opts.legend_on(this.btns["legend_"+cat])
		}
	}
}

//Oculta todos los puntos de una categoria
Map.prototype.hideMarkers=function (cat){
	if(typeof this.markers[cat].points!="undefined"){
		for(i=0;i<this.markers[cat].points.length;i++){
			this.markers[cat].points[i].hide()
		} 
		this.markers[cat].hidden=true
		if(typeof this.opts.legend_off!="undefined" && typeof this.btns["legend_"+cat]!="undefined"){
			this.opts.legend_off(this.btns["legend_"+cat])
		}
	}
}

//Muestra todos los puntos de todas las categoria
Map.prototype.showAllMarkers=function (){
	for(var cat in this.markers){
		this.showMarkers(cat);
	} 
}

//Oculta todos los puntos de todas las categoria
Map.prototype.hideAllMarkers=function (){
	for(var cat in this.markers){
		this.hideMarkers(cat);
	} 
}

//Centra el mapa en el centro de la zona total de puntos
Map.prototype.centerByPointsZone=function (){
	var points = this.getAllPoints();
	var lat=0;
	var long=0;
	for(var i in points){
		lat+=points[i].lat()
		long+=points[i].lng()
	}
	lat=lat/points.length
	long=long/points.length
	this.center=new GLatLng(lat,long);
	this.map.setCenter(this.center);
	
	this.refreshMargins()
}

Map.prototype.refreshMargins=function (){
	if(typeof this.opts.marginRight!="undefined")this.map.panBy(new GSize(-this.opts.marginRight,0));
}

//Devuelve las coordenadas de todos los puntos del mapa
Map.prototype.getAllPoints=function (){
	var points = new Array();
	
	for(var cat in this.markers){
		if(typeof this.markers[cat].points!="undefined"){
			for(i=0;i<this.markers[cat].points.length;i++){
				points.push(this.markers[cat].points[i].getLatLng());
			}
		}	
	} 
	return points;
}


//CAMBIA EL TIPO DE MAPA
Map.prototype.setType=function(type){
	if(type=="normal")this.map.setMapType(G_NORMAL_MAP)
	else if(type=="hybrid")this.map.setMapType(G_HYBRID_MAP)
	else if(type=="satellite")this.map.setMapType(G_SATELLITE_MAP)
	else if(type=="physical")this.map.setMapType(G_PHYSICAL_MAP)
	
	if(typeof this.opts.type_on!= "undefined"){
		this.opts.type_on(this.btns[type])
	}
	if(typeof this.opts.type_off!= "undefined"){
		if(this.type!=null)this.opts.type_off(this.btns[this.type])
	}
	
	this.type=type;
}

//ACTUALIZA LOS BOTONES Y CAMBIA EL MAPA
Map.prototype.changeType=function(type){
	if(type!==this.type)this.setType(type)
}

//RUTAS
//Carga una ruta
Map.prototype.getRoute=function(from,to,result_div,error_func,callback_func,travelmode){
	
	
	if(typeof travelmode=="undefined") travelmode=""
	if(travelmode=="w") travel=G_TRAVEL_MODE_WALKING
	else travel=G_TRAVEL_MODE_DRIVING
	
	

	if(this.route==null){
		this.route = new GDirections(this.map, document.getElementById(result_div));
		
        //Función de error
		if(typeof error_func=="undefined") GEvent.addListener(this.route, "error", this.handleRouteErrors);
		else GEvent.addListener(this.route, "error", error_func);
	}
	
	

	
	//Función de respuesta
	if(typeof callback_func!="undefined"){
		GEvent.addListener(this.route, "load", callback_func);
	}
	this.route.load("from: " + from + " to: " + to,{ "locale": idioma,"travelMode":travel});
	this.lastRoute["from"]=from;
	this.lastRoute["to"]=to;
	this.lastRoute["travelmode"]=travelmode;
	
}

//Error de ruta
Map.prototype.handleRouteErrors=function (){
	alert("The route couldn't be find.");
}

//Imprime la última ruta cargada
Map.prototype.printLastLoadedRoute=function (){
	this.printRoute(this.lastRoute["from"],this.lastRoute["to"],this.lastRoute["travelmode"]);
}

//Imprime una ruta concreta
Map.prototype.printRoute=function (to,from,travelmode){
	if(typeof travelmode=="undefined") travelmode=""
   	NewWindowScrollResize('http://maps.google.com/maps?f=d&hl=es&geocode=&time=&date=&ttype=&saddr='+to+'&daddr='+from+'&om=1&pw=2&dirflg='+travelmode,"600","800");
 }	




//Configura los botones presentes en la capa id
Map.prototype.setSkin=function (id){
	
	
	//ZOOM-IN
	if(typeof $("#"+id+" .normal").get(0)!="undefined"){
		var btn=$("#"+id+" .normal").get(0)
		btn.classObject=this
		btn.onclick=function(){	this.classObject.map.changeType()}
		this.btns["normal"]=btn;
	}
	
	
	//ZOOM-IN
	if(typeof $("#"+id+" .zoom-in").get(0)!="undefined"){
		var btn=$("#"+id+" .zoom-in").get(0)
		btn.classObject=this
		btn.onclick=function(){	this.classObject.zoomIn()}
		this.btns["zoom-in"]=btn;
	}
	
	//ZOOM-OUT
	if(typeof $("#"+id+" .zoom-out").get(0)!="undefined"){
		var btn=$("#"+id+" .zoom-out").get(0)
		btn.classObject=this
		btn.onclick=function(){	this.classObject.zoomOut()}
		this.btns["zoom-out"]=btn;
	}
	
	
	//Cursores del zoom
	if(typeof $("#"+id+" .cursor").get(0)!="undefined"){
		
		var btns=$("#"+id+" .cursor").get()
		btns.reverse()
		for(var i in btns){
			var btn=btns[i]
			btn.zoom=i
			btn.classObject=this
			btn.onclick=function(){ 
				this.classObject.setZoom(this.zoom)
			}
			this.btns["cursor"+i]=btn;
		}
	}
	
	
	//PAN-LEFT
	if(typeof $("#"+id+" .left").get(0)!="undefined"){
		var btn=$("#"+id+" .left").get(0)
		btn.classObject=this
		btn.onclick=function(){ this.classObject.map.panBy(new GSize(this.classObject.pan,0))}
		this.btns["left"]=btn;
	}
	
	//PAN-RIGHT
	if(typeof $("#"+id+" .right").get(0)!="undefined"){
		var btn=$("#"+id+" .right").get(0)
		btn.classObject=this
		btn.onclick=function(){ this.classObject.map.panBy(new GSize(-this.classObject.pan,0))}
		this.btns["right"]=btn;
	}
	
	//PAN-UP
	if(typeof $("#"+id+" .up").get(0)!="undefined"){
		var btn=$("#"+id+" .up").get(0)
		btn.classObject=this
		btn.onclick=function(){ this.classObject.map.panBy(new GSize(0,this.classObject.pan))}
		this.btns["up"]=btn;
	}
	
	//PAN-DOWN
	if(typeof $("#"+id+" .down").get(0)!="undefined"){
		var btn=$("#"+id+" .down").get(0)
		btn.classObject=this
		btn.onclick=function(){ this.classObject.map.panBy(new GSize(0,-this.classObject.pan))}
		this.btns["down"]=btn;
	}
	
	//PAN-DOWN
	if(typeof $("#"+id+" .center").get(0)!="undefined"){
		var btn=$("#"+id+" .center").get(0)
		btn.classObject=this
		btn.onclick=function(){ 
			this.classObject.map.setCenter(this.classObject.center)
			this.classObject.setZoom(this.classObject.zoom)
			this.classObject.refreshMargins()
		}
		this.btns["center"]=btn;
		
	}
	
	
	
	//TIPOS DE MAPA
	
	//TIPO MAP
	if(typeof $("#"+id+" .normal").get(0)!="undefined"){
		var btn=$("#"+id+" .normal").get(0)
		btn.classObject=this
		btn.onclick=function(){ 
			this.classObject.changeType('normal')
		}
		this.types.push("normal")
		this.btns["normal"]=btn;
	}
	
	//TIPO HYBRID
	if(typeof $("#"+id+" .hybrid").get(0)!="undefined"){
		var btn=$("#"+id+" .hybrid").get(0)
		btn.classObject=this
		btn.onclick=function(){ 
			this.classObject.changeType('hybrid')
		}
		this.types.push("hybrid")
		this.btns["hybrid"]=btn;
	}
	
	//TIPO HYBRID
	if(typeof $("#"+id+" .physical").get(0)!="undefined"){
		var btn=$("#"+id+" .physical").get(0)
		btn.classObject=this
		btn.onclick=function(){ 
			this.classObject.changeType('physical')
		}
		this.types.push("physical")
		this.btns["physical"]=btn;
	}
	
	//TIPO SATELLITE
	if(typeof $("#"+id+" .satellite").get(0)!="undefined"){
		var btn=$("#"+id+" .satellite").get(0)
		btn.classObject=this
		btn.onclick=function(){ 
			this.classObject.changeType('satellite')
		}
		this.types.push("satellite")
		this.btns["satellite"]=btn;
	}
	

	

}




