// 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 SearchAdvance(StrAddress, LayerId, StateId, MunicipalityId, ParishId, CityId, SectorId, nPage){
	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;
	}

	StrAddress = StrAddress.replace(/(^\s*)|(\s*$)/g,""); 
	
	if (StrAddress != "" && StrAddress != null)
	{
		L0TJ(0,0);
		
		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;
		}
		
		gStrAddress = StrAddress;
		
		StrAddress = encodeURIComponent(StrAddress);//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+"&txtName="+StrAddress+"&LayerId="+LayerId+"&nPage="+nPage;
				
		//getDataAdvance("Result","Search/AjaxSearchAdvance.php"+sParams);
		getDataAdvance("Search/AjaxSearchAdvance.php", sParams, "Result", true);	
		
	}	
}

function SearchRefAdvance(StrAddress, DescTypeId, DescSubTypeId, StateId, MunicipalityId, ParishId, CityId, SectorId, nPage, LayerId){
	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;
	}

	StrAddress = StrAddress.replace(/(^\s*)|(\s*$)/g,""); 
	
	if (StrAddress != "" && StrAddress != null)
	{
		L0TJ(0,0);
		
		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;
		}
		if (DescTypeId == 0 || DescTypeId == null){
			DescTypeId = -1;
		}
		if (DescSubTypeId == 0 || DescSubTypeId == null){
			DescSubTypeId = -1;
		}
		gStrAddress = StrAddress;
		
		StrAddress = encodeURIComponent(StrAddress);//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+"&txtName="+StrAddress+"&DescSubTypeID="+DescSubTypeId+"&DescTypeID="+DescTypeId+"&LayerId="+LayerId+"&nPage="+nPage;
		
		
		getDataAdvance("Search/AjaxSearchAdvance.php", sParams, "Result", true);		
	}	
}


/***************************************************************************
 * getDataAdvance
 * Procedimiento que obtiene los datos devueltos de una busqueda avanzada
 ****************************************************************************/
 function getDataAdvance(urlajax,dataajax,div,iframe){
	 //document.op_map.OneLine.value = 0;
	
	$.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 index = 0;
			var noDiv = true;
			while(noDiv == true){ //Mientras no encuentre la etiqueta div con el id del parametro 'div'

				var objDiv = $("#Resultados").contents().find("div").eq(index);// seleccionamos el div con indice index

				if(objDiv.attr("id") == div){// el div seleccionado es igual al que se desea realizar ajax?
					noDiv = false; // indicamos que se debe de salir del wuile
					objDiv.html(htmlWait); // asignamos la imagen al div
				}else{
						index = index + 1;	// avanzamos al siguiente div
				}	
			}
		},
		success: function(XMLhtml){
			if(iframe){//TRUE: si se desea cargar los datos llamando la funcion fuera del iframe
				var index = 0;
				var noDiv = true;
				while(noDiv == true){ //Mientras no encuentre la etiqueta div con el id del parametro 'div'
				
					var objDiv = $("#Resultados").contents().find("div").eq(index);// seleccionamos el div con indice index
					
					if(objDiv.attr("id") == div){// el div seleccionado es igual al que se desea realizar ajax?
						noDiv = false; // indicamos que se debe de salir del wuile
						
						if (XMLhtml != "SessionRefresh")
						{
							objDiv.html(XMLhtml);
						}else {
							window.open('CloseIngeoMaps.php','_parent','','true');
						}
						
					}else{
						index = index + 1;	// avanzamos al siguiente div
					}
					
				}
			}
			else{//FALSE: Si se desea cargar los datos llamando la funcion dentro del iframe
				$(div).html(XMLhtml);
			}
			
		},
		error: function(XMLhtml, textStatus, errorThrown){
			var htmlError = "<p class='titulo2verde11' align='left'>No se pudo realizar la busqueda...</p>";
			
			var index = 0;
			var noDiv = true;
			while(noDiv == true){ //Mientras no encuentre la etiqueta div con el id del parametro 'div'

				var objDiv = $("#Resultados").contents().find("div").eq(index);// seleccionamos el div con indice index

				if(objDiv.attr("id") == div){// el div seleccionado es igual al que se desea realizar ajax?
					noDiv = false; // indicamos que se debe de salir del wuile
					objDiv.html(htmlError); // asignamos la imagen al div
				}else{
						index = index + 1;	// avanzamos al siguiente div
				}	
			}
			
		}
		
	})
}

function SearchByLL(Long,Latit,op){
	//getDataImage("Search/AjaxViewSearch.php", "dblLati=" + Latit + "&dblLong=" + Long +"&dblZoom=" +100 +"&op=" + op, "ImageDiv", true);
	var long;
	var lat;
	
	if(op==2){ //GRADOS/MIN/SEG
		arrayLong = Long.split("/");
		arrayLati = Latit.split("/");
				
		//Valores de la longitud
		LongGrados = parseFloat(arrayLong[0]);
		LongMinutos = parseFloat(arrayLong[1]);
		LongSegundos = parseFloat(arrayLong[2]);
				
		//Valores de la latitud
		LatiGrados = parseFloat(arrayLati[0]);
		LatiMinutos = parseFloat(arrayLati[1]);
		LatiSegundos = parseFloat(arrayLati[2]);
				
		//Calculos
		//alert(LongGrados+', '+LongMinutos+', '+LongSegundos);
		//alert(LatiGrados+', '+LatiMinutos+', '+LatiSegundos);
		
		long = LongSegundos/60;
		long = long + LongMinutos;
		long = long/60;
		long = long + LongGrados;
		long = long * (-1);
		
		lat = LatiSegundos/60 ;
		lat = lat + LatiMinutos;
		lat = lat/60;
		lat = lat + LatiGrados;
		
		
		//long = -1*( ( ( ( LongSegundos/60 ) + LongMinutos )/60 ) + LongGrados);
		//lat = ( ( ( ( LatiSegundos/60 ) + LatiMinutos )/60 ) + LatiGrados);
	}
	else{ //DECIMALES
		long =  parseFloat(Long);
		lat =  parseFloat(Latit);
	}
	
	var img = document.createElement( 'img' );
	img.src = '../Images/Map/Symbols/SearchPoint.gif';
	img.height = img.width = 27;
	myKaMap.addObjectGeo( canvas, long, lat, img );
	myKaMap.zoomToExtents((long),(lat),(long),(lat));
	
		//setPointLocation(Long,Latit,name,state,city,municipality,parish,zoom,DivO_D)
}


/***************************************************************************
 * getDataImage
 * Procedimiento que obtiene la imagen del mapa
 ****************************************************************************/
 function getDataImage(urlajax,dataajax,div,iframe){
	
	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		beforeSend: function(XMLhtml){
							
			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'><img src='../Images/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>";
			
			var index = 0;
			var noDiv = true;
			while(noDiv == true){ //Mientras no encuentre la etiqueta div con el id del parametro 'div'

				var objDiv = parent.$("#Map").contents().find("div").eq(index);// seleccionamos el div con indice index

				if(objDiv.attr("id") == div){// el div seleccionado es igual al que se desea realizar ajax?
					noDiv = false; // indicamos que se debe de salir del wuile
					objDiv.html(htmlWait); // asignamos la imagen al div
				}else{
						index = index + 1;	// avanzamos al siguiente div
				}	
			}
		},
		success: function(XMLhtml){
			if(iframe){//TRUE: si se desea cargar los datos llamando la funcion fuera del iframe
				var index = 0;
				var noDiv = true;
				while(noDiv == true){ //Mientras no encuentre la etiqueta div con el id del parametro 'div'
				
					var objDiv = parent.$("#Map").contents().find("div").eq(index);// seleccionamos el div con indice index
					
					if(objDiv.attr("id") == div){// el div seleccionado es igual al que se desea realizar ajax?
						noDiv = false; // indicamos que se debe de salir del wuile
						
						if (XMLhtml != "SessionRefresh")
						{
							objDiv.html(XMLhtml);
						}else {
							window.open('CloseIngeoMaps.php','_parent','','true');
						}
						
					}else{
						index = index + 1;	// avanzamos al siguiente div
					}
					
				}
			}
			else{//FALSE: Si se desea cargar los datos llamando la funcion dentro del iframe
				$(div).html(XMLhtml);
			}
			
		},
		error: function(XMLhtml, textStatus, errorThrown){
			var htmlError = "<p class='tituloverde16' align='left'> Ha ocurrido un error...</p>";
			
			var index = 0;
			var noDiv = true;
			while(noDiv == true){ //Mientras no encuentre la etiqueta div con el id del parametro 'div'

				var objDiv = parent.$("#Map").contents().find("div").eq(index);// seleccionamos el div con indice index

				if(objDiv.attr("id") == div){// el div seleccionado es igual al que se desea realizar ajax?
					noDiv = false; // indicamos que se debe de salir del wuile
					objDiv.html(htmlError); // asignamos la imagen al div
				}else{
						index = index + 1;	// avanzamos al siguiente div
				}	
			}
			
		}
		
	})
}



/******************************************** USADO EN ADVANCESEARCH (POPUP)******************************************/
/*********************************************************************************************************************/

var StringAddress = "";
var StringAddressB = "";
var StringAddressSector= "";
var StringReference= "";
var LayerId_Sector = 4;
var LayerId_Building = 5;
var LayerId_Viality = 7;
var LayerId_Reference = 3;



function Validate(){

	var desc1 = $('#cmbDesc1').attr("value");
	var address1 = $('#txtAdd1').attr("value");
	var desc2 = $('#cmbDesc2').attr("value");
	var address2 = $('#txtAdd2').attr("value");

	address1 = address1.replace(/$/g,""); 
	address1 = address1.replace(/!/g,""); 
	address1 = address1.replace(/\|/g,""); 
	address1 = address1.replace(/&/g,""); 
	address1 = address1.replace(/%/g,""); 
	address1 = address1.replace(/\(/g,""); 
	address1 = address1.replace(/\)/g,"");
	
	address2 = address2.replace(/$/g,""); 
	address2 = address2.replace(/!/g,""); 
	address2 = address2.replace(/\|/g,""); 
	address2 = address2.replace(/&/g,""); 
	address2 = address2.replace(/%/g,""); 
	address2 = address2.replace(/\(/g,""); 
	address2 = address2.replace(/\)/g,"");
	

	if (address1 == "" && desc1 != 0){
		alert('Debe colocar el nombre de la vialidad principal');
	}
	else if (address2 == "" && desc2 != 0){
		alert('Debe colocar el nombre de la vialidad secundaria');
	}
	else if (address2 != "" && desc2 == 0){
		alert('Debe colocar el tipo de la vialidad secundaria');
	}
	else if((address1 == "" || desc1 == 0) && (address2 != "" || desc2 != 0)){
		alert('Debe colocar la vialidad principal');
	}
	else{
		
		StateId = $("#cmbState").attr("value");
		MunicipalityId = $("#cmbMunicipality").attr("value");
		ParishId = $("#cmbParish").attr("value");
		CityId = $("#cmbCity").attr("value");
		SectorId = $("#cmbSector").attr("value");
		
		if(desc1 == 0){
			desc1 = -1;
		}
		if(desc2 == 0){
			desc2 = -1;
		}
		
		StrAddress = desc1 +' , '+address1+' , '+desc2+' , '+address2;
		
		window.opener.SearchAdvance(StrAddress, LayerId_Viality, StateId, MunicipalityId, ParishId, CityId, SectorId, 1);
		
		window.opener.focus();
	}
}

function ValidateB(){
	var desc1 = $('#cmbDesc1B').attr("value");
	var address1 = $('#txtAdd1B').attr("value");

	address1 = address1.replace(/$/g,""); 
	address1 = address1.replace(/!/g,""); 
	address1 = address1.replace(/\|/g,""); 
	address1 = address1.replace(/&/g,""); 
	address1 = address1.replace(/%/g,""); 
	address1 = address1.replace(/\(/g,""); 
	address1 = address1.replace(/\)/g,"");
	
	if (address1 == "" && desc1 != 0){
		alert('Debe colocar el nombre del inmueble');
	}
	else{
		
		StateId = $("#cmbState").attr("value");
		MunicipalityId = $("#cmbMunicipality").attr("value");
		ParishId = $("#cmbParish").attr("value");
		CityId = $("#cmbCity").attr("value");
		SectorId = $("#cmbSector").attr("value");
		
		if(desc1 == 0){
			desc1 = -1;
		}
		
		StrAddress = desc1 +' , '+address1;
		window.opener.SearchAdvance(StrAddress, LayerId_Building, StateId, MunicipalityId, ParishId, CityId, SectorId, 1);
		window.opener.focus();
	}
}

function ValidateSector(){

	var address1 = $('#txtSector').attr("value");
	address1 = address1.replace(/$/g,""); 
	address1 = address1.replace(/!/g,""); 
	address1 = address1.replace(/\|/g,""); 
	address1 = address1.replace(/&/g,""); 
	address1 = address1.replace(/%/g,""); 
	address1 = address1.replace(/\(/g,""); 
	address1 = address1.replace(/\)/g,"");
	
	if (address1 == ""){
		alert('Debe colocar el nombre del sector');
	}
	else{
		
		StateId = $("#cmbState").attr("value");
		MunicipalityId = $("#cmbMunicipality").attr("value");
		ParishId = $("#cmbParish").attr("value");
		CityId = $("#cmbCity").attr("value");
		SectorId = $("#cmbSector").attr("value");
		
		StrAddress = address1;
		
		window.opener.SearchAdvance(StrAddress, LayerId_Sector, StateId, MunicipalityId, ParishId, CityId, -1, 1);

	window.opener.focus();
	}
}

function ValidateReference(){

	var desc1 = $('#cmbRef1').attr("value");
	var desc2 = $('#cmbRef2').attr("value");
	var address1 = $('#txtRef').attr("value");
	address1 = address1.replace(/$/g,""); 
	address1 = address1.replace(/!/g,""); 
	address1 = address1.replace(/\|/g,""); 
	address1 = address1.replace(/&/g,""); 
	address1 = address1.replace(/%/g,""); 
	address1 = address1.replace(/\(/g,""); 
	address1 = address1.replace(/\)/g,"");
	
	if (address1 == ""){
		alert('Debe colocar el nombre del punto de referencia');
	}
	else{
		StateId = $("#cmbState").attr("value");
		MunicipalityId = $("#cmbMunicipality").attr("value");
		ParishId = $("#cmbParish").attr("value");
		CityId = $("#cmbCity").attr("value");
		SectorId = $("#cmbSector").attr("value");

		if (desc1 == 0){
			desc1 = -1;
			desc2 =-1;
			
		}
		window.opener.SearchRefAdvance(address1, desc1, desc2, StateId, MunicipalityId, ParishId, CityId, SectorId, 1, LayerId_Reference);

	window.opener.focus();
	}
}

function ShowString(){
	
	var div = "StringDiv";
	var desc1 = $('#cmbDesc1').attr("value");
	var add1 = encodeURIComponent($('#txtAdd1').attr("value"));
	var desc2 = $('#cmbDesc2').attr("value");
	var add2 =  encodeURIComponent($('#txtAdd2').attr("value"));
	
	add1 = add1.replace(/$/g,""); 
	add1 = add1.replace(/!/g,""); 
	add1 = add1.replace(/\|/g,""); 
	add1 = add1.replace(/&/g,""); 
	add1 = add1.replace(/%/g,""); 
	add1 = add1.replace(/\(/g,""); 
	add1 = add1.replace(/\)/g,"");
	
	add2 = add2.replace(/$/g,""); 
	add2 = add2.replace(/!/g,""); 
	add2 = add2.replace(/\|/g,""); 
	add2 = add2.replace(/&/g,""); 
	add2 = add2.replace(/%/g,""); 
	add2 = add2.replace(/\(/g,""); 
	add2 = add2.replace(/\)/g,"");
	
	urlajax= "AjaxGetDescName.php";
	dataajax = "descID="+desc1+"&descID2="+desc2+"&add1="+add1+"&add2="+add2;	
		
	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		success: function(XMLhtml){
			if (XMLhtml != ''){
				$('#'+div).html("Usted desea buscar: '" + XMLhtml + "'");
			}
			else{
				$('#'+div).html("");
			}

			$("#cmbDesc1B").attr("value",0);
			$("#txtAdd1B").attr("value","");
			$("#cmbRef1").attr("value",0);
			$("#cmbRef2").attr("value",0);
			$("#txtRef").attr("value","");
			$("#txtSector").attr("value","");
		},
		error: function(XMLhtml, textStatus, errorThrown){
			$('#'+div).html("");
			
		}
	})
}
	

function ShowStringB(){

	var div = "StringDiv";
	var desc1 = $('#cmbDesc1B').attr("value");
	var add1 = encodeURIComponent($('#txtAdd1B').attr("value"));
	
	urlajax= "AjaxGetDescNameBuilding.php";
	dataajax = "descID="+desc1+"&add1="+add1;	
	
	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		success: function(XMLhtml){
			if (XMLhtml != ''){
				$('#'+div).html("Usted desea buscar: '" + XMLhtml + "'");
			}
			else{
				$('#'+div).html("");
			}

			$("#cmbDesc1").attr("value",0);
			$("#txtAdd1").attr("value","");
			$("#cmbDesc2").attr("value",0);
			$("#txtAdd2").attr("value","");
			$("#txtSector").attr("value","");
		},
		error: function(XMLhtml, textStatus, errorThrown){
			$('#'+div).html("");
			
		}
	})
}

function ShowStringSec(){

	var div = $("#StringDiv");
	var add1 = $('#txtSector').attr("value");
		
	div.html("Usted desea buscar: '" + add1 + "'");
	StringAddressSector = add1;
	$("#cmbDesc1").attr("value",0);
	$("#txtAdd1").attr("value","");
	$("#cmbDesc2").attr("value",0);
	$("#txtAdd2").attr("value","");
	$("#cmbDesc1B").attr("value",0);
	$("#txtAdd1B").attr("value","");
	$("#cmbRef1").attr("value",0);
	$("#cmbRef2").attr("value",0);
	$("#txtRef").attr("value","");

	if (add1 != ''){
		$("#cmbSector").attr("value",0);
		$("#cmbSector").attr("disabled", true);
	}
}

function ShowStringRef(){

	var div = "StringDiv";
	var desc1 = $('#cmbRef2').attr("value");
	var add1 = encodeURIComponent($('#txtRef').attr("value"));
	
	urlajax= "AjaxGetDescNameReference.php";
	dataajax = "descID="+desc1+"&add1="+add1;	
	
	$.ajax({
		type: "GET",
		url: urlajax,
		data: dataajax,
		dataType: "html",
		cache: false,
		success: function(XMLhtml){
			if (XMLhtml != ''){
				$('#'+div).html("Usted desea buscar: '" + XMLhtml + "'");
			}
			else{
				$('#'+div).html("");
			}

			$("#cmbDesc1").attr("value",0);
			$("#txtAdd1").attr("value","");
			$("#cmbDesc2").attr("value",0);
			$("#txtAdd2").attr("value","");
			$("#cmbDesc1B").attr("value",0);
			$("#txtAdd1B").attr("value","");
			$("#cmbSector").attr("value",0);
			$("#txtSector").attr("value","");
		},
		error: function(XMLhtml, textStatus, errorThrown){
			$('#'+div).html("");
			
		}
	})
}

function OnlyLetter(evt, string){
	//Mayusculas 65-90
	//Minusculas 97-122
	// 209,  241
	//Enter 13
	// # (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 == 13){
		Validate();
		value= false;
	}	
	else if (!(key <= 32  || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122)|| (key == 241 || key == 209) || 
				 (key == 45 && 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()) {
				//alert('copy/paste');
				return false;
			}
		}
	}
	return true;
}

function OnlyLetterB(evt, string){
	//Mayusculas 65-90
	//Minusculas 97-122
	// 209,  241
	//Enter 13
	// # (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 == 13){
		ValidateB();
		value= false;
	}	
	else if (!(key <= 32  || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122)|| (key == 241 || key == 209) || 
				 (key == 45 && string.indexOf(char)==-1) )){
		 value= false;
	}
	
	return value;

}

function OnlyLetterRef(evt, string){
	//Mayusculas 65-90
	//Minusculas 97-122
	// 209,  241
	//Enter 13
	// # (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 == 13){
		ValidateReference();
		value= false;
	}	
	else if (!(key <= 32  || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122)|| (key == 241 || key == 209) || 
				 (key == 45 && string.indexOf(char)==-1) )){
		 value= false;
	}
	
	return value;

}

function OnlyLetterSec(evt, string){
	//Mayusculas 65-90
	//Minusculas 97-122
	// 209,  241
	//Enter 13
	// # (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 == 13){
		ValidateSector();
		value= false;
	}	
	else if (!(key <= 32  || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122)|| (key == 241 || key == 209) )){
		 value= false;
	}
	
	return value;

}

//**************************************************
//**   MakeSearch(): 
//*    Dependiendo de cual es la opcion pulsada, se realiza el MakeSearch correspondiente, GMS o GD. 
//*    
//**************************************************
function MakeSearch()
{
	//Capturo cual radio button fue pulsadalerto por el usuario:

	//El radio button pulsado fue el de grado, minutos y segundos?
	var OpLL = $("#OpLL");

	if($("#OpLL").attr("checked") )
	{
		//op = 1 para la longitud
		//op = 2 para la latitud
		
		//Se le asigna a la longitud su validacion correspondiente al caso de GMS:
		return MakeSearchGMS();	
	}else
	{
		return MakeSearchLL();
	}
}

function EventEnterLatitLong(evt){
	// NOTE: Enter = 13
	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 == 13){
	
		if($("#OpLL").attr("checked"))
		{
			MakeSearchGMS();
			return false;
		}else
		{
			MakeSearchLL();
			return false;
		}
	}
	return true;
}

function OnlyNumber(evt,op){
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, '.' = 46 , '-' = 45
	var key; 
	var value= true;
	
	if(window.event) // IE
	{
		key = evt.keyCode;
	}
	else if(evt.which) // Netscape/Firefox/Opera
	{
		key = evt.which;
	}

	//ES Latitud?
	if(op == 2)
	{
	      // capturo el string actual escrito en el text
	      var charr = $("#Latitud").attr("value");
	      var txt = "latitud";
	}else
	{
	   // capturo el string actual escrito en el text
	   var charr = $("#Longitud").attr("value");
	   var txt = "longitud";
	}
	
	//capturo la longitud de dicho string
	var charLength = charr.length;
	
	//Es key='.' y es el primer caracter que se escribe? 
	if((charLength == 0)&&(key == 46)) // true: en el comienzo del string existe un '.'.
	{
           return false;// No se escribe en el text
	   
	}else
	    {  // evaluacion del text longitud
	      if(txt == "longitud")
	      {
	    
	        //ES key = '-' y se escribe despues del primer caracter?
	    	if(((charLength >= 1)&&(key == 45))&&(charr.indexOf("-") != -1))// TRue: el usuario esta escribiendo el caracter - a partir del 2 caracter, por lo tanto no es permitido un numero con un - a partir de la posicion 2 de la cadena
	        {
	              return false;// NO se escribe en el text
		      
		}else
		    {
		       //El usuario ya antes a escrito el caracter '.' y lo esta tratando de ingresar denuevo?
		       if((key == 46 )&& (charr.indexOf(".") != -1))// TRue: el usuario ya ha escrito en el text el caracter . 
		       {
		       		return false; //No se escribe en el text 
				
		       }else
		       	   {   //El usuario ha escrito alguna letra o caracter no permitido sobre el texto?
				if((key <= 13) || (key >= 48 && key <= 57) || (key == 45) || (key == 46))//True: se ha escrito correctamente el caracter
				{
					return true;// Se escribe el caracter en el text
				}else
				{	
					return false;// NO se escribe el caracter
				}	   
			   }
		    }
              }else //Evaluacion del text Latitud
	      	  {
		  	//El usuario ya antes a escrito el caracter '.' y lo esta tratando de ingresar denuevo?
		       if((key == 46 )&& (charr.indexOf(".") != -1))// TRue: el usuario ya ha escrito en el text el caracter . 
		       {
		       		return false; //No se escribe en el text 
				
		       }else
		       	   {	
				//El usuario ha escrito alguna letra o caracter no permitido sobre el texto?
				if((key <= 13) || (key >= 48 && key <= 57) ||(key == 46))//True: se ha escrito correctamente el caracter
				{
					return true;// Se escribe el caracter en el text
				}else
				{	
					return false;// NO se escribe el caracter
				}
			  }	    	   
		  }		      
	 }		
}

function OnlyNumberGMS(evt,op){
	// NOTE: Backspace=8,   Enter=13,   '0'=48,    '9'=57,    '/'= 47    '.'=46
	
	var key; 
		
	if(window.event) // IE
	{
		key = evt.keyCode;
	}
	else if(evt.which) // Netscape/Firefox/Opera
	{
		key = evt.which;
	}
	
	if(op == 1){
	  var GMS = $("#Longitud").attr("value");
	}
	else{
		var GMS = $("#Latitud").attr("value");
	}
	
	  //El usuario ya antes a escrito el caracter '.' y lo esta tratando de ingresar denuevo?
	  if((key == 46 )&& (GMS.indexOf(".") != -1)){// TRue: el usuario ya ha escrito en el text el caracter . 
	  		 return false; //No se escribe en el text 
	  }
	  else{
	  
		return (key <= 13 || (key >= 48 && key <= 57) || (key == 47) || (key == 46));
	  }	
}

function MakeSearchGMS(){

	var LongitudGMS = $("#Longitud").attr("value");
	var LatitudGMS = $("#Latitud").attr("value");
	var Pass = true;
	var OpLongLatit = 1;
	

	while(OpLongLatit < 3){
	
		var Error ="";
		var Latit_Long = LongitudGMS;
		var Latit_LongGMSLength = LongitudGMS.length;//longitud de la longitud
		var ContLatit_LongGMS = 0;//Contador que lleva la cuenta del caracter /.
		var CleanLatit_LongGMS =LongitudGMS.split("/");// Elimino los caracteres /.
		
		if(OpLongLatit == 1){//True: se evaluara para longitud/False: se evaluara para latitud
			Error = "lo";
		}	
		else{
		  	Error = "la";
		}
			
		//*****Validacion de la Latitud que contenga solo 3 /:*****
		for(i=0;i<Latit_LongGMSLength;i++)
		{
			if(Latit_Long.charAt(i)=="/")
				ContLatit_LongGMS = ContLatit_LongGMS + 1;	
		}
			
		//true: contiene mas de 3 /. False: no contiene mas de 3 /, por lo tanto hay que evaluar que no esten juntos los /, por ejemplo: 45//66/
		if(ContLatit_LongGMS != 2){
			Pass = false;
			SetSmsError(Error);
		}
		else{ 

			var cont = 0;
				
			//Se recorre los grados, segundos y minutos.
			//Mientras sea menor a los 3 registors y no se haya encontrado algun error
			while(cont < 3)
			{
		
				var CleanLatit_LongGMSLength = CleanLatit_LongGMS[cont].length;//Longitud del registro
			
			//true: quiere decir que los grados o minutos contienen mas de 2 caracter, por ejemplo: 234/345666/....
			//False: no son mas de dos caracteres grados/minutos o se comenzara a evaluar los segundos porque el cont es mayor que 2, en este caso se chequea si se esta evaluando el segundo
				if((CleanLatit_LongGMSLength > 2)&&(cont < 2))//Para este caso, los segundos solamente pueden tener mas de dos caracteres 
				{	//alert("tienen mas de dos caracteres los grados o minutos ERROR");
					Pass = false;
					
					SetSmsError(Error);
				}else
				{
					if(cont == 2)//true: se comenzara a evaluar los segundos
					{
					//Se chequea que si se da el caso de que el usuario lo escriba con decimal, este este bien escrito.
					//Se valuan solamente estos 2 casos: .34 o 343.
								
					//TRue: El usuario ha escrito el decimal de esta manera .xx
						if(CleanLatit_LongGMS[cont].indexOf(".")==0)
						{//alert("hay un decimal al principio del Nr");
							Pass = false;
							SetSmsError(Error);
						}
						else
						{  //True: quiere decir que el usuario escribio el decimal de esta manera xx.
							if(CleanLatit_LongGMS[cont].indexOf(".")==(CleanLatit_LongGMSLength - 1))
							{//alert("hay un decimal al final del Nr");
									Pass = false;
									SetSmsError(Error);
							}	
						}
					}else
					{
						//Se chequea que el usuario no haya colocado en grado o minutos un decimal.
						//True: quiere decir que grados o minutos contiene un decimal .
						if(CleanLatit_LongGMS[cont].indexOf(".")!= -1)
						{//alert("hay un decimal en grados o minutos");
							Pass = false;
							SetSmsError(Error);
						}
					}
				}	    
				cont = cont + 1;		    
			}
    	}

		//*****Fin Validacion	
		OpLongLatit = OpLongLatit + 1; 	    
		//alert(OpLongLatit);
	}
	
	//SE permite la ejecucion del procedimiento que busca en el mapa por medio de lati y long?
	if(Pass == true){
			SetSmsError("");
		 window.opener.SearchByLL($("#Longitud").attr("value"),$("#Latitud").attr("value"),2);
		 window.opener.focus();
	}			
}					

function SetSmsError(Error){

	var div = $("#ErrorDiv");
	
	if (Error != ""){
		if(Error == "lo"){
			div.html("El valor que introdujo en longitud es incorrecto");
		}
		else{
			div.html("El valor que introdujo en latitud es incorrecto");
		}
	}
	else{
		div.html("&nbsp;");
	}
}

//**************************************************
//**    CleanErrorLa()): 
//*    Limpia el mensaje de error 
//*   
//**************************************************
function CleanError(op){
	
	$("#ErrorDiv").html("&nbsp;");
} 

//**************************************************
//**   MakeSearchLL(): 
//*    Ejecuta la funcion que realiza la 
//*    busqueda sobre el mapa, en la ventana padre.
//**************************************************
function MakeSearchLL()
{
	var Latitud = $("#Latitud").attr("value");
	var Longitud = $("#Longitud").attr("value");
	
	var LatitudLength = Latitud.length;
	var LongitudLength = Longitud.length;
	
	var PosCharPointLatitud = Latitud.length - 1;
	var PosCharPointLongitud = Longitud.length - 1;
	var Pass = true; 
	
	
	
	//El usuario ha escrito la latitud con el caracter . al final del numero?
	if((Latitud.charAt(PosCharPointLatitud) == ".")||(Latitud<0.568288)||(Latitud>12.247812))
	{
	 SetSmsError("la");//Sms Error en lalitud
	 Pass = false;
	
	}  
	if((Longitud.charAt(PosCharPointLongitud)==".")||(Longitud.charAt(PosCharPointLongitud)=="" )||(Longitud<-73.387373)||(Longitud>-59.742652))
	{
	 SetSmsError("lo");//Sms Error en longitud
	 Pass = false;
	}		
	
	//SE permite la ejecucion del procedimiento que busca en el mapa por medio de lati y long?
	if(Pass == true)
	{
	SetSmsError("");
	  window.opener.SearchByLL($("#Longitud").attr("value"),$("#Latitud").attr("value"),1);
	  window.opener.focus();
	}
	else
	{
	 return false;	
	}
}

//**************************************************
//**   Validated(): 
//*    Dependiendo del radio button que haya pulsado el usuario, esta funcion agrega la validacion correspondiente a la longitud o latitud, para el caso de GMS o GD. 
//*    
//**************************************************
function Validated(evt,op)
{
	//Capturo cual radio button fue pulsado por el usuario:

	//El radio button pulsado fue el de grado, minutos y segundos?
	
	if($("#OpLL").attr("checked"))
	{
		//op = 1 para la longitud
		//op = 2 para la latitud
		
		//Se le asigna a la longitud su validacion correspondiente al caso de GMS:
		return OnlyNumberGMS(evt,op);	
	}else
	{
		//El pulsado fue grados decimal:
		return OnlyNumber(evt,op);
	}
}


//*************************************************
//************* RadioOpLL()  **********************

//Limpia los campos de latitud y longitud y modifica el estado del cheked del radio button pulsado

//*************************************************
//*************************************************
function RadioOpLL()
{
	$("#Latitud").attr("value","");
	$("#Longitud").attr("value", "");
	$("#OpLL").attr("checked", false);
}

function RadioOpLL2()
{
	$("#Latitud").attr("value", "");
	$("#Longitud").attr("value", "");
	$("#OpLL").attr("checked", false);
	//document.getElementById("OpLL").checked.value="false";
	//var f = document.getElementById("OpLL").checked;
}

function GoToHelp(){
	var url = "Longitud_Latitud.html";
	var PopUp = window.open(url,'','resizable=0,left=120,top=90,width=500,height=400,toolbar=0, scrollbars=1, status=yes ');
	PopUp.focus();

}


/***************************************************************************
 * LoadMunicipality
 * Procedimiento que dado un estado muestra los municipios correspondientes
 * en el combo
 ****************************************************************************/
function LoadMunicipality(intState,div,sURL){

	if(intState!=0)
	{
		
		//Construye la cadena de parámetros para la consulta
		var sParams="cmbState="+intState;
		
		$.ajax({
			type: "GET",
			url: sURL,
			data: sParams,
			dataType: "html",
			cache: false,
			beforeSend: function(XMLhtml){
				$("#ImageMunicipality").html("<img src='../../Images/Map/Loading/InfoLoading2.gif'/>");				
			},
			success: function(XMLhtml){
			
				$('#'+div).html(XMLhtml);
				$('#'+div).attr("enabled", true); 
				$("#cmbMunicipality").attr("disabled", false);
				$("#cmbMunicipality").attr("value", 0);	
				$("#ImageMunicipality").html("");
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				$("#ImageMunicipality").html("");
				
			}
			
		})
	
		$("#cmbParish").attr("value", 0);
		$("#cmbParish").attr("disabled", true);
		
	}
	else{
		$("#cmbCity").attr("disabled", true);
		$("#cmbCity").attr("value", 0);	
		$("#cmbMunicipality").attr("disabled", true);
		$("#cmbMunicipality").attr("value", 0);	
		$("#cmbParish").attr("disabled", true);
		$("#cmbParish").attr("value", 0);		
		$("#cmbSector").attr("disabled", true);
		$("#cmbSector").attr("value", 0);	
	}		
}

/***************************************************************************
 * LoadParish
 * Procedimiento que dado un municipio muestra las parroquias correspondientes 
 * en el combo
 ****************************************************************************/
function LoadParish(intMunicipality,div,sURL){
	//Construye la cadena de parámetros para la consulta
	var sParams="cmbMunicipality="+intMunicipality;
	
	$.ajax({
		type: "GET",
		url: sURL,
		data: sParams,
		dataType: "html",
		cache: false,
		beforeSend: function(XMLhtml){
							
			$("#ImageParish").html("<img src='../../Images/Map/Loading/InfoLoading2.gif'/>");
		},
		success: function(XMLhtml){
			
			$('#'+div).html(XMLhtml);
			$('#'+div).attr("enabled", true); 
			$("#cmbParish").attr("disabled", false);
			$("#cmbParish").attr("value", 0);	
			$("#ImageParish").html("");
				
			
		},
		error: function(XMLhtml, textStatus, errorThrown){
			$("#ImageParish").html("");
			
		}
	})
}


/***************************************************************************
 * LoadCity
 * Procedimiento que dado un estado muestra las ciudades correspondientes
 * en el combo
 ****************************************************************************/
function LoadCity(intState,div,sURL){

if(intState!=0)
	{
		//Construye la cadena de parámetros para la consulta
		var sParams="cmbState="+intState;
		
		$.ajax({
			type: "GET",
			url: sURL,
			data: sParams,
			dataType: "html",
			cache: false,
			beforeSend: function(XMLhtml){
								
				$("#ImageCity").html("<img src='../../Images/Map/Loading/InfoLoading2.gif'/>");
			},
			success: function(XMLhtml){
				
				$('#'+div).html(XMLhtml);
				$('#'+div).attr("enabled", true); 
				$("#cmbCity").attr("disabled", false);
				$("#cmbCity").attr("value", 0);	
				$("#ImageCity").html("");
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				$("#ImageCity").html("");
				
			}
			
		})
//		$("#cmbCity").attr("value", 0);
//		$("#cmbCity").attr("disabled", true);
	}
}


/***************************************************************************
 * LoadStateSector
 * Procedimiento que dado un estado muestra los sectores correspondientes
 * en el combo
 ****************************************************************************/
function LoadStateSector(intState,div,sURL){

	if(intState!=0)
	{
		//Construye la cadena de parámetros para la consulta
		var sParams="cmbState="+intState;
	
		$.ajax({
			type: "GET",
			url: sURL,
			data: sParams,
			dataType: "html",
			cache: false,
			beforeSend: function(XMLhtml){
								
				$("#ImageSector").html("<img src='../../Images/Map/Loading/InfoLoading2.gif'/>");
			},
			success: function(XMLhtml){
				
				$('#'+div).html(XMLhtml);
				$('#'+div).attr("enabled", true); 
				$("#cmbSector").attr("disabled", false);
				$("#cmbSector").attr("value", 0);	
				$("#ImageSector").html("");
						
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				$("#ImageSector").html("");
				
			}
			
		})
	
		$("#cmbSector").attr("value", 0);
		$("#cmbSector").attr("disabled", true);
		
	}

}

/***************************************************************************
 * LoadMunicipalitySector
 * Procedimiento que dado un municipio muestra los sectores correspondientes
 * en el combo
 ****************************************************************************/
function LoadMunicipalitySector(intMunicipality,div,sURL){


	if(intMunicipality!=0)
	{
		//Construye la cadena de parámetros para la consulta
		
		var sParams="cmbMunicipality="+intMunicipality;
		
		$.ajax({
			type: "GET",
			url: sURL,
			data: sParams,
			dataType: "html",
			cache: false,
			beforeSend: function(XMLhtml){
				
				$("#ImageSector").html("<img src='../../Images/Map/Loading/InfoLoading2.gif'/>");
				//$("#cmbSector").attr("value", 0);
				//$("#cmbSector").attr("disabled", true);
				
			},
			success: function(XMLhtml){
				
				$('#'+div).html(XMLhtml);
				$('#'+div).attr("enabled", true); 
				$("#cmbSector").attr("disabled", false);
				$("#cmbSector").attr("value", 0);	
				$("#ImageSector").html("");
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				$("#ImageSector").html("");
				alert("error");	
			}
		})	
	}
	else{
		//si no se selecciona una parroquia, se carga con los sectores del estado
		LoadStateSector($("#cmbState").attr("value"), "SectorDiv","AjaxStateSector.php");
	}	
}


/***************************************************************************
 * LoadParishSector
 * Procedimiento que dado una parroquia muestra los sectores correspondientes
 * en el combo
 ****************************************************************************/
function LoadParishSector(intParish,div,sURL){

	if(intParish!=0)
	{
		//Construye la cadena de parámetros para la consulta
		var sParams="cmbParish="+intParish;
		
		$.ajax({
			type: "GET",
			url: sURL,
			data: sParams,
			dataType: "html",
			cache: false,
			beforeSend: function(XMLhtml){
								
				$("#ImageSector").html("<img src='../../Images/Map/Loading/InfoLoading2.gif'/>");
			},
			success: function(XMLhtml){
				
				$('#'+div).html(XMLhtml);
				$('#'+div).attr("enabled", true); 
				$("#cmbSector").attr("disabled", false);
				$("#cmbSector").attr("value", 0);	
				$("#ImageSector").html("");
				
			},
			error: function(XMLhtml, textStatus, errorThrown){
				$("#ImageSector").html("");
				
			}
			
		})
	
		$("#cmbSector").attr("value", 0);
		$("#cmbSector").attr("disabled", true);
		
	}
	else{
		//si no se selecciona una parroquia, se carga con los sectores del estado
		LoadMunicipalitySector($("#cmbMunicipality").attr("value"), "SectorDiv","AjaxMunicipalitySector.php");
	}

}


/***************************************************************************
 * LoadReferenceDescSubType
 * Procedimiento que dado un tipo de descriptor de referencia, muestra los 
 * subdescriptores correspondientes en el combo
 ****************************************************************************/
function LoadReferenceDescSubType(){

	intDescType = $("#cmbRef1").attr("value");
	objDiv = "RefDiv";
	
	if(intDescType>0)
	{
		//Objeto XMLHttpRequest para el manejo de Ajax
		var objAj = false;
		
		//Creación del objeto XMLHttpRequest
		if (window.XMLHttpRequest){
			objAj = new XMLHttpRequest()
		} else if (window.ActiveXObject) {
			objAj = new ActiveXObject("Microsoft.XMLHTTP");
		}
	
		if(objAj){
			$("#cmbRef2").attr("disabled",true);
			$("#cmbRef2").attr("value",0);
			
			//Objeto XMLHttpRequest
			var obj=document.getElementById(objDiv);
				
			objAj.open("GET","AjaxReferenceDescSubType.php?cmbRef="+intDescType);
			
			objAj.onreadystatechange = function(){
				if (objAj.readyState==4) {
				
					if (objAj.status==200){
						obj.innerHTML = objAj.responseText;
						obj.enabled=true;
						$("#cmbRef2").attr("disabled",false);
						$("#cmbRef2").attr("value",0);	
						$("#ImageRef2").html("");
						
					}
					else{
						$("#ImageRef2").html("");
					}		
				}
				else{
					$("#ImageRef2").html("<img src='../../Images/Search/InfoLoading2.gif'/>");
				}
			}
			objAj.send(null);	
		}
		else{
			//si no se selecciona una parroquia, se carga con los sectores del estado
			//alert('0');
			//LoadMunicipalitySector(document.getElementById("cmbMunicipality").value, "SectorDiv","AjaxMunicipalitySector.php");
			//document.getElementById("cmbSector").disabled=true;
			//document.getElementById("cmbSector").value=0;
		}
	}		
}