// JavaScript Document
var VartxtCity; //Variable que contiene el texto que muestra el sistema en el txt 
				//de serach si el usuario no escribio nada para buscar pero si en el txt de ciudad


function Search(pagina){
	
	//$(function(){clearAutoComplete();});
	//document.getElementById('btnAjaxSearch').focus();
	
	if(!pagina)//Por una extraña razon, el valor pagina mandado desde control, a veces lo manda como indefinido, cuando en control se le manda a search: seach(1)
	{
		pagina = 1;
	}

	var txtName = $('#txtName').attr("value");
	var txtCity = $('#txtCity').attr("value");
	var Option = $('#cmbSearchType').attr("value");
	txtNameDeseaBuscar = decodeURIComponent(txtName); //Se usa para solamente validar que no sea "¿Qué desea buscar" y se usa otra 

	txtCity = txtCity.replace(/(^\s*)|(\s*$)/g,""); 

	//Extraeré solamente el "Que desea buscar"
	//Posicion del caracter "r"
	var txtNameDecodePositionEnd = txtNameDeseaBuscar.indexOf("r");

	txtNameDecodePositionEnd =  txtNameDecodePositionEnd + 1;

	//Extraigo el string "Que desea buscar"
	txtNameDeseaBuscar = txtNameDeseaBuscar.slice(0, txtNameDecodePositionEnd);

	if (txtName != "" && txtNameDeseaBuscar !="&iquest;Qu&eacute;a desea buscar" && txtNameDeseaBuscar.match("desea buscar")==null && txtName != null && txtName.length >= 3)
	{
		
		//L0TJ(0,0);
		ViewResults();
		
		txtName = encodeURIComponent(txtName);//Se codifican a utf8 debido a que ajax manda los datos en este formato
		txtCity = encodeURIComponent(txtCity);
		
		var Limit = 100; //$("#cmbLimit").attr("value");
		var State = $('#cmbState').attr("value");
		var Municipality = $('#cmbMunicipality').attr("value");
		var Parish = $('#cmbParish').attr("value");
		
		//En caso de ser valores indefinidos
		if (!State>0) State=-1;
		if (!Municipality>0) Municipality=-1;
		if (!Parish>0) Parish=-1;	
		
		
		var sParams="cmbState="+State+"&cmbMunicipality="+Municipality+"&cmbParish="+Parish+"&txtName="+txtName+"&rbtnSearch="+Option+"&CityName="+txtCity+"&LayerId="+Option+"&Limit="+Limit+"&pagina="+pagina+"&SectorId=-1";
	
/*		if ($("#SearchType_0").attr("checked")) {
			getDataSearch("Search/AjaxSearch.php", sParams, "Result", true);
			
		}
		//TIPO DE BUSQUEDA DICCIONARIO
		else {*/
			getDataSearch("Search/AjaxSearchDictionary.php", sParams, "Result", true);
			
		//}
							  
	}else
	{
		if(trim(txtName) != "" && txtName != null && txtNameDeseaBuscar !="&iquest;Qu&eacute;a desea buscar" && txtNameDeseaBuscar.match("desea buscar")==null)//txtName.length < 3 && 
		{
			alert("Lo que desea buscar tiene que ser mayor a 2 letras");
		}else
		{
			//Quiere decir que txtName es vacio o null, osea el usuario no ha escrito nada para buscar.
			if(txtCity != "")//True: quiere decir que el usuario ha escrito algo en ciudad pero no en lo que desea buscar.
			{
				
				var text = String.fromCharCode(191)+"Qu"+String.fromCharCode(233)+"  desea buscar en la ciudad " + 	txtCity + "?" ;
				$('#txtName').attr("value", text);
				$('#txtName').attr("className", "txt10rojo2");
				
				VartxtCity = $('#txtName').attr("value") ;
				
			}else
			{
				//El usuario no ha escrito nada para buscar
				$('#txtName').attr("value", String.fromCharCode(191)+"Qu"+String.fromCharCode(233)+" desea buscar?");
				$('#txtName').attr("className", "txt10rojo2");
			}
		}	
	}	
}

function EventEnter(evt){
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57 
	var key; 
	
	if(window.event) // IE
	{
		key = evt.keyCode;
	}
	else if(evt.which) // Netscape/Firefox/Opera
	{
		key = evt.which;
	}

	
	if (key == 13){
		Search(1);
		return false;
	}
	return true;
}


function OnlyLetterS(evt, string){
	//Mayusculas 65-90
	//Minusculas 97-122
	// 209,  241
	//Enter 13
	//Punto 46
	// # (key == 35 && string.indexOf(char)==-1) || 
	var key; 
	var value= true;
	var char; 
	
	if(window.event) // IE
	{
		key = evt.keyCode;
	}
	else if(evt.which) // Netscape/Firefox/Opera
	{
		key = evt.which;
	}
	char = String.fromCharCode(key);

	if (key){
		if (key == 13){
			Search(1);
			value= false;
		}	
		else if (!(key <= 32  || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122)|| (key == 241 || key == 209 || key == 46) ||  (key == 45 && string.indexOf(char)==-1) || (key == 35 && string.indexOf(char)==-1) ) ){
			 value= false;
		}
	}
	
	return value;

}
 function noCopyKey(e) {

	var forbiddenKeys = new Array('c','x','v');
	var keyCode = (e.keyCode) ? e.keyCode : e.which;
	var isCtrl;

	if(window.event)
		isCtrl = e.ctrlKey;
	else
		isCtrl = (window.event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;

	if(isCtrl) {
		for(i = 0; i < forbiddenKeys.length; i++) {
			if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
				return false; 
			}
		}
	}
	return true;
} 

function trim(string)
{
	for(i=0; i<string.length; )
	{
		if(string.charAt(i)==" ")
			string=string.substring(i+1, string.length);
		else
			break;
	}

	for(i=string.length-1; i>=0; i=string.length-1)
	{
		if(string.charAt(i)==" ")
			string=string.substring(0,i);
		else
			break;
	}
	return string;
}

//Search paginacion
function SearchPag(pagina,NewString,StateID,MunicipalityID,ParishID,CityID,SectorID,LayerID){
	
	if(!pagina)//Por una extraña razon, el valor pagina mandado desde control, a veces lo manda como indefinido, cuando en control se le manda a search: seach(1)
	{
		pagina = 1;
	}

	//L0TJ(0,0);
	ViewResults();

	var sParams="cmbState="+StateID+"&cmbMunicipality="+MunicipalityID+"&cmbParish="+ParishID+"&txtName="+NewString+"&rbtnSearch="+LayerID+"&CityID="+CityID+"&LayerId="+LayerID+"&pagina="+pagina;

	//getData("Result","AjaxSearchPag.php"+sParams+"&pagina="+pagina);
	getDataSearch("Search/AjaxSearchPag.php", sParams, "Result", true);
	
}

//Search paginacion
function SearchPagDict(pagina, NewString, StateID, MunicipalityID, ParishID, CityID, SectorID, LayerID, All, Some, Without, nResults){

	if(!pagina)//Por una extraña razon, el valor pagina mandado desde control, a veces lo manda como indefinido, cuando en control se le manda a search: seach(1)
	{
		pagina = 1;
	}

	//L0TJ(0,0);
	ViewResults();
	
	NewString = encodeURIComponent(NewString);

	//NewString = decodeURIComponent(NewString);
	//alert(NewString);
	var sParams="cmbState="+StateID+"&cmbMunicipality="+MunicipalityID+"&cmbParish="+ParishID+"&txtName="+NewString+"&rbtnSearch="+LayerID+"&CityID="+CityID+"&LayerId="+LayerID+"&Limit="+nResults+"&All="+All+"&Some="+Some+"&Without="+Without+"&nResults="+nResults+"&pagina="+pagina;
	

	//getData("Result","AjaxSearchPagDict.php"+sParams+"&pagina="+pagina);
	getDataSearch("Search/AjaxSearchPagDict.php", sParams, "Result", true);
	
}

//Search paginacion
function SearchPagDictInt(pagina, NewString, StateID, MunicipalityID, ParishID, CityID, SectorID, LayerID, All, Some, Without, nResults){

	
	if(!pagina)//Por una extraña razon, el valor pagina mandado desde control, a veces lo manda como indefinido, cuando en control se le manda a search: seach(1)
	{
		pagina = 1;
	}

	//L0TJ(0,0);
	ViewResults();

	var sParams="cmbState="+StateID+"&cmbMunicipality="+MunicipalityID+"&cmbParish="+ParishID+"&txtName="+NewString+"&rbtnSearch="+LayerID+"&CityID="+CityID+"&LayerId="+LayerID+"&Limit="+nResults+"&All="+All+"&Some="+Some+"&Without="+Without+"&nResults="+nResults+"&pagina="+pagina;
	
	getDataSearch("Search/AjaxSearchPagDictInt.php", sParams, "Result", true);
	
}


function getDataSearch(urlajax,dataajax,div,iframe){

	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		beforeSend: function(XMLhtml){

			var htmlWait = "<p class='titulo2verde11' align='left'><img src='../../Images/Map/Loading/InfoLoading.gif'/> Buscando, por favor espere...</p>";
						
			var objFrame = $("#Resultados").contents().find('iframe');
			
			var objDivFrame = objFrame.contents().find('div');

			objDivFrame.html(htmlWait);
				
		},
		success: function(XMLhtml){
		
			if (XMLhtml != "SessionRefresh")
			{	
				var objFrame = $("#Resultados").contents().find('iframe');
		
				var objDivFrame = objFrame.contents().find('div');

				objDivFrame.html(XMLhtml);
		
			}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>";
			
			var objFrame = $("#Resultados").contents().find('iframe');
			
			var objDivFrame = objFrame.contents().find('div');

			objDivFrame.html(htmlError);
		}
	})
}



//Funcion que limpia el txt de la búsqueda
function CleanSearchTxt()
{
	var txtName = $('#txtName').attr("value");
//	if((txtName == "¿Qué desea buscar?")||(txtName == VartxtCity))
//	{
		//Limpio el txt
		$('#txtName').attr("value", "");
		//Asigno la clase del estilo al txt
		$("#txtName").attr("className", "texto10gris2");
//	}
}


function SearchAdvanceDictionary(Allwords,Somewords,Withoutwords, LayerId, StateId, MunicipalityId, ParishId, CityId, SectorId, nPage, nResults){
	$("#txtName").attr("value", "");
	$("#txtCity").attr("value", "");
	$("#cmbLimit").attr("value", 100);
	$("#cmbSearchType").attr("value", 0);
	
	if(!nPage)//Por una extraña razon, el valor pagina mandado desde control, a veces lo manda como indefinido, cuando en control se le manda a search: seach(1)
	{
		nPage = 1;
	}

	Allwords = Allwords.replace(/(^\s*)|(\s*$)/g,"");
	Somewords = Somewords.replace(/(^\s*)|(\s*$)/g,"");
	Withoutwords = Withoutwords.replace(/(^\s*)|(\s*$)/g,"");
	
	if ((Allwords != "" && Allwords != null)||(Somewords != "" && Somewords != null)||(Withoutwords != "" && Withoutwords != null))
	{
		//L0TJ(0,0);
		ViewResults();
		
		if (LayerId == 0 || LayerId == null){
			LayerId = -1;
		}
		if (StateId == 0 || StateId == null){
			StateId = -1;
		}
		if (MunicipalityId == 0 || MunicipalityId == null){
			MuniciaplityId = -1;
		}
		if (ParishId == 0 || ParishId == null){
			ParishId = -1;
		}
		if (SectorId == 0 || SectorId == null){
			SectorId = -1;
		}
		if (CityId == 0 || CityId == null){
			CityId = -1;
		}
		
		Allwords  = encodeURIComponent(Allwords);//Se codifican a utf8 debido a que ajax manda los datos en este formato
		Somewords  = encodeURIComponent(Somewords);//Se codifican a utf8 debido a que ajax manda los datos en este formato
		Withoutwords  = encodeURIComponent(Withoutwords);//Se codifican a utf8 debido a que ajax manda los datos en este formato

		
		var sParams="cmbState="+StateId+"&cmbMunicipality="+MunicipalityId+"&cmbParish="+ParishId+"&cmbCity="+CityId+"&cmbSector="+SectorId+"&LayerId="+LayerId+"&All="+Allwords+"&Some="+Somewords+"&Without="+Withoutwords+"&nResults="+nResults+"&nPage="+nPage;
		getDataSearch("Search/AjaxSearchAdvanceDict.php", sParams, "Result", true);		
	}	
}

function SearchAdvanceDictionary_Int(txtSearch, LayerId, StateId, MunicipalityId, ParishId, CityId, SectorId, nPage, nResults){
	$("#txtName").attr("value", "");
	$("#txtCity").attr("value", "");
	$("#cmbLimit").attr("value", 100);
	$("#cmbSearchType").attr("value", 0);
	
	if(!nPage)//Por una extraña razon, el valor pagina mandado desde control, a veces lo manda como indefinido, cuando en control se le manda a search: seach(1)
	{
		nPage = 1;
	}

	txtSearch = txtSearch.replace(/(^\s*)|(\s*$)/g,"");
	
	if (txtSearch != "" && txtSearch != null)
	{
		//L0TJ(0,0);
		ViewResults();
		
		if (LayerId == 0 || LayerId == null){
			LayerId = -1;
		}
		if (StateId == 0 || StateId == null){
			StateId = -1;
		}
		if (MunicipalityId == 0 || MunicipalityId == null){
			MuniciaplityId = -1;
		}
		if (ParishId == 0 || ParishId == null){
			ParishId = -1;
		}
		if (SectorId == 0 || SectorId == null){
			SectorId = -1;
		}
		if (CityId == 0 || CityId == null){
			CityId = -1;
		}
		
		txtSearch  = encodeURIComponent(txtSearch);//Se codifican a utf8 debido a que ajax manda los datos en este formato
		
		var sParams="?cmbState="+StateId+"&cmbMunicipality="+MunicipalityId+"&cmbParish="+ParishId+"&cmbCity="+CityId+"&cmbSector="+SectorId+"&LayerId="+LayerId+"&Intersection="+txtSearch+"&nResults="+nResults+"&nPage="+nPage;
		
		
		getDataSearch("Search/AjaxSearchAdvanceDict.php", sParams, "Result", true);		
	}	
}

/******************CODIGO REALIZADO POR RESULTS:PHP **************************************/
var CursorType = "default";

/***************************************************************************
 * SetLocationAd
 * Procedimiento ubica el mapa en un x, y, z al realizar una busqueda en direcciones
 ****************************************************************************/
function SetLocationAd(Long,Latit,Zoom,Linfo,State,City){


	//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(window.parent.document.getElementById("RulerInfo").style.visibility == "visible" || window.parent.document.getElementById("divInfo").style.visibility == "visible")
	{
		window.parent.CleanDiv("#RulerInfo");
	}


	//Evaluamos si esta en una ciudad o no
	
	if(City.toUpperCase() == "SIN CIUDAD")
	{
		Zoom = 100000;
	}
	
	//Como se pulso algun resultado del buscador apra ubicar al usuario en el mapa, hay que esconder la tabla de resultados
	StyleTabResult = "0";//hidden

	
	parent.ajaxLoadImage("Search/AjaxViewSearch.php", "dblLati=" + Latit + "&dblLong=" + Long +"&dblZoom=" + Zoom + "&State="+State + "&Linfo="+Linfo + "&City="+City, "ImageDiv", true);
}

/***************************************************************************
 * SetLocationPo
 * Procedimiento ubica el mapa en un x, y, z al realizar una busqueda en poblaciones
 ****************************************************************************/
function SetLocationPo(Long,Latit,Zoom,Po){

//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(window.parent.document.getElementById("RulerInfo").style.visibility == "visible" || document.getElementById("divInfo").style.visibility == "visible")
	{
		parent.CleanDiv("#RulerInfo");
	}



	//Como se pulso algun resultado del buscador apra ubicar al usuario en el mapa, hay que esconder la tabla de resultados
	StyleTabResult = "0";//hidden
	parent.ajaxLoadImage("Search/AjaxViewSearch.php", "dblLati=" + Latit + "&dblLong=" + Long +"&dblZoom=" + Zoom + "&Po="+Po, "ImageDiv", true);
}


/***************************************************************************
 * SetLocationSe
 * Procedimiento ubica el mapa en un x, y, z al realizar una busqueda en sectores
 ****************************************************************************/
function SetLocationSe(Long,Latit,Zoom,City,Se){

//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(window.parent.document.getElementById("RulerInfo").style.visibility == "visible" || window.parent.document.getElementById("divInfo").style.visibility == "visible")
	{
		window.parent.CleanDiv("#RulerInfo");
	}


	parent.ajaxLoadImage("Search/AjaxViewSearch.php", "dblLati=" + Latit + "&dblLong=" + Long +"&dblZoom=" + Zoom + "&City="+City + "&Se=" + Se, "ImageDiv", true);
	
}


/***************************************************************************
 * SetLocationMuni
 * Procedimiento ubica el mapa en un x, y, z al realizar una busqueda en municipios
 ****************************************************************************/
function SetLocationMuni(Long,Latit,Width, Height){

//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(window.parent.document.getElementById("RulerInfo").style.visibility == "visible" || window.parent.document.getElementById("divInfo").style.visibility == "visible")
	{
		window.parent.CleanDiv("#RulerInfo");
	}


	parent.ajaxLoadImage("Search/AjaxViewSearch.php", "Latit=" + Latit + "&Long=" + Long +"&Width=" + Width + "&Height=" + Height, "ImageDiv", true);
	
}

