var variablesVentanaModal = "dialogHeight:610px;dialogWidth:840px;help:no;resizable:no;status:no;center:yes";
var variablesVentanaCasos = "dialogHeight:300px;dialogWidth:830px;help:no;resizable:no;status:no;center:yes";

/*INICIO metodos para realizar busqueda en los combos*/
var digitos=10 //cantidad de digitos buscados
var puntero=0
var buffer=new Array(digitos) //declaración del array Buffer
var cadena=""
var ClickSobreMenu = "";
var estadoMensaje = "";
var noValidar = false;
var permitirExportar = true;

function Anthem_Error(result) {
	if(result.error!="123Session"){
		try{
			if(document.getElementById("cLoadingIndicator").style.display=="")
				cLoadingIndicator_PostCallBack();
		}catch(error){}
		var error = new String(result.error);
		if(error == "BADRESPONSE" || error == "NORESPONSE")
		{
			document.location.href ='../Comun/SessionFinalizada.htm';
		}
		else
		{
			//alert(document.location.href );
			var pag= "../Comun/ErrorAplicacion.aspx?error=" + error.replace(new RegExp("\"","g"), "'");
		
			new popUp(posXPopUp-100, posYPopUp, 750, 380, 'idDiv', pag, 'white', '#00385c', '16pt serif', 'Se present&oacute un error en la aplicaci&oacuten', '#00385c', 'white', 'lightgrey', '#00568c', 'black', true, true, true, true, true, false,'../img/popup/min.gif','../img/popup/max.gif','../img/popup/close.gif','resize.gif');
		
		}
	}
}

function buscar_op(obj){
   var letra = String.fromCharCode(event.keyCode)
   if(puntero >= digitos){
       cadena="";
       puntero=0;
    }
   //si se presiona la tecla ENTER, borro el array de teclas presionadas y salto a otro objeto...
   if (event.keyCode == 13){
       borrar_buffer();
       try{
		obj.onchange();
	}catch(error){}
    }
    //si se presiona la tecla ESC, inica de nuevo la consulta
	   if (event.keyCode == 27){
	       borrar_buffer();
	       obj.selectedIndex = 0;
	       try{
			obj.onchange();
			}catch(error){}
    }
   //sino busco la cadena tipeada dentro del combo...
   else{
       buffer[puntero]=letra;
       //guardo en la posicion puntero la letra tipeada
       cadena=cadena+buffer[puntero]; //armo una cadena con los datos que van ingresando al array
       puntero++;

       //barro todas las opciones que contiene el combo y las comparo la cadena...
       for (var opcombo=0;opcombo < obj.length;opcombo++){
          if(obj[opcombo].text.substr(0,puntero).toLowerCase()==cadena.toLowerCase()){
			obj.selectedIndex=opcombo;
			break;
          }
       }
    }
   event.returnValue = false; //invalida la acción de pulsado de tecla para evitar busqueda del primer caracter
}
//encontrar la posicion relativa de un objeto, se usa para calcular las posiciones del menu
function findPos(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
	return [curleft,curtop];
}

function borrar_buffer(){
    if(cadena != ""){
		var obj = window.event.srcElement;
		try{
			obj.onchange();
		}catch(error){}
	}
   //inicializa la cadena buscada
    cadena="";
    puntero=0;
}

/*FIN metodos para realizar busqueda en los combos*/

/*Inicio tool Tip Combo*/

	function getX(obj){
		return( obj.offsetParent==null ? obj.offsetLeft : obj.offsetLeft+getX(obj.offsetParent) );
	}
	function getY(obj)
	{
		return( obj.offsetParent==null ? obj.offsetTop : obj.offsetTop+getY(obj.offsetParent) );
	}
//valida la extension maxima de un campo de texto multilinea
function maxLengthTextArea(obj,e,valor) {
	ma=valor; //nº máximo de caracteres
	tecla=(document.all)?e.keyCode:e.which;		
	if(obj.value.length==ma && tecla!=8 && tecla!=13 && tecla!=37 && tecla!=38 && tecla!=39 && tecla!=40 && tecla!=46 && tecla!=35 && tecla!=36 && !(event.ctrlKey && tecla==67))
	   return false;

	/*if(tecla==13 && e.srcElement.type == "textarea")
	   return false;*/
}

//valida la extension maxima de un campo de texto multilinea
///Modificado por Dairo: Agosto 21 - 2007
function maxLengthTextAreaOnDrop(obj,e,valor) {

	ma=valor;
	tecla=(document.all)?e.keyCode:e.which;
	var textoCopy = new String(event.dataTransfer.getData('Text'));
	textoCopy = textoCopy.replace(new RegExp("<","g"),'{MENOR}').replace(new RegExp(">","g"),'{MAYOR}');
	textoCopy = textoCopy.replace(new RegExp("\\r\\n", "g"),'. ');
	lenCampo = obj.value.length;
    lenCopy = textoCopy.length;   	
	if (lenCampo > 0)
	{
	   lenCampo = lenCopy + lenCampo;
	}
	else
	{
	   lenCampo = lenCopy;
	}
	
	permitido = ma-obj.value.length;
	if((permitido >0) && tecla!=8){
		var cortar =obj.value + textoCopy.substring(0,permitido);
		obj.value =cortar ;
	}
	return false;
}

//valida la extension maxima de un campo de texto multilinea al pegar (copy - paste)
///Modificado por Dairo: Agosto 21 - 2007
function maxLengthTextAreaOnPaste(obj, e, maxLength) 
{
	ma=maxLength;
	tecla=(document.all)?e.keyCode:e.which;
	var textoCopy = new String(window.clipboardData.getData('Text'));
	var seleccionado=document.selection.createRange(); 
	var seleccion = seleccionado.text;
	obj.value  = obj.value.replace(seleccion,'');
	textoCopy = textoCopy.replace(new RegExp("<","g"),'{MENOR}').replace(new RegExp(">","g"),'{MAYOR}');
	textoCopy = textoCopy.replace(new RegExp("\\r\\n", "g"),'. ');
	
	lenCampo = obj.value.length;
    lenCopy = textoCopy.length;   	
	if (lenCampo > 0)
	{
	   lenCampo = lenCopy + lenCampo;
	}
	else
	{
	   lenCampo = lenCopy;
	}
	
	permitido = ma-obj.value.length;
	if((permitido >0) && tecla!=8){
		var cortar =obj.value + textoCopy.substring(0,permitido);
		obj.value =cortar ;
	}
	return false;
}

/*
Comparar fechas 
retorna 
0 si on iguales
1 si fecha Ini > fecha Fin
-1si fecha Ini < fecha Fin
FORMATO yyyy/mm/dd ó yyyy-mm-dd
*/
function CompararFechas(FechaUno, FechaDos)
{
	
	///Agosto 01: Se comento eeste codigo y se ccambio por el que sigue, porque fallaba cuando la fecha 
	///final tenia como dia el 08 o 09.
	/*var anoUno=parseInt(FechaUno.substr(0,4));
	var mesUno=(FechaUno.substr(5,2));
	var diaUno=parseInt(FechaUno.substr(8,2));
	var anoDos=parseInt(FechaDos.substr(0,4));
	var mesDos=(FechaDos.substr(5,2));
	var diaDos=parseInt(FechaDos.substr(8,2));
	*/
	var anoUno=FechaUno.substr(0,4);
	var mesUno=FechaUno.substr(5,2);
	var diaUno=FechaUno.substr(8,2);
	var anoDos=FechaDos.substr(0,4);
	var mesDos=FechaDos.substr(5,2);
	var diaDos=FechaDos.substr(8,2);
	
	if(FechaUno == FechaDos)
	{
		return 0;
	}
	if (anoUno>anoDos)
	{
		return 1;
	}
	if ((anoUno==anoDos) && (mesUno>mesDos))
	{
		return 1;
	}
	if ((anoUno==anoDos) && (mesUno==mesDos) && (diaUno>diaDos))
	{
		return 1;
	}
	return -1
}

/*metodos para validar cajas de texto que solo permitan valores porcentaje */

function getCursorPos(el){ 
	var sel, rng, r2, i=-1; 
	var selection = document.selection; 
	var textRange = el.createTextRange 
	if(selection && textRange) 
	{ 
		sel=document.selection; 
		if(sel)
		{ 
			r2=sel.createRange(); 
			rng=el.createTextRange(); 
			rng.setEndPoint("EndToStart", r2); 
			i=rng.text.length; 
		} 
	} 
	return i; 
} 




function validarCaracteres(campo)
{
	Code=window.event.keyCode;
	if ((Code >= 48 && Code <=57) || (Code == 46) || (Code >= 65 && Code <= 90) || (Code >= 97 && Code <= 122) || (Code == 95))
		return true;
	else
		window.event.returnValue = false;
}


function validarPorcentaje(campo){
	Code=window.event.keyCode;
	if(Code==46)
	{
		if(campo.value.length ==0 )
			window.event.returnValue = false;
		if(campo.value.indexOf('.',0) != -1 || campo.value.length == 3)
			window.event.returnValue = false;
	}
	else
	{
		
		if(!(Code >=48 && Code <= 57))
			window.event.returnValue = false;

		var posicion = getCursorPos(campo);
		var cadenaLeft = campo.value.substring(0, posicion);
		var cadenaRight = campo.value.substring(posicion, campo.value.length);		
		//validar que no haya texto seleccionado
		var seleccionado=document.selection.createRange(); 
		
		if(parseFloat(cadenaLeft + String.fromCharCode(event.keyCode) + cadenaRight) > 100 && seleccionado.text =="")
			window.event.returnValue = false;
		
		if(Code ==48){
			if(campo.value.length ==1 && campo.value == "0")
				window.event.returnValue = false;
		}

		if(campo.value.length ==1 && campo.value == "0" && Code >=48 && Code <= 57 )
		{
			if (campo.value == "0" && Code == 48)
				window.event.returnValue = false;
		}
		if(campo.value.indexOf('.',0) != -1){
			var cadena = campo.value.substring( campo.value.indexOf('.',0) + 1,  campo.value.length);
			if(cadena.length + 1 > 8 && posicion > campo.value.indexOf('.',0))
				window.event.returnValue = false;
		}							
	}
}

function DesplaceVertical()
{
	/*Code=window.event.keyCode;
	if(event.srcElement.type != "select" || event.srcElement.type != "textarea"){
		if((Code == 37 || Code == 38 || Code == 39 || Code == 40))
			window.event.returnValue = false;
	}*/
}
			
	/* Fin metodos porcentaje*/


  /*INICIO tool Tip en un Combo*/

 function DivSetVisible(state){
    var lobjCurrentDropdown = window.event.srcElement;
    posX = getX(lobjCurrentDropdown) ;
    posY = getY(lobjCurrentDropdown);
	var DivRef = document.getElementById('PopupDiv');
	var IfrRef = document.getElementById('DivShim');
	if(lobjCurrentDropdown.selectedIndex != null){
		if(state){
			DivRef.innerHTML = lobjCurrentDropdown.options[lobjCurrentDropdown.selectedIndex].text;
			DivRef.style.display = "block";
			DivRef.style.top = posY +20;
			DivRef.style.left = posX + 2;
			IfrRef.style.width = DivRef.offsetWidth;
			IfrRef.style.height = DivRef.offsetHeight;
			IfrRef.style.top = DivRef.style.top;
			IfrRef.style.left = DivRef.style.left;
			IfrRef.style.zIndex = DivRef.style.zIndex - 1;
			IfrRef.style.display = "block";
			
		}
		else{
			DivRef.style.display = "none";
			IfrRef.style.display = "none";
		}
	}
  }
  /*FIN tool Tip Combo*/

if (window.Event) 
	document.captureEvents(Event.MOUSEUP); 


function hideElemento(elmID,control) {
	if(document.all) {
		for(i = 0; i < document.all.tags( elmID ).length; i++) {
			obj = document.all.tags(elmID)[i];
			if(!obj || !obj.offsetParent) continue;
			if(control.name !=obj.name && !obj.disabled){
				obj.disabled = true;
				obj.title = "Solicitud en Proceso ...";
			}
		}
	}
	
}
function showElemento(elmID) {
		if(document.all) {
			for(i = 0; i < document.all.tags( elmID ).length; i++) {
				obj = document.all.tags(elmID)[i];
				if(!obj || !obj.offsetParent) continue;
				if(obj.title == "Solicitud en Proceso ..."){
					obj.disabled=false;
					//alert('aqui es!!!');
					//obj.title = ""; 
				}
			}
		}
	
}
function VerificarValidadores()
{	
	var elementosRFV = document.getElementsByTagName('span');
	var elementosVS = document.getElementsByTagName('div');
	
	var nombre;
	for (var i = 0; i < elementosRFV.length; i++){
		nombre = elementosRFV.item(i).id.substring(0,3);
		if (nombre == 'rfv' || nombre == 'cov' || nombre.substring(0,2) == 'rv' || nombre == 'rev' || nombre == 'cuv' || nombre.substring(0,2) == 'uc'){
			if(elementosRFV.item(i).style.visibility == 'visible')
				alert(elementosRFV.item(i).style.visibility)
			}
				//return false;
	}
	/*for (var i = 0; i < elementosVS.length; i++)
	{
		nombre = elementosVS.item(i).id.substring(0,2);
		if (nombre == 'vs')
			if(elementosVS.item(i).style.display == '' || elementosVS.item(i).style.display == 'none')
			alert(elementosVS.item(i).style.display)
				//return false;
	}*/				
	return true;
}
function nocontextmenu()
{ 
	event.cancelBubble =true; 
   event.returnValue = false; 
	return false; 
} 
var mouseLeft = 1;

//Para el control del timeout
var intTimeOut = 9000000;
var intIDTimeOut;
function validarTimeOut(){
	if (mouseLeft==1 || mouseLeft==3){
		return;
	}else {
		if (document.getElementById("txtIDControlFocus")!=null)
			document.getElementById("txtIDControlFocus").value="";
		
		//cerrarSession('/Comun/FinSession.htm');
		intTimeOut = 9000000;
		cLoadingIndicator_PreCallBack1();
		clearTimeout(intIDTimeOut);
		mouseLeft=3;
		alert("El sistema no responde debido a que la operaci\xf3n est\xe1 tomando m\xe1s tiempo del esperado.\nFavor intente m\xe1s tarde. En caso de persistir el problema comun\xedquese con la l\xednea atenci\xf3n de clientes de XM.");
		//window.location.href = "../comun/Logout.aspx";
	}
}

//function Anthem_PreCallBack(control){
function cLoadingIndicator_PreCallBack(control){
	try{
		//alert("PreCallBack: " + mouseLeft);
		if(window.event != null)
		{
			var control = window.event.srcElement;
		}
		var puedeMostrar = true;
		// Se cambió esta linea 
		//if (typeof(Page_ClientValidate) == 'function' && control.tagName == "INPUT" && control.value != "False" ) {
		if (typeof(Page_ClientValidate) == 'function') {
			puedeMostrar = Page_ClientValidate();
			//alert(puedeMostrar)
		}
		if(puedeMostrar)
		{
			if (document.getElementById("cLoadingIndicator") != null)
			{
				document.getElementById("cLoadingIndicator").style.display="";
				mouseLeft=2;
				if(control != null)
					hideElemento('SELECT',control);
					
				//Inicia el control del timeout
				intIDTimeOut = window.setTimeout("validarTimeOut();",intTimeOut);
			}
		}
	}
	catch(error)
	{
		mouseLeft=1;
		if (document.getElementById("cLoadingIndicator") != null)
			document.getElementById("cLoadingIndicator").style.display="none";
		showElemento('SELECT');
	}
}
//function Anthem_PostCallBack(control){

function cLoadingIndicator_PreCallBack1(control){
	//alert("PreCallBack: " + mouseLeft);
	try{
		if(window.event != null)
		{
			var control = window.event.srcElement;
		}
		
			if (document.getElementById("cLoadingIndicator") != null)
			{
				document.getElementById("cLoadingIndicator").style.display="";
				mouseLeft=2;
				if(control != null)
					hideElemento('SELECT',control);
					
				//Inicia el control del timeout
				intIDTimeOut = window.setTimeout("validarTimeOut();",intTimeOut);
			}
	}catch(error){
		mouseLeft=1;
		if (document.getElementById("cLoadingIndicator") != null)
			document.getElementById("cLoadingIndicator").style.display="none";
		showElemento('SELECT');
	}
}
//function Anthem_PostCallBack(control){

function cLoadingIndicator_PostCallBack(){
	try{
		//Si ya habia ocurrido timeout
		//alert("PostCallBack: " + mouseLeft);
		clearTimeout(intIDTimeOut);
		if (mouseLeft==3){
			alert("Se ha restablecido la comunicaci\xf3n con el servidor.");
		}
		
		mouseLeft=1;
		if (document.getElementById("cLoadingIndicator") != null)
			document.getElementById("cLoadingIndicator").style.display="none";
		//if(control != null)
		showElemento('SELECT');
	}catch(error){
		mouseLeft=1;
		if (document.getElementById("cLoadingIndicator") != null)
			document.getElementById("cLoadingIndicator").style.display="none";
		showElemento('SELECT');
	}
}

function Anthem_CallBackCancelled(){
	//alert("CallBackCancelled: " + mouseLeft);
	mouseLeft=1;
	clearTimeout(intIDTimeOut);
	if (document.getElementById("cLoadingIndicator") != null)
			document.getElementById("cLoadingIndicator").style.display="none";
}

function norightclick(e){ 
	if (window.Event){ 
		if (e.which !=1 && e.which !=2)
			return false;
		else{
			if((mouseLeft==2 || mouseLeft==3) && (e.which == 1 || e.which == 2)){
				alert("Solicitud en Proceso...") 
				return false;
			}
		}
	} 
	else{	
		if (event.button !=1 && event.button !=2){ 
			event.cancelBubble = true; 
			event.returnValue = false; 
			return false; 
		} 
		else{
			if((mouseLeft==2 || mouseLeft==3) && (event.button == 1 || event.button == 2)){
				alert("Solicitud en Proceso...") 
				return false;
			}
		}
	}	
} 
/*
INICIO Manejo de los tabs para toda la aplicacion
*/
	//var Controles;
	
	function aplicarTabs(){
	
		var controlesTemp = document.getElementsByTagName('*');;
		
		var index = 0;
		for (var i=0;i<controlesTemp.length;i++)
		{	
			var e=controlesTemp.item(i);
			var cal = true;
			
			if(e.tagName == "IMG" && e.src.indexOf("cal.gif")!= -1){
				cal = false;
			}
			if(cal && (e.tagName == "IMG" && e.style.cursor =="hand") ||(e.tagName == "A" && e.href.indexOf("#")==-1 && e.href.indexOf("www.intergrupo.com")==-1 )||e.tagName == "TEXTAREA" ||e.tagName == "SELECT" || e.tagName == "OPTION" || (e.tagName == "INPUT" && e.type!= "hidden")|| (e.tagName == "INPUT" && e.type== "image") )
			{
				e.tabIndex = i;
			}
			else
			{
				e.tabIndex = -1;
			}
		}
		//limpiarKeyUp();
	}

	var intIDEventGotFocus=0;
	
	function gotFocus(controlID)
	{
		if (controlID=="") return;
		document.getElementById("txtIDControlFocus").value=controlID;
		
		//if (document.getElementById(document.getElementById('txtIDControlFocus').value).tagName == "INPUT"){
		//	if (intIDEventGotFocus!=0)clearTimeout(intIDEventGotFocus);
		//	intIDEventGotFocus = window.setTimeout("strTMPValue=document.getElementById(document.getElementById('txtIDControlFocus').value).value;document.getElementById(document.getElementById('txtIDControlFocus').value).value=strTMPValue;alert(strTMPValue);document.getElementById(document.getElementById('txtIDControlFocus').value).select();",50);
		//}
	}
	
	function setFocus()
	{
		if (document.getElementById("txtIDControlFocus").value!=""){
			var control=document.getElementById(document.getElementById("txtIDControlFocus").value);
			if (control!=null && control.disabled==false)
			{
				//alert(control);
				try{
				control.focus();
				control.focus();
				}catch(error){}

				if (control.tagName == "INPUT"){
					if (intIDEventGotFocus!=0)clearTimeout(intIDEventGotFocus);
					intIDEventGotFocus = window.setTimeout("SetEnd(document.getElementById('txtIDControlFocus').value);",10);
					//intIDEventGotFocus = window.setTimeout("document.getElementById(document.getElementById('txtIDControlFocus').value).select();",10);
				}
			}
			//document.getElementById(document.getElementById("txtIDControlFocus").value).focus();
			//document.getElementById(document.getElementById("txtIDControlFocus").value).focus();
		}
		//cLoadingIndicator_PostCallBack();
	}

	function SetEnd(controlID)
	{
		if (controlID==null)return;
		if (document.getElementById(controlID)==null)return;
		var TB = document.getElementById(controlID);
		if (TB.tagName != "INPUT"){return;}
		if (TB.createTextRange)
		{
			try{
				var FieldRange = TB.createTextRange();
				FieldRange.moveStart('character', TB.value.length);
				FieldRange.collapse();
				FieldRange.select();
				TB.select();
			}catch(error){}
		}
	}
	
	function aplicarOnFocus(){
	
		var controlesTemp = document.getElementsByTagName('*');;
		
		var index = 0;
		for (var i=0;i<controlesTemp.length;i++)
		{	
			var e=controlesTemp.item(i);
			var cal = true;
			
			if(e.tagName == "IMG" && e.src.indexOf("cal.gif")!= -1){
				cal = false;
			}
			if(cal && (e.tagName == "IMG" && e.style.cursor =="hand") ||(e.tagName == "A" && e.href.indexOf("#")==-1 && e.href.indexOf("www.intergrupo.com")==-1 )||e.tagName == "TEXTAREA" ||e.tagName == "SELECT" || e.tagName == "OPTION" || (e.tagName == "INPUT" && e.type!= "hidden")|| (e.tagName == "INPUT" && e.type== "image") )
			{
				setAttOnFocus(e.id);
			}
		}
		//limpiarKeyUp();
	}
	
	function aplicarOnBlur(){
	
		var controlesTemp = document.getElementsByTagName('*');;
		
		var index = 0;
		for (var i=0;i<controlesTemp.length;i++)
		{	
			var e=controlesTemp.item(i);
			var cal = true;
			
			if(e.tagName == "IMG" && e.src.indexOf("cal.gif")!= -1){
				cal = false;
			}
			if(cal && (e.tagName == "IMG" && e.style.cursor =="hand") ||(e.tagName == "A" && e.href.indexOf("#")==-1 && e.href.indexOf("www.intergrupo.com")==-1 )||e.tagName == "TEXTAREA" ||e.tagName == "SELECT" || e.tagName == "OPTION" || (e.tagName == "INPUT" && e.type!= "hidden")|| (e.tagName == "INPUT" && e.type== "image") )
			{
				setAttOnFocus(e.id);
				setAttOnBlurValue(e.id)
			}
		}
		//limpiarKeyUp();
	}

	function setAttOnFocus(nombreControl) {
		if (nombreControl == "")return;
		var a = document.getElementById(nombreControl);

		if (a != null){
			a.onfocus = new Function("document.getElementById('txtIDControlFocus').value = '" + nombreControl + "';document.getElementById('txtIDControlValue').value=this.value");
			
			//alert(a.getAttribute("onfocus"));
		}
	}

	function setAttOnFocusValue(nombreControl) {
		if (nombreControl == "")return;
		var a = document.getElementById(nombreControl);
		if (a != null){
			var onfocusAnt = a.getAttribute("onfocus")
			a.onfocus = new Function("gotFocus(this.id);aplicarObjetoValor(this.value);");
			//alert(a.getAttribute("onfocus"));
		}
	}
	
	function setAttOnBlurValue(nombreControl) {
		return;
		if (nombreControl == "")return;
		var a = document.getElementById(nombreControl);
		if (a != null){
			var onFocus = a.getAttribute("onfocus")
			if (onFocus.indexOf("txtIDControlValue")!=-1)
				{
					a.onblur = new Function(onblurAnt.replace("calcularTotales(", "if(validarObjetoCambio(this.id, this.value))calcularTotales("));
					alert(a.getAttribute("onblur"));
				}
		}
	}
	
	function controlarTab(obj)
	{	
		alert(event.keyCode);
		if(event.keyCode == 0)
		{
			var index = Number(obj.posControl);
			alert("[" + Controles[index + 1] + "]");
			//document.getElementsById(Controles[index + 1]).focus();
		}
	}
	
	
/*
FIN Manejo de los tabs para toda la aplicacion
*/





/*****************************************************************/
/** Funcion Ocultar Validadores **********************************/
/** Objetivo: Oculta los controles de tipo RequiereFieldValidator*/
/**                                        CompareValidator ******/
/**                                        RangeValidator ********/
/**                                        RegularExpValidator ***/
/**                                        CustomValidator *******/
/** Creado por John Antonny Jaramillo (jjaramillo@intergrupo.com)*/
/*****************************************************************/
/******* INTERGRUPO S.A. TODOS LOS DERECHOS RESERVADOS (R)********/
/*****************************************************************/

function OcultarValidadores()
{	
	var elementosRFV = document.getElementsByTagName('span');
	var elementosVS = document.getElementsByTagName('div');
	
	var nombre;
	for (var i = 0; i < elementosRFV.length; i++)
	{
		nombre = elementosRFV.item(i).id.substring(0,3);
		if (nombre == 'rfv' || nombre == 'cov' || nombre.substring(0,2) == 'rv' || nombre == 'rev' || nombre == 'cuv' || nombre.substring(0,2) == 'uc')
		{
			if(nombre == 'ucCabezote_ddlNegocio' || nombre == 'ucCabezote_ddlAgenteCambio')
				elementosRFV.item(i).style.visibility = 'hidden';
		}
	}
					
	for (var i = 0; i < elementosVS.length; i++)
	{
		nombre = elementosVS.item(i).id.substring(0,2);
		if (nombre == 'vs')
			elementosVS.item(i).style.display = 'none';
	}				

}

/*function onPaste(){
	alert("sdasdsad")
	if(event.srcElement.type != "text" || event.srcElement.type != "textarea" || event.srcElement.type != "password"){
		var strClipboardData = new String(window.clipboardData.getData( "Text" ))
		alert(strClipboardData)
		if(event.srcElement.value == "<")
			return false;
	}
}*/
   

function onKeyDown(){
	//alert(event.keyCode);
	if ( (event.altKey) || ((event.keyCode == 8) && 
		(event.srcElement.type != "text" &&
		event.srcElement.type != "textarea" &&
		event.srcElement.type != "password")) || 
		((event.ctrlKey) && ((event.keyCode == 82)) ) ||
		(event.keyCode == 122) || (event.keyCode == 116) ) 
	{
		try{
			event.keyCode = 0;
			event.returnValue = false;
			return false;
		}catch(error){}
	}

	if((mouseLeft==2 || mouseLeft==3)){
		alert("Solicitud en Proceso...") 
		return false;
	}

    if (event.srcElement.tagName == "A" && window.event.shiftKey){
		return false;
    }

	if(event.srcElement.type != "text" || event.srcElement.type != "textarea" || event.srcElement.type != "password"){
		if(event.keyCode == 226)
			return false;
		if((event.ctrlKey) && (event.keyCode == 72))
			return false;
	}
	
	//desplazamiento vertical
	
	if(event.srcElement.type != "select-one" && event.srcElement.type != "textarea" && event.srcElement.type != "text" && event.srcElement.type != "radio"){
		if((event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40))
			return false;
		
	}
	
	var paste = new String(event.srcElement.onpaste);
	if(event.srcElement.type != "textarea" && event.ctrlKey && event.keyCode == 86 && paste.indexOf('false',0)==-1) {
		var seleccionado=document.selection.createRange(); 
		
		var strActual = new String(event.srcElement.value )
		var strClipboardData = new String(window.clipboardData.getData( "Text" ))
		
		if(strClipboardData.indexOf("<") != -1 || strClipboardData.indexOf(">") != -1 ){
			var strDato = new String(strActual.replace(seleccionado.text,"") + strClipboardData.replace("<","").replace(">",""));
			if(strDato.length > event.srcElement.maxLength){
				event.srcElement.value = strDato.substring(0,event.srcElement.maxLength);
			}else
				event.srcElement.value = strDato;
		}
		//return false;
	}
	else if(event.ctrlKey && event.keyCode == 86 && paste.indexOf('false',0)!=-1)
	{
		return false;
	}
	
	if((event.altKey && event.keyCode == 39) || (event.altKey && event.keyCode == 37)){
			return false;
		}
		else{
			if ( (( event.altKey) && (
					event.srcElement.type != "text" &&
					event.srcElement.type != "file" &&
					event.srcElement.type != "textarea" &&
					event.srcElement.type != "password")) ||
					((event.keyCode == 8) &&  (event.srcElement.type != "text" &&
					event.srcElement.type != "file" && 
					event.srcElement.type != "textarea" && 
					event.srcElement.type != "password")) ||
					((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82))) ||
					((event.keyCode == 8) &&  ((event.srcElement.type == "text" ||
						event.srcElement.type == "file" || 
						event.srcElement.type == "textarea" ||
						event.srcElement.type == "password")) && event.srcElement.getAttribute("readonly")) ||
					(event.keyCode == 113) ||
					(event.keyCode == 114) ||
					(event.keyCode == 115) ||
					(event.keyCode == 116) ||
					(event.keyCode == 117) ||
					(event.keyCode == 118) ||
					(event.keyCode == 119) ||
					(event.keyCode == 120) ||
					(event.keyCode == 121) ||
					(event.keyCode == 122) ||
					(event.keyCode == 123) ||
					(event.keyCode == 13 && event.srcElement.type == "select")
				){
					try{
						event.keyCode = 0;
						event.returnValue = false;
					}catch(error){}
				}
		}
		
}
	function modifcarEstadoMenu(mensaje){
		if(mensaje =="")
			estadoMensaje = "2";
		else{
			ClickSobreMenu = mensaje;
			estadoMensaje = "1";
		}
	
	}
	//mmlink
		//menu
	function hacerclickSobreMenu(){
		//invalidar menu
      if (event.srcElement.tagName == "A" && window.event.shiftKey){
		return false;
	  }

      if(estadoMensaje == ""){
			try{
				elemento = document.getElementById(event.srcElement.id);
				if (elemento!= null && 
				  elemento.id!= null && 
				  elemento.id.indexOf('mmlink') != -1 || 
				  elemento.id.indexOf('menu') != -1 && 
				  elemento.tagName == "A"){
					//alert("'" + elemento.tagName + "'");
					cLoadingIndicator_PreCallBack1();
				}
					
			}catch(error){}
		}
					
		try{
			if(estadoMensaje == "1"){
				elemento = document.getElementById(event.srcElement.id);
				if(elemento.id.indexOf('mmlink') != -1 || elemento.id.indexOf('menu') != -1){
					elemento.title = ClickSobreMenu;
					return false;
				}
			}
			//activar menu
			if(estadoMensaje == "2"){
				elemento = document.getElementById(event.srcElement.id);
				if(elemento.id.indexOf('mmlink') != -1 || elemento.id.indexOf('menu') != -1){
					elemento.title = "";
					estadoMensaje = "";
				}
			}
		}catch(error){}
		
		
		
	}
	
function MostrarFila(nombre,ver) 
{ 
	dis=ver?'':'none'; 
	document.getElementById(nombre).style.display = dis;
}

//Valida en el rango de fechas, si la fecha es requerida
//Invocado desde: Consultar histórico contratos
function ValidarFechaMod(source, arguments)
{
   var chkContratos = document.getElementById('UcFiltro_chkTodosContratos');
   var nombreControl = source.id + '_Calendario1_txtFecha';
   nombreControl = nombreControl.replace('rfv','');
   if (chkContratos.checked)
   {
	      var txtFecha = document.getElementById(nombreControl.toString());
	      if (txtFecha.value != "")
	      {
		      arguments.IsValid = true;
		   }
		   else
		   {
		      arguments.IsValid = false;
		   }
   }
   else
   {
      arguments.IsValid = true;
   }
}

function CerrarVentana()
{
	window.close();		
}	
//Habilita la validaión de requerido para el campo
//en Eventos Submercados
function ValidarGrupo() 
{
	var control = document.getElementById('UcAsociacionesGrupoDemanda1_rfvGrupo');
	control.enabled=true;
	Anthem_InvokePageMethod('ibtnAplicarAsociaciones_Click',null,function (result) {});
}
function AbrirHistoricoContrato(codigoSolicitud,codContrato)
{
	window.open("../Historial/DetalleHistorialContratoInfBasica.aspx?idSolicitud=" + codigoSolicitud +"&idContrato=" + codContrato + "&redirecciona=1", "FullScreen", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=640,height=480");	
}

function RedirectManual()
{
	cLoadingIndicator_PostCallBack();
	window.location="../Comun/DescargaManual.aspx";

}	
// funcion de trim para utilizar en strings.
function trimAll(sString) 
{
	return sString.replace(/^\s*/, "").replace(/\s*$/, ""); 
}

function cerrarSession(url){
	//var objWin = window.self;
	//var objPar = typeof(objWin.opener)=="undefined" ? objWin.dialogArguments : objWin.opener
	
	try
	{
		if(typeof(typeof(window.opener)=="undefined" ? window.dialogArguments : window.opener)!="undefined") 
		{ 
			var x_win = window.self; 
			while(x_win!="undefined") 
			{ 
				var x_winP = typeof(x_win.opener)=="undefined" ? x_win.dialogArguments : x_win.opener
				if(typeof(typeof(x_winP.opener)=="undefined" ? x_winP.dialogArguments : x_winP.opener)=="undefined")
				{
					x_win.close();
					x_winP.location.href=url;
					break; 
				}
				else{
					x_win.close();
					x_win = x_winP;
				}
			} 
		} 
		else 
		{ 
			window.location.href=url; 
		}
	}
	catch(e)
	{
		x_win.location.href=url;
	}	
}

//JMORA: Issue: 22064(Interno) Problema detectado al tipo de controles: FormattedNumberTextBoxAnthem
//Al pasar con tabulador por un campo de tarifa o de cantidad se espera
//que si el campo está seleccionado y se ingresa un nuevo valor el
//anterior se desaparezca, es el comportamiento normal de un campo
//seleccionado, en este caso el sistema ingresa los valores unos al
//principio y otros al final de la información que estaba en el campo y
//no elimina la que había. Situación que si sucede cuando se selecciona
//un campo con el Mouse
function fixOnKeyPressTextBoxAnthem(tb){
	if (tb!=null && tb.disabled==false)
	{
		tb.onkeypress = new Function("return OnlyNumbersOnePointKeyPressFixed(this,0); formatNumberKeyUp(this);");
		//tb.onkeypress = new Function("");
		//Lo que hace normalmente el control: FormattedNumberTextBoxAnthem
		//onkeypress="return OnlyNumbersOnePointKeyPress(this,0)"

		//tb.onkeypress="return OnlyNumbersOnePointKeyPressFixed(this,0); formatNumberKeyUp(this);";
	}
}

function OnlyNumbersOnePointKeyPressFixed(tb,signo)
{
	var key = '';
	var e = event;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	var strCheck = '0123456789.';
	if(signo == 1)strCheck = '0123456789.-';
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) < 0) return false;  // Not a valid key
	if (key == '.' && tb.value.indexOf('.') > -1) return false; //there is a point already
	if(signo == 1){
		if (key == '-' && tb.value.indexOf('-') > -1) 
			event.keyCode = 0; //there is a menos already
		else if(key == '-'){
			tb.value='-' + tb.value
			event.keyCode = 0;
		}
	}
	//formatNumberKeyUp(tb);
	//return true;
}

//JMORA: Issue: 4453 (Similar al 22064(Interno)) Problema detectado al tipo de controles: FormattedNumberTextBoxAnthem
//Este tipo de controles sobreescriben los eventos onpaste, onkeypress, etc.
function fixOnPasteTextBoxAnthem(tb){
	if (tb!=null && tb.disabled==false)
	{
		//alert(tb.getAttribute("onpaste"));
		tb.onpaste = new Function("");
		//Lo que hace normalmente el control: FormattedNumberTextBoxAnthem
		//onpaste="return OnlyNumbersOnePointPaste(this,1)"

		tb.onpaste="return false;";
		//alert(tb.getAttribute("onpaste"));
	}
}

function aplicarObjetoValor(strValor){
	document.getElementById("txtIDControlValue").value=strValor;
	//alert(strValor);
}

function resetearObjetoValor(txtIDControlValue){
	document.getElementById("txtIDControlFocus").value="";
}

function validarObjetoCambio(strIDObjeto, strValorActual){
	if (noValidar) {noValidar = false; return true};
	
	if (document.getElementById(strIDObjeto)==null) return;
	
	if (document.getElementById(strIDObjeto).value == document.getElementById("txtIDControlValue").value)
		return false
	else
		return true
}

//JMORA: Issue: 5233: 2008-08-12: Validación de terminación de sesion para los popups
function AplicarEstadoSesion(valor){
	if (document.getElementById('txtSessionClosed')==null) return;
	document.getElementById('txtSessionClosed').value = valor;
}

function ValidarEstadoSesion(){
	if (document.getElementById('txtSessionClosed')==null) return;
	return document.getElementById('txtSessionClosed').value;
}

function MostrarOcultarRequerido(strIdReq, strIdFecha, requerido)
{
	var req = document.getElementById(strIdReq);
	if (requerido == "true")
	{
		var fecha = document.getElementById(strIdFecha);
		if (fecha != null)
		{
			if (req != null)
			{
				if (fecha.value.length > 0)
				{
					req.style.visibility = "hidden";
					req.style.position = "absolute";
				}
				else
				{
					req.style.visibility = "";
					req.style.position = "relative";
				}
			}
		}
		else
		{
			if (req != null)
			{
				req.style.visibility = "hidden";
				req.style.position = "absolute";
			}
		}
	}
	else
	{
		if (req != null)
		{
			req.style.visibility = "hidden";
			req.style.position = "absolute";
		}
	}
}

document.onclick = hacerclickSobreMenu; 
document.oncontextmenu = nocontextmenu; 
document.onmousedown = norightclick; 
document.onkeydown = onKeyDown;

//Limpia las variables de sesion cuando se cambia en una opción del menú
//Limpia solamente las variables de sesion que no deben de permanecer en memoria mientras esté en ejecución la aplicación
//25-08-2008
function AbrirUrlMenu(strUrl)
{
	Anthem_InvokePageMethod(
		'LimpiarVariablesSesion',
		null,
		function(result) {
			window.location=strUrl;
			cLoadingIndicator_PreCallBack1();
		}
	);			
}

function openPopUpValidacionInicial(Texto)
{
	var variablesVentana = "dialogHeight:480px;dialogWidth:580px;help:no;resizable:no;status:no;center:yes";
	window.showModalDialog("PopUpValidacionInicial.aspx?txt=",self,variablesVentana);
	window.location.href = "../comun/logonMercadoSecundario.aspx";	
}

function establecerPermitirExportar(valor)
{
	permitirExportar = valor;
}

function permitirExportar()
{
	return permitirExportar;
}