// JavaScript Document

var width = 660; //800;
var height	= 547.46;//600;


//funcion que elimina eventos del cuerpo del iframe
function DeleteEventIframeBody(div,evt){
	
	//Obtenemos el body del iframe Map
	var objDiv = $(div).contents().find("body");
	
	//Eliminamos el evento
	objDiv.unbind(evt);
}

//Funcion para seleccionar un div dentro del iframe
function selectDivIframe(div){

	var objDiv = $("#Map").contents().find("div#"+div+"");// seleccionamos el div con id ImageDiv
	return objDiv; //retornamos el obj
		
}


function LoadMap(){

	$(document).ready(function(){
							   
		var Lati= GetUrlParams('PosLa');
	   	var Long = GetUrlParams('PosLo');
		var Visit = GetUrlParams('Visit');
		var LayerId = GetUrlParams('LId');
		var Extent = GetUrlParams('extent');
		var CltD = GetUrlParams("urlClient");

	//Verificamos si IngeoMaps se cargo por medio de un link desde otra pagina
		if((Lati != "") && (Long != "")&&(CltD != ""))//True: 	Es el modelo de latitud y longitud
		{	
			SearchByNotIngeoLL(Lati,Long,CltD); 
		}else
		{
			//Verificamos si se envio com oparametro el extent.
			if((Extent != "")&&(Lati=="")&&(Long=="")&&(CltD==""))//True: si solamente se esta enviando el extent. Por ejemplo en el caso de enviar a un amigo
			{
				LocatedByExtent(Extent);
			}else
			{
				//En caso de que no se haya ejecutado desde otra pagina.
				ajaxLoadImage('Load/AjaxImage.php','operation=Inicio&width=' + width + '&height=' + height,'ImageDiv',true);
			}		
		}
		
		ajaxLoadCmbState('LocationControls/AjaxState.php','ParamsDiv');
	})
}
function LoadMapRouteFavorite(){

	$(document).ready(function(){
	
	
		//En caso de que no se haya ejecutado desde otra pagina.
		ajaxLoadImage('Load/AjaxImageRouteFavorite.php','operation=Inicio&width=' + width + '&height=' + height,'ImageDiv',true);
			
		ajaxLoadCmbState('LocationControls/AjaxState.php','ParamsDiv');
	})
}
 function ajaxLoadCmbState(urlajax,div){
			
	$.ajax({
		type: "GET",
		url: urlajax,
		dataType: "html",
		cache: false,
		success: function(XMLhtml){
	
			$("#ButtonTableEMP").attr("style","visibility:visible"); 

			//RelocateObject("ParamsDiv", EMP_LEFT, EMP_TOP); 
			var JQobjParamsDiv = $("#"+div);
			//JQobjParamsDiv.css("visibility","visible");
			JQobjParamsDiv.html(XMLhtml);	
			
			
		}
	}) 
 }

/***************************************************************************
 * OperationOnMap
 * Procedimiento que cambia las imagénes de los botones según se seleccionen
 ****************************************************************************/	
function OperationOnMap(ImageOperation){ 

	$(document).ready(function(){
		
		ExecuteFile("Load/AjaxCleanDistanceValue.php","");

		if(ImageOperation.name == "ZoomIn"){

			// en caso que haya ejecutado el mismo boton dos veces hay que desactivarlo o activarlo. El if evalua este caso
			if($("#keep").attr("value")==1){
		
				ImageOperation.src ="../Images/Map/Tools/GIF/UBICATE_+.gif";
				$("#keep").attr("value",0); 
				$("#zoom").attr("value",""); 
				
				$("#Map").contents().find("body").css("cursor", "default");
				
			  	//Eliminamos el evento drag
				document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");
				
			  	//Eliminamos el evento mousedown
				selectDivIframe("ImageDiv").unbind("mousedown");
				
			}
			else{
		
				ImageOperation.src = "../Images/Map/Tools/GIF_SELECCIONADOS/UBICATE+_+.gif";
			
			   //Eliminamos el evento drag
				 document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");
				 
				//frames["Map"].DestroyDragObjInIframe("#map");
				var objDivMap = selectDivIframe("ImageDiv");
				
			   //Eliminamos el evento mousedown
				objDivMap.unbind("mousedown");
			
				$("#zoom").attr("value",$(ImageOperation).attr("value")); 
				
				$("#keep").attr("value",  $("#zoom").attr("value")); 
							
				$("#ZoomOut").attr("src", "../Images/Map/Tools/GIF/UBICATE_-.gif");
				$("#center").attr("src", "../Images/Map/Tools/GIF/UBICATE_CENTRAR.gif");
				$("#info").attr("src", "../Images/Map/Tools/GIF/UBICATE_INFORMACION.gif");
				$("#ruler").attr("src", "../Images/Map/Tools/GIF/UBICATE_DISTANCIA.gif");
				$("#pan").attr("src", "../Images/Map/Tools/GIF/UBICATE_MOVER.gif");
							
				//Asigno a la variable CursorType(que contiene el valor que indica al cursor que mantenga la imagen de la operacion luego de realiarla)
				$("#Map").contents().find("body").css("cursor", "../../Images/Map/Tools/btnZoomIn.cur");
			
				//Asignamos el evento de zoomin al mapa.
				//Cuando el documento dentro del iframe este completamente cargado, se ejecutara la funcion correspondiente
				$(document.getElementById('Map').contentWindow).ready(function(){	
					objDivMap.mousedown( function(e){
						//Limpiamos el resultado si el usuario realizo el evento de la regla
	
						if($("#RulerInfo").css("visibility")=="visible"){
							CleanDiv("#RulerInfo");
							ExecuteFile("Load/AjaxCleanDistanceValue.php","");
						}
						//Limpiamos el resultado del info si el usuario realizo el evento info
						if($("#divInfo").css("visibility")=="visible"){
							CleanDiv("#divInfo");
						}

						mouseDownRubberBand("ImageDiv",e,"ZoomRect");
				})	
			  })
			}			
		}
		else{
			if(ImageOperation.name == "ZoomOut"){
					
				if($("#keep").attr("value")==-1){
					
					ImageOperation.src = "../Images/Map/Tools/GIF/UBICATE_-.gif";
					$("#keep").attr("value", 0);
					$("#zoom").attr("value", "");
					
					//Asigno a la variable CursorType que desactive la imagen que muestra la operacion realizada
					$("#Map").contents().find("body").css("cursor", "default");
					  //Eliminamos el evento drag
						document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
					  //Eliminamos el evento mousedown
					  selectDivIframe("ImageDiv").unbind("mousedown");
					
				}
				else{
					ImageOperation.src = "../Images/Map/Tools/GIF_SELECCIONADOS/UBICATE-_-.gif";
					 //Eliminamos el evento drag
					 var objDivMap = selectDivIframe("ImageDiv");
					document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
					 //Eliminamos el evento mousedown
					 objDivMap.unbind("mousedown");
					
					$("#zoom").attr("value", $(ImageOperation).attr("value"));
					$("#keep").attr("value", $("#zoom").attr("value")); 
					
					$("#ZoomIn").attr("src", "../Images/Map/Tools/GIF/UBICATE_+.gif");
					$("#center").attr("src", "../Images/Map/Tools/GIF/UBICATE_CENTRAR.gif");
					$("#info").attr("src", "../Images/Map/Tools/GIF/UBICATE_INFORMACION.gif");
					$("#ruler").attr("src", "../Images/Map/Tools/GIF/UBICATE_DISTANCIA.gif");
					$("#pan").attr("src", "../Images/Map/Tools/GIF/UBICATE_MOVER.gif");
							
					$("#Map").contents().find("body").css("cursor", "../../Images/Map/Tools/btnZoomOut.cur");
							
					//Asignamos el evento de zoomout al mapa
					//Cuando el documento dentro del iframe este completamente cargado, se ejecutara la funcion correspondiente
					$(document.getElementById('Map').contentWindow).ready(function(){	
						objDivMap.mousedown( function(e){
														  
							//Limpiamos el resultado si el usuario realizo el evento de la regla
							if($("#RulerInfo").css("visibility")=="visible"){
								CleanDiv("#RulerInfo");
								ExecuteFile("Load/AjaxCleanDistanceValue.php","");
							}
						
							//Limpiamos el resultado del info si el usuario realizo el evento info
							if($("#divInfo").css("visibility")=="visible"){
								CleanDiv("#divInfo");
								//Para el caso del div de Info, hay que asignar al display none
								$("#divInfo").css("display",'none');	
							}
							//mouseDownRubberBand("ImageDiv",e,"ZoomRect");
							ZoomOut(e);
						})
					})
				 }
			}
			else{//fin 3
			
				if(ImageOperation.name == "center"){	
										
					if($("#keep").attr("value")=="center"){
					
						ImageOperation.src = "../Images/Map/Tools/GIF/UBICATE_CENTRAR.gif";
						$("#keep").attr("value", 0);
						$("#zoom").attr("value", "");
							
						$("#Map").contents().find("body").css("cursor", "default");
						  //Eliminamos el evento drag
						 // frames["Map"].DestroyDragObjInIframe("#map"); 
						document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
						 //Eliminamos el evento mousedown
						 selectDivIframe("ImageDiv").unbind("mousedown");
					}
					else{
						
						ImageOperation.src = "../Images/Map/Tools/GIF_SELECCIONADOS/UBICATE-_CENTRAR.gif";
						
						$("#zoom").attr("value",  $(ImageOperation).attr("value"));
						$("#keep").attr("value", $("#zoom").attr("value"));
						
						$("#ZoomIn").attr("src", "../Images/Map/Tools/GIF/UBICATE_+.gif");
						$("#ZoomOut").attr("src", "../Images/Map/Tools/GIF/UBICATE_-.gif");
						$("#info").attr("src", "../Images/Map/Tools/GIF/UBICATE_INFORMACION.gif");
						$("#ruler").attr("src", "../Images/Map/Tools/GIF/UBICATE_DISTANCIA.gif");
						$("#pan").attr("src", "../Images/Map/Tools/GIF/UBICATE_MOVER.gif");
					
						$("#Map").contents().find("body").css("cursor", "../../Images/Map/Tools/btnCenter.cur");
						 //Eliminamos el evento drag
						 var objDivMap = selectDivIframe("ImageDiv");
						// frames["Map"].DestroyDragObjInIframe("#map"); 
						document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
						//Eliminamos el evento mousedown
						objDivMap.unbind("mousedown");
						
						//Asignamos el evento centrar el mapa
						//Cuando el documento dentro del iframe este completamente cargado, se ejecutara la funcion correspondiente
						$(document.getElementById('Map').contentWindow).ready(function(){	
							objDivMap.mousedown( function(e){
								//Limpiamos el resultado si el usuario realizo el evento de la regla
	
								if($("#RulerInfo").css("visibility")=="visible"){
									CleanDiv("#RulerInfo");
									ExecuteFile("Load/AjaxCleanDistanceValue.php","");
								}
								//Limpiamos el resultado del info si el usuario realizo el evento info
								if($("#divInfo").css("visibility")=="visible"){
									CleanDiv("#divInfo");
								}
								Center(e);
							})
						})
					 }
				}
				else{
					if(ImageOperation.name == "info"){
					
						if($("#keep").attr("value")=="info"){
					
							ImageOperation.src = "../Images/Map/Tools/GIF/UBICATE_INFORMACION.gif";
							$("#keep").attr("value", 0);
							$("#zoom").attr("value", "");
								
							$("#Map").contents().find("body").css("cursor", "default");
							  //Eliminamos el evento drag
							// frames["Map"].DestroyDragObjInIframe("#map"); 
							document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
							//Eliminamos el evento mousedown
							selectDivIframe("ImageDiv").unbind("mousedown");
												
						}
						else{
							
							ImageOperation.src = "../Images/Map/Tools/GIF_SELECCIONADOS/UBICATE-_INFORMACION.gif";
							
							$("#zoom").attr("value",  $(ImageOperation).attr("value"));
							$("#keep").attr("value", $("#zoom").attr("value"));
							
							$("#ZoomIn").attr("src", "../Images/Map/Tools/GIF/UBICATE_+.gif");
							$("#ZoomOut").attr("src", "../Images/Map/Tools/GIF/UBICATE_-.gif");
							$("#center").attr("src", "../Images/Map/Tools/GIF/UBICATE_CENTRAR.gif");
							$("#ruler").attr("src", "../Images/Map/Tools/GIF/UBICATE_DISTANCIA.gif");
							$("#pan").attr("src", "../Images/Map/Tools/GIF/UBICATE_MOVER.gif");
						
							$("#Map").contents().find("body").css("cursor", "crosshair");
							  //Eliminamos el evento drag
							  var objDivMap = selectDivIframe("ImageDiv");
							document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
							//Eliminamos el evento mousedown
							objDivMap.unbind("mousedown");
							
							//Asignamos el evento de info al mapa
							objDivMap.mousedown( function(e){
														
								//Variable que contiene el html de la forma del info
								var vformInfo = '<img id="FLinfo" class="Layer1" src="../Images/Map/Info/InfoFondo.gif" /><div id="idtxtInfo"></div><div id="x"><img src="../Images/Map/Info/legend_x.png" onClick="javascript:closeInfo()" width="14" height="14"/></div>';
																
								infoMap("Load/AjaxInfo.php","mapX=" + e.clientX + "&mapY=" + e.clientY + "&Browser=" + navigator.appName,"#divInfo",vformInfo,"#idtxtInfo",e.clientX,e.clientY);
								
							})		
								
						 }
					}else{
						if(ImageOperation.name == "ruler")
						{							
							if($("#keep").attr("value")=="ruler"){
						
							ImageOperation.src = "../Images/Map/Tools/GIF/UBICATE_DISTANCIA.gif";
								$("#keep").attr("value", 0);
								$("#zoom").attr("value", "");
								
								$("#Map").contents().find("body").css("cursor", "default");
								  //Eliminamos el evento drag
								// frames["Map"].DestroyDragObjInIframe("#map"); 
								document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
								//Eliminamos el evento mousedown
								selectDivIframe("ImageDiv").unbind("mousedown");
								
								//Limpiamos el resultado si el usuario realizo el evento de la regla
				
								if($("#RulerInfo").css("visibility")=="visible"){
										CleanDiv("#RulerInfo");
										ExecuteFile("Load/AjaxCleanDistanceValue.php","");
								}
													
				
							}else{
						
								ImageOperation.src = "../Images/Map/Tools/GIF_SELECCIONADOS/UBICATE-_DISTANCIA.gif";
								$("#zoom").attr("value",  $(ImageOperation).attr("value"));
								$("#keep").attr("value", $("#zoom").attr("value"));
								
								$("#ZoomIn").attr("src", "../Images/Map/Tools/GIF/UBICATE_+.gif");
								$("#ZoomOut").attr("src", "../Images/Map/Tools/GIF/UBICATE_-.gif");
								$("#center").attr("src", "../Images/Map/Tools/GIF/UBICATE_CENTRAR.gif");
								$("#info").attr("src", "../Images/Map/Tools/GIF/UBICATE_INFORMACION.gif");
								$("#pan").attr("src", "../Images/Map/Tools/GIF/UBICATE_MOVER.gif");
							
								$("#Map").contents().find("body").css("cursor", "pointer");
								  //Eliminamos el evento drag
								  var objDivMap = selectDivIframe("ImageDiv");
								  
								document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
									//Eliminamos el evento mousedown
								objDivMap.unbind("mousedown");
								
								//Asignamos el evento de ruler al mapa
								//Cuando el documento dentro del iframe este completamente cargado, se ejecutara la funcion correspondiente
								$(document.getElementById('Map').contentWindow).ready(function(){	
									objDivMap.mousedown( function(e){
																
											//Limpiamos el resultado del info si el usuario realizo el evento info
											if($("#divInfo").css("visibility")=="visible"){
												CleanDiv("#divInfo");
											}
								
										Ruler(e,'RulerInfo');
									})					
								})
							  }
						}else{
							if(ImageOperation.name == "pan")
							{	
								if($("#keep").attr("value")=="pan"){
						
									ImageOperation.src = "../Images/Map/Tools/GIF/UBICATE_MOVER.gif";
									$("#keep").attr("value", 0);
									$("#zoom").attr("value", "");
										
									$("#Map").contents().find("body").css("cursor", "default");
									
									//Eliminamos el evento drag
									document.getElementById('Map').contentWindow.DestroyDragObjInIframe("#map");;
									//Eliminamos el evento mousedown
									selectDivIframe("ImageDiv").unbind("mousedown");
																									
								}else{
										
									ImageOperation.src = "../Images/Map/Tools/GIF_SELECCIONADOS/UBICATE-_MOVER.gif";
								
									$("#zoom").attr("value",  $(ImageOperation).attr("value"));
									$("#keep").attr("value", $("#zoom").attr("value"));
									
									$("#ZoomIn").attr("src", "../Images/Map/Tools/GIF/UBICATE_+.gif");
									$("#ZoomOut").attr("src", "../Images/Map/Tools/GIF/UBICATE_-.gif");
									$("#center").attr("src", "../Images/Map/Tools/GIF/UBICATE_CENTRAR.gif");
									$("#info").attr("src", "../Images/Map/Tools/GIF/UBICATE_INFORMACION.gif");
									$("#ruler").attr("src", "../Images/Map/Tools/GIF/UBICATE_DISTANCIA.gif");
							
								$("#Map").contents().find("body").css("cursor", "../../Images/Map/Tools/btnPan.cur");	
									
									//Se define denuevo poruqe no lo puedopasar como parametro
									var objDivMap = selectDivIframe("ImageDiv"); 
											
									//Eliminamos el evento mousedown
									objDivMap.unbind("mousedown"); 
																 
									//Asignamos el evento de ruler al mapa
									//var objDivMap = $("#Map").contents().find("input").eq(0);
									
									if($("#RulerInfo").css("visibility")=="visible"){
										CleanDiv("#RulerInfo");
										ExecuteFile("Load/AjaxCleanDistanceValue.php","");
									}
									//Limpiamos el resultado del info si el usuario realizo el evento info
									if($("#divInfo").css("visibility")=="visible"){
										CleanDiv("#divInfo");
									}
						
									//La funcion dragmap contiene de una vez el evento onmouse drag	
									document.getElementById('Map').contentWindow.dragMap(objDivMap);
													
								}
							}
						}		
					}	
				}//fin 4			
			 }//fin3
		}//fin 2	
	})
}//fin 1

/***************************************************************************
 * LoadMunicipality
 * Procedimiento que dado un estado muestra los municipios correspondientes
 * en el combo
 ****************************************************************************/
function LoadMunicipality(intState,objDiv,sURL){

	if (intState>0){
		var sParams="cmbState="+intState;
	
		$.ajax({
			type: "GET",
			url: sURL,
			data: sParams,
			dataType: "html",
			cache: false,
			success: function(XMLhtml){
		
				$('#'+objDiv).html(XMLhtml);	
				$('#'+objDiv).attr("enabled", true);	
			}
		})
	}
	else{
		$('#cmbParish').attr("value", 0);
		$('#cmbParish').attr("disabled", true);
	}
	
}

/***************************************************************************
 * LoadParish
 * Procedimiento que dado un municipio muestra las parroquias correspondientes 
 * en el combo
 ****************************************************************************/
function LoadParish(intMunicipality,objDiv,sURL){
		
	var sParams="cmbMunicipality="+intMunicipality;
	
	$.ajax({
		type: "GET",
		url: sURL,
		data: sParams,
		dataType: "html",
		cache: false,
		success: function(XMLhtml){
	
			$('#'+objDiv).html(XMLhtml);	
			$('#'+objDiv).attr("enabled", true);	
		}
	}) 
}

/****************************************************************
SetLocationMap:
Funcion que ejecuta la busqueda sobre el mapa cambiando la opciones del combo					

*****************************************************************
*/
function SetLocationMap(ID,op)
{

	//Limpiamos el resultado del info si el usuario realizo el evento info

	if($("#divInfo").css("visibility")=="visible"){
		CleanDiv("#divInfo");
		//Para el caso del div de Info, hay que asignar al display none
		$("#divInfo").css("display",'none');	
	}
			
		//***************************************************************************************************************	
	//Esta variable nos indica si el usuario ya realizó una busqueda. En caso de que no la haya realizado, será null.
	//var tableContainer = document.getElementById("Resultados").contentWindow.document.getElementById("tableContainer");
	var objFrame = $("#Resultados").contents().find('iframe');
	var tableContainer = objFrame.contents().find("tableContainer");
	
	
	if(tableContainer != null)//Ha realizado una búsqueda, por lo tanto limpiamos el resultado de la misma para que no haya problemas al pulsar el combo box denuevo y realizar otra oepracion que tenga que ve con la busqueda
	{
		//********Cambiamos la pagina de resultados por la que contiene los ejemplos********
		//document.getElementById("Resultados").contentWindow.location = "Search/Results.php";
		$("#Resultados").contents().location = "Search/Results.php";
	
	}
	//***************************************************************************************************************


	//Limpiamos los div de Info sobre el mapa y de la informacion de la regla en el caso de que el usuario haya realizado alguna o ambas operaciones	
	if(document.getElementById("RulerInfo").style.visibility == "visible" || document.getElementById("divInfo").style.visibility == "visible")
	{
		CleanDiv("#RulerInfo");
	}

	if(op == 1)
	{
		if (ID > 0){
			ajaxLoadImage('Load/AjaxComboSearch.php','StateID=' + ID + '&opcion=1','ImageDiv',true);
		}
		else{	
			Original();
		}
			
	}else if(op==2)
	{
		if (ID > 0){	
			ajaxLoadImage('Load/AjaxComboSearch.php','StateID=' + ID + '&opcion=2','ImageDiv',true);
		}//Si el municipio es nulo, centro en el estado
		else{
			ajaxLoadImage('Load/AjaxComboSearch.php','StateID=' + document.getElementById('cmbState').value + '&opcion=1','ImageDiv',true);
			//getDataImage(datasource);
		}
			
	}else if(op == 3)
	{
		if (ID > 0){
			ajaxLoadImage('Load/AjaxComboSearch.php','StateID=' + ID + '&opcion=3','ImageDiv',true);
		}
		else{
			if (document.getElementById('cmbMunicipality').value>0){
				
				ajaxLoadImage('Load/AjaxComboSearch.php','StateID=' + document.getElementById('cmbMunicipality').value + '&opcion=2','ImageDiv',true);
			}
			else {
				ajaxLoadImage('Load/AjaxComboSearch.php','StateID=' + document.getElementById('cmbState').value + '&opcion=1','ImageDiv',true);
								
			}			
		}
	} 	
}


/***************************************************************************
 * original
 * Procedimiento ubica el mapa en el estado inicial "todo el mapa"
 ****************************************************************************/
function Original(){
	
	// Asigno a la bandera 0 para que deje de dibujar la linea continuamente y pueda volver a realizar ruler
	document.op_map.OneLine.value = 0;

	document.op_map.zoom.value = 3;
	
	//Se limpia en caso de que haya alguna informacion sobre el mapa
	if(document.getElementById("RulerInfo").style.visibility == "visible" || document.getElementById("divInfo").style.visibility == "visible")
	{
		CleanDiv("#RulerInfo");
	}
	
	ajaxLoadImage("Load/AjaxAllCountry.php", "width=" + width + "&height=" + height,'ImageDiv',true);
}

/****************************************************************
getReferenceImage:
Funcion que obtiene la imagen de la referencia					

*****************************************************************
*/
function getReferenceImage(url){
	
	var strDiv ="#ReferenceDiv";
	ajaxLoadDataReference(url,strDiv);
	
	RelocateObject("ReferenceDiv", REF_LEFT, REF_TOP);	
	
	$(strDiv).css("visibility","visible");
}


/*************************** FUNCIONES DE BUSQUEDA DESDE OTRA PAGINA**************************/
/************************** FUNCIONES DE BUSQUEDA DESDE LAS SECCIONES ************************/

function GetUrlParams( name ){
	
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp ( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	
	if( results == null ){
		return"";
	}
	else{
		var strResult = results[1];
		
		strResult = strResult.replace(/(%20\s*)|(\s*$)/g," ");
		
		return trim(strResult);
	}
		
}

function SearchFOP()
{
//Capturo las variables mandada por $get de lo que se desea buscar

	var txtName = GetUrlParams('txtName');
	var rbtnSearch = GetUrlParams('rbtnSearch');
	var CityName = GetUrlParams('CityName');
	var LayerId = GetUrlParams('LayerId');
	var sfop = GetUrlParams('sfop');
	
	if(sfop==1)
	{
		var pagina = 1;
		
		//txtName =encodeURIComponent(txtName);
		//CityName =encodeURIComponent(CityName);
		//alert(txtName);
		
		$('#txtName').attr("value", decodeURIComponent(txtName));
		$('#txtCity').attr("value", decodeURIComponent(CityName));
		
		var searchType = document.getElementById("cmbSearchType");
		
		if (searchType){
			
			for (index = 0; index < searchType.length; index++){
				if (searchType.options[index].value == LayerId){
					searchType.options[index].selected=true;
					index= searchType.length;
				}
			}
		}

		//L0TJ(0,0);
		ViewResults();
		var sParams="cmbState=-1&cmbMunicipality=-1&cmbParish=-1&txtName="+txtName+"&rbtnSearch="+rbtnSearch+"&CityName="+CityName+"&LayerId="+LayerId+"&pagina="+pagina; //+"&SectorId=-1";
		/*if ($("#SearchType_0").attr("checked")) {
			getDataFOP("Result","Search/AjaxSearch.php", sParams);
			
		}
		//TIPO DE BUSQUEDA DICCIONARIO
		else {*/
		getDataFOP("Results","Search/AjaxSearchDictionary.php", sParams);
			
		//}
	}
}

/***************************************************************************
 * getDataFOP
 * Procedimiento que obtiene los datos devueltos de una busqueda desde otra pagina
 ****************************************************************************/
function getDataFOP(objDiv, urlajax, dataajax)
{
	//var obj = document.getElementById("Resultados").contentWindow.document.getElementById(objDiv);
	var objFrame = $("#Resultados").contents().find('iframe');	
	var obj = objFrame.contents().find('div');

	RelocateObject("ReferenceDiv", REF_LEFT, REF_TOP);	
	
	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		beforeSend: function(XMLhtml){
		
				obj.html("<p class='titulo2verde11' align='left'><img src='../../Images/Map/Loading/InfoLoading.gif'/> Buscando, por favor espere...</p>");		
				$("#btnAjaxSearch").attr("disabled", true);	   
				$('#txtName').attr("disabled", true);
				$('#txtCity').attr("disabled", true);
				$('#cmbSearchType').attr("disabled", true);
				document.body.style.cursor="wait";

		},
		success: function(XMLhtml){
			//Evaluo si la variable de session caducó
			var answer = XMLhtml;
			//##############################Obtenemos los string necesarios###################
			
			//Obtengo posicion del caracter que divide los resultados de los datos necesarios para simular el setlocation
			var PosSpaceDataSearchByNotIngeo = answer.indexOf("~");
			
			//Sumo una posicion para poder extraer el string correctamente
			PosSpaceDataSearchByNotIngeo = PosSpaceDataSearchByNotIngeo + 1;
			
			//Obtengo los datos necesarios para realizar el setlocation
			var DataSearchByNotIngeo = answer.slice(PosSpaceDataSearchByNotIngeo);
			
			//Resto una posicion para poder extraer el string correctamente hasta esa posicion
			PosSpaceDataSearchByNotIngeo = PosSpaceDataSearchByNotIngeo - 1;
			
			//Actualizamos el string que contiene la informacion de los resultados.
			answer = answer.substring(0,PosSpaceDataSearchByNotIngeo);

			var Fwidth = 100;
			
			 //Indico al usuario cuantos registros se obtuvo de la busqueda:
			if(answer != "SessionRefresh")
			{ 
				obj.html(XMLhtml);
				getReferenceImage("Load/AjaxReferenceImage.php");
				$("#btnAjaxSearch").attr("disabled", false);	   
				$('#txtName').attr("disabled", false);
				$('#txtCity').attr("disabled", false);
				$('#cmbSearchType').attr("disabled", false);
				document.body.style.cursor = "default";
				
			}else{
				window.open('CloseIngeoMaps.php','_parent','','true');
			}
			
		},
		error: function(XMLhtml, textStatus, errorThrown){
			var htmlError = "<p class='titulo2verde11' align='left'>No se pudo realizar la busqueda...</p>";
			obj.html(htmlError); 
			
			$("#btnAjaxSearch").attr("disabled", true);	   
			$('#txtName').attr("disabled", true);
			$('#txtCity').attr("disabled", true);
			$('#cmbSearchType').attr("disabled", true);

			document.body.style.cursor = "default";
			document.getElementById("btnAjaxSearch").focus();
		}
	})
}


//**************************************************
//**    SearchByNotIngeoLL() 
//*    Busca una posada dado la longitud y latitud desde otra pagina que no sea IngeoMaps
//**************************************************

function SearchByNotIngeoLL(Lati,Long,CltD)
{
	$(document).ready(function(){

		var fMap =document.getElementById("Map").contentWindow.document.getElementById("ImageDiv");
		
		RelocateObject("ReferenceDiv", REF_LEFT, REF_TOP);	
		
		var urlajax = "Search/AjaxSearchByNotIngeoLL.php";
		var dataajax = "dblLati=" + Lati  + "&dblLong=" + Long;
		
		$.ajax({
			type: "GET",
			url: urlajax,
			data: dataajax,
			dataType: "html",
			cache: false,
			success: function(XMLhtml){

				//Capturamos la data que nos permite decidir a que zoom mostraremos la posada
				var posCityID = XMLhtml.indexOf("/");
				var CityName = XMLhtml.substr(0, posCityID); 
			
				//..........Obtenemos los zoom respectivos............
				var arrayCltD = CltD.split("/")//Arreglo que contiene los datos del cliente, su identificador y los zoom respectivos.
				
				
				var Clt = arrayCltD[0]; //Identificador del cliente
				var ZC = arrayCltD[1]; //Z en ciudad
				var ZNC = arrayCltD[2]; // Z no en ciudad
				
			
				//Evaluamos si el objeto esta en ua ciudad o no
				if(CityName.toUpperCase() == "SIN CIUDAD")//true: Si la posada no se encuentra en una ciudad. 
				{
					var zoom = ZNC;
				}else{
					var zoom = ZC;
				}
				
					
				var  op = 1; //Se le indica a ajaxviewsearch que va a realizar una busqueda por latitud y longitud
						 
				//Se mantiene la misma estructura que realiza advancesearch cuando se busca por latitud y longitud
				getDataSearchByNotIngeoLL("Search/AjaxViewSearchByLL.php", "dblLati=" + Lati  + "&dblLong=" + Long +"&dblZoom=" +zoom +"&op=" + op + '&width=' + width + '&height=' + height + "&Clt="+Clt);
							
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				var htmlError = "<p class='titulo2verde11' align='left'>Ha ocurrido un error...</p>";
				fMap.innerHTML = htmlError; 
			}
		})
	});
}


function getDataSearchByNotIngeoLL(urlajax, dataajax)
{
	var fMap =document.getElementById("Map").contentWindow.document.getElementById("ImageDiv");
		

	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		beforeSend: function(html){

							
			var htmlWait = "<table width='638' height='196'><!--DWLayoutTable--><tr><td width='145' height='184'>&nbsp;</td><td width='324'>&nbsp;</td><td width='147'>&nbsp;</td></tr><tr><td height='72'>&nbsp;</td><td align='center' valign='middle'><input type='image' id='map' name='map'  src='../../Images/Map/Loading/MapLoad.gif' /><p class='titulo3verde16' align='center'> Cargando...</p><td>&nbsp;</td></tr><tr><td height='128'>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></table>";
							
			fMap.innerHTM =htmlWait;

		},
		success: function(XMLhtml){

			if(XMLhtml != "SessionRefresh")
			{
				fMap.innerHTML = XMLhtml;
				
				//Habilito el boton search
				$("#btnAjaxSearch").attr("disabled", false);
				$("#txtName").attr("disabled", false);
				
				getReferenceImage("Load/AjaxReferenceImage.php");

			}else
			{
				window.open('CloseIngeoMaps.php','_parent','','true');
			}	
			
		},
		error: function(XMLhtml, textStatus, errorThrown){
			var htmlError = "<p class='titulo2verde11' align='left'>Ha ocurrido un error...</p>";
			fMap.innerHTML = htmlError; 
		}
	})
}

//*****************************
//LocatedByExtent: Ubica en el mapa mediante el parametro extent del mapa
//Se usa cuando: Ubicar al usuario en acaso que se envie el mapa mediante la herramienta enviar a un amigo 
//*****************************
function LocatedByExtent(Extent)
{
   $(document).ready(function(){

		var fMap =document.getElementById("Map").contentWindow.document.getElementById("ImageDiv");	
		
		//capturamos el extent
		var extent = GetUrlParams('extent');
	
		RelocateObject("ReferenceDiv", REF_LEFT, REF_TOP);	

		var urlajax = "Search/AjaxLocatedByExtent.php";
		var dataajax = "extent="+extent+"&width="+width+"&height="+height;
		
		$.ajax({
			type: "GET",
			url: urlajax,
			data: dataajax,
			dataType: "html",
			cache: false,
			success: function(XMLhtml){

				fMap.innerHTML = XMLhtml;
			
				getReferenceImage("Load/AjaxReferenceImage.php");
				
				$("#btnAjaxSearch").attr("disabled", false);
				$("#txtName").attr("disabled", false);		
					
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				var htmlError = "<p class='titulo2verde11' align='left'>Ha ocurrido un error...</p>";
				fMap.innerHTML = htmlError; 
			}
		})

	});
}


/***************************************************************************
 * ReferenceUbication
 * Procedimiento que centra el mapa en un punto desde la referencia
 ****************************************************************************/
function ReferenceUbication(x,y)
{
	// Asigno a la bandera 0 para que deje de dibujar la linea continuamente y pueda volver a realizar ruler
	parent.document.op_map.OneLine.value = 0;						
	
	ajaxLoadImage('LocationControls/AjaxReferenceClick.php','mapa_x='+ x + '&mapa_y=' + y,'ImageDiv',true);
}	

/*************************************************************************
ClickReference
Procedimiento que al pulsar la referencia, actualiza la ubicación en el mapa
***************************************************************************/
function ClickReference(evt)
{
	
	if($("#RulerInfo").css("visibility")=="visible"){
		CleanDiv("#RulerInfo");
		ExecuteFile("Load/AjaxCleanDistanceValue.php","");
	}
	//Limpiamos el resultado del info si el usuario realizo el evento info
	if($("#divInfo").css("visibility")=="visible"){
		CleanDiv("#divInfo");
	}
	//Obtengo la posicion de la etiqueta que envuelve la imagen de la refencia para poder calcular la posicion en pixel al darle click sobre la imagen, debido a que dependiendo de la resolucion, esto varia.
	var left = document.getElementById("ReferenceDiv").offsetLeft + 2;//18
	var top = document.getElementById("ReferenceDiv").offsetTop + 2;//8

	var x = evt.clientX - left; 

	var TopPosScroll = $(document).scrollTop();
	var y2 = evt.clientY + TopPosScroll; // Se suma la posicion del scroll, ya que si se mueve, el pixel del objeto tambien cambia de posicion
	var y = y2  - top ;

	ReferenceUbication(x,y);
}