/**
 * @fileoverview Contiene las herramientas comunes para el mapa.
 * @author rafaelpellicer
 * Julio 2008
 * 
 * --
 * @author : Luis Raul Marin
 * Modificado: se adicionaron variables y funciones como
 * los puntos de referencias, json para traer el promedio de
 * alcance del punto actual seleccionado por el cliente y el que se 
 * encuentra en el servidor, varios eventos listener, rutas, 
 * nube y coordenadas actuales
 * 
 * 
 */

function MapLibs(){};

 	MapLibs.listeners = new Array();
 	
 	//variables o propiedades
 	MapLibs.listeners["icon_map_layer"] = null;
 	
 	MapLibs.showInfo = false; 	//Boolean
 	MapLibs.showCheckBox = true;	//Boolean
 	
 	//objetos para el layer
 	MapLibs.punto_map;			//nombre del mapa .map	//String 		
 	MapLibs.layer_map;			//nombre de la capa		//String
 	MapLibs.view;				//nombre de la vista 	//String
 	MapLibs.where;				//condicion a buscar	//String
 	
 	/** layer puntos de referencias**/
 	//coordenadas puntos en el servidor
 	MapLibs.x;
 	MapLibs.y;
 	MapLibs.xmin;
 	MapLibs.ymin;
 	MapLibs.xmax;
 	MapLibs.ymax; 	
 	
 	//nivel y coordenadas actuales
 	MapLibs.act_x;				//coordenada x actualmente en el mapa //Floar
 	MapLibs.act_y;				//coordenada y actualmente en el mapa //Float
 	MapLibs.act_nvl;			//nivel actual en el mapa			  //Integer
 	
 	//show rutas puntos de referencia 
 	MapLibs.ShowPuntRuta; 		//si se va a marcar la ruta de los puntos de referencias //Boolean
 	//nivel del mapa
 	MapLibs.nivMap = 13;		//nivel del mapa // integer
 	MapLibs.point; 				//punto			 // float 	
 	//icono del mapa
 	MapLibs.listener			//object listener
 	MapLibs.ObjIcon;			//objeto del icono
 	//icono del punto rojo del mapa
 	MapLibs.icon_poin = 'icon_false';
 	
 	//variable para mostrar el rectangulo en el mapa, true cuando hay que mostrarlo
 	MapLibs.showRectangle = false;
 	
/**
 * Eventos del mapa
 */
	MapLibs.listeners["onzoom"] = null;
	MapLibs.listeners["onmove"] = null;
	MapLibs.listeners["onzoomd"] = null;
	MapLibs.listeners["onzooma"] = null;
	MapLibs.listeners["onchangezoom"] = null;

/**
 * Inicializa el mapa principal y el ojo de agila
 */
initMap = function()
{
	
	mapObj = new SMap(document.getElementById("map"));

	mapObj.detectWindowResize(true);
	var mSlider=mapObj.addControl(new Slider());
    mSlider.setOffSet(0, 0);
    mSlider.setPosition("top", "left");
	MapLibs.listeners["onmove"] = SEvent.AddListener(mapObj, "OnMapEndMove", MapLibs.SyncronizeMap);
	MapLibs.listeners["onchangezoom"] = SEvent.AddListener(mapObj, "OnMapChangeLevel", MapLibs.SyncronizeMap);
	MapLibs.listeners["onzoomd"] = SEvent.AddListener(mapObj, "OnZoomWindowDeactivated", MapLibs.DeactivateZoom);
	MapLibs.listeners["onzooma"] = SEvent.AddListener(mapObj, "OnZoomWindowActivated", MapLibs.ActivateZoom);
	
	
};

MapLibs.ClickOnMap = function(on){	
	var ruta = '';
	var zoom = mapObj.GetLevel();
	var factor = new Array(2621440,1310720, 655360, 327680, 163840, 81920, 40960, 20480, 10240, 5120, 2560, 1280, 640, 320, 160, 80, 40, 20, 10); 
	var k = factor[zoom-1];
	var l = '';
	var limite = '0';
	var fil = MapLibs.where;
	var params="";
	var x = on.X;
	var y = on.Y;
	params = params+'?x='+on.X;
	params = params+'&y='+on.Y;
	params = params+'&tolerance='+k;
	params = params+'&fil='+fil;
	params = params+'&limites='+limite;	
	//alert("puntos_interes/db_puntos.php"+params);
	 jQuery.getJSON("puntos_interes/db_puntos.php"+params,function(data){

		 	jQuery.each(data,function(index,cam){	
		 		//obtenemos informacion de la base de datos en forma de json
		 		MapLibs.x = parseFloat(cam["x"]);
		 		MapLibs.y = parseFloat(cam["y"]);
		 		MapLibs.xmin = parseFloat(cam["xmin"]);
		 		MapLibs.ymin = parseFloat(cam["ymin"]);
		 		MapLibs.xmax = parseFloat(cam["xmax"]);
		 		MapLibs.ymax = parseFloat(cam["ymax"]);	
		 		var arrData = new Array();
		 		arrData["rif_est"] 		= cam["rif_est"];
		 		arrData["nom_pdv"] 		= cam["nom_pdv"];
		 		arrData["tel_per_enc"]	= cam["tel_per_enc"];		 		
		 		arrData["num_tel_1_pdv"]= cam["num_tel_1_pdv"];
		 		arrData["nom_per_enc"]	= cam["nom_per_enc"];
		 		arrData["car_per_enc"]	= cam["car_per_enc"];
		 		arrData["hor_ate"]		= cam["hor_ate"];
		 		arrData["nom_urb_pdv"]	= cam["nom_urb_pdv"];
		 		arrData["via_fre"]		= cam["via_fre"];
		 		arrData["id_est"]		= cam["id_est"];
		 		
		 		var i = 0;
		 		var _limit = 10;
		 		for(ind in arrData){
		 			i++;if (arrData[ind] == null || arrData[ind] == 'null' || arrData[ind]=='') arrData[ind]="S/N";
		 			if (i == _limit)break;//cantidad de elementos que se supone son del array
		 		}
		 		
		 		if (cam["get"]){		 					 		
		 			MapLibs.ShowPuntRuta = true;
		 			// llamamos esta funcion que esta en el main
			 		//Zoom(MapLibs.xmin,MapLibs.ymin,MapLibs.xmax,MapLibs.ymax,"prueba");
			 		MapLibs.centerPoint(MapLibs.x,MapLibs.y);
			 		showInfoCloud(arrData);
		 		}
		 		
		 	});
	});
		 			 
		
	//document.getElementById('frame_info').src = 'puntos/inf_puntos.php'+params;
	on_coor = on;	
}	

//funcion para centrar el mapa cuando encuentra el punto
MapLibs.centerPoint = function (x,y){
	var point = new SGeoPoint(x,y);		
	mapObj.ZoomAndGoTo(point, mapObj.GetLevel());	
	MapLibs.point = point;
}

MapLibs.ShowPuntos = function (update){	// Mostrar Puntos de Interes.
	if (MapLibs.where == undefined || MapLibs.where == "id_sub_cat IN()") 
		return;
	var layer = mapObj.AddDynamicLayer(MapLibs.layer_map);
	layer.setMapFileFeatures(MapLibs.punto_map,MapLibs.layer_map);
	layer.setDatabaseFeatures(MapLibs.view,"the_geom",MapLibs.where);					
	layer.setDebugMode(false);	
	layer.setSRID(4326);
	layer.setOpacity(100);
	layer. withCache(false);	
	if (update)
		layer.update();
	//SEvent.ClearListeners(mapObj,"OnMapClick");
		
	if (MapLibs.showInfo == false){
		MapLibs.listener=SEvent.AddListener(mapObj, "OnMapClick", MapLibs.ClickOnMap);	
		MapLibs.showInfo = true;	
		
	}
	
}

MapLibs.DelPuntos = function (map_layer){
	if (MapLibs.showInfo == true){
		mapObj.RemoveDynamicLayer(map_layer);
		
		SEvent.RemoveListener(MapLibs.listener);
		mapObj.removeIconsOnLayer(MapLibs.icon_poin);
		//SEvent.ClearListeners(mapObj,"OnMapClick");
		MapLibs.showInfo = false;		
	}		
	
}

MapLibs.DeactivateZoom = function()
{
	jQuery("#zoomin").css("display", "block")
	jQuery("#hand-to-move").css("display", "none");
};

MapLibs.ActivateZoom = function()
{
	jQuery("#zoomin").css("display", "none")
	jQuery("#hand-to-move").css("display", "block");			
};

MapLibs.ActivateZoomRectangle = function(forced)
{
	if ((typeof(mapObj.ZoomHasBeenActivated)!="undefined" && mapObj.ZoomHasBeenActivated==true)||forced==true)
	{
		mapObj.ZoomHasBeenActivated = true;
		mapObj.activateZoomRectangle();
		if (!MapLibs.listeners["onzoom"])
		{	
			MapLibs.listeners["onzoom"] = SEvent.AddListener(mapObj, "OnMapChangeLevel", MapLibs.ActivateZoomRectangle);
		}
	}	
};


MapLibs.DeactivateZoomRectangle = function()
{
	delete mapObj.ZoomHasBeenActivated;
	mapObj.cancelZoomRectangle();
	
};
MapLibs.SyncronizeMapBE = function(){
	bemap.DisableDrag();
	bemap.DisableKeyboard();
	bemap.DisableClick();	

};

MapLibs.SyncronizeMap = function(update){
			
	var zoom = mapObj.GetLevel();	
	if (zoom >= MapLibs.nivMap){ //nivel del mapa 
		MapLibs.ShowPuntos(update);
				
		if (MapLibs.showCheckBox){			
			if (!MapLibs.showInfo){	 //cuando se abre por primera vez
				//funcion del index para mostrar check
				chk_est_show();
				jQuery("#div_puntos_hide").css("display","none");												
				
			} else {	
				
				jQuery("#div_puntos_hide").css("display","none");
				jQuery("#div_puntos").css("display","block");
				menu_chan();
			}
			//esto es para ejecutar la ventana cada vez que llegue en el nivel
			//if(!(menu.children("a#a_sec-puntos-interes").is(".selected")))
	   		// 	menu.accordion( 'activate',  0 );
				MapLibs.showCheckBox = false;
		}
	
	} else {				
		MapLibs.DelPuntos(MapLibs.layer_map);
		//funcion del index para ocultar check	
		jQuery("#div_puntos").css("display","none");
		jQuery(document).ready(function(){
			chk_est_hide();	
		})
		
		MapLibs.showCheckBox = true;
	}		
	
	
	var center = mapObj.GetCenter();
	//se guardan los las coordenadas del mapa en un campo de texto
	jQuery("#txt_x").val(center.X);
	jQuery("#txt_y").val(center.Y);
	
	//posicion posicion y nivel actual en el mapa
	MapLibs.act_x = center.X;
	MapLibs.act_y = center.Y;
	MapLibs.act_nvl = zoom;

	MapLibs.history.save();
};


/**
 * Inicializa la animaci�n del ojo de �guila y
 * las herramientas del mapa.
 */
jQuery(function () {
	jQuery("#bem-shrinks").bind("click", function(){toogleBirdeye();});
	jQuery("#control_3").bind("click", function(){toogleMapControl();});	
});


/**
 * Expande o contrae el ojo de �gila
 */
toogleBirdeye = function(){
	jQuery("#bird-eye-container").animate({
		height: "0px", width: "0px", "height": "toggle", "width": "toggle"
	}, { duration: 250, queue: false });
	jQuery("#bem-shrinks").toggleClass("be-shrinked");
};

/**
 * Expande o contrae las herramientas del mapa
 */
toogleMapControl = function()
{
	var obj = jQuery("#map-bar");
	var _right = "-318px";
	
	if(obj.css("right") == _right)
	{
		_right = "0px";
	}
	
	obj.animate({
		right:_right}, { duration:500, queue:false });
};

 
MapLibs.ZoomIn = function()
{
	mapObj.ZoomIn();
};

MapLibs.ZoomOut = function()
{
	//this.DeactivateZoomRectangle();
	mapObj.ZoomOut();
};

MapLibs.ExtendTo = function(xmin, ymin, xmax, ymax)
{
	mapObj.ZoomToBox(new SGeoBox(xmin, ymin, xmax, ymax));
};


MapLibs.setInitialExtent = function(x, y , niv)
{
	this.xini = x;
	this.yini = y;
	this.nivini = niv;
	

};

MapLibs.goInitialExtent = function()
{ 
	var x = (typeof(this.xini)=="undefined"||!this.xini)?0:this.xini;
	var y = (typeof(this.yini)=="undefined"||!this.yini)?0:this.yini;
	var niv = (typeof(this.nivini)=="undefined"||!this.nivini)?0:this.nivini;
	
	mapObj.ZoomAndGoTo(new SGeoPoint(x,y),niv);
};


MapLibs.slide = function(direction)
{ 
	var from = null;
	var w = mapObj.mapPixelWidth;
	var h = mapObj.mapPixelHeight;
	
	switch(direction)
	{
		case "up":
			from = new SGeoPoint(w/2, 0);
			break;
		case "left":
			from = new SGeoPoint(0, h/2);
			break;
		case "down":
			from = new SGeoPoint(w/2, h);
			break;
		case "right":
			from = new SGeoPoint(w, h/2);
			break;
		case "up-left":	
			from = new SGeoPoint(0, 0);
			break;
		case "up-right":	
			from = new SGeoPoint(w, 0);
			break;
		case "down-left":
			from = new SGeoPoint(0, h);
			break;
		case "down-right":
			from = new SGeoPoint(w, h);
			break;

			
	}
	
	if (from)
	{
		var to = new SGeoPoint(w/2, h/2);
		mapObj.FlyMapCenter(from, to);
	}
	

};
MapLibs.history = {
	lastback:false,
	max:20,
	levels:null,
	afterSaving:false,
	save:function()
	{
		var o = new Object();
		o.x = mapObj.GetCenter().X;
		o.y = mapObj.GetCenter().Y;
		o.level = mapObj.GetLevel();
	
		this.points.push(o);
		
		if (this.points.length > this.max)
			this.points.shift();

		
	},
	
	back:function()
	{
		if (this.points.length<2)
			return;
					
		MapLibs.DeactivateZoomRectangle();

			
		if (this.points.length>=2)
		{
			var p =  this.points[this.points.length-2];
			var removed =this.points.splice(this.points.length-2,2);
		}
		else
		{
			var p =  this.points[this.points.length-1];
			var removed =this.points.pop();
		}
		
		
		 	
		if (typeof(p)=="undefined"||!p)
			return;
		
		
		mapObj.ZoomAndGoTo(new SGeoPoint(p.x, p.y), p.level);
		
	}
};


 MapLibs.history.points = new Array();
