//Muestra un tooltip en los items dentro de un
//dropdownlist
//---------------------------------------------------
function MostrarTooltip (idObject) 
{ 	
	var x = (window.Event) ? e.pageX : event.clientX;
	var y = (window.Event) ? e.pageY : event.clientY;
	var obj = document.getElementById( idObject ); 
	
	if(obj.selectedIndex != -1)
	{	
		document.getElementById("tooltip").innerHTML = obj.options[obj.selectedIndex].text;
		if(obj.options[obj.selectedIndex].value !="") 
		{
			//Formato Tooltip 			
			
 			document.getElementById("tooltip").style.zIndex = 9999999; 
  			document.getElementById("tooltip").style.display = "inline"; 
  			document.getElementById("tooltip").style.position = "absolute"; 
 			document.getElementById("tooltip").style.border =  "ActiveBorder  1px	solid"  ; 
			document.getElementById("tooltip").style.padding =   "3px"; 
			document.getElementById("tooltip").style.fontSize =  "10px"; 
			document.getElementById("tooltip").style.fontFamily = "Verdana"; 
			document.getElementById("tooltip").style.backgroundColor = "LemonChiffon"; 
			document.getElementById("tooltip").style.top = y + document.body.scrollTop; 
			document.getElementById("tooltip").style.left =	x;
			
		}      
	}
} 
//Oculta los tooltip de los imtems dentro de 
//un dropdownlist
//---------------------------------------------------
function OcultarTooltip ()
{ 
	document.getElementById("tooltip").style.display = "none"; 
}	

//Superpone los objetos calendarios
//---------------------------------------------------
function toggleContents1(strDiv, strFrame, strCalendar)
{
	//debugger;	   
	var div = document.getElementById(strDiv);
	if(div.style.display == 'none')
	{   		
		div.style.display = "";			
		document.getElementById(strFrame).style.height = document.getElementById(strCalendar).offsetHeight + 'px';//document.getElementById(strCalendar).style.height;
		document.getElementById(strFrame).style.width = document.getElementById(strCalendar).offsetWidth + 'px';//document.getElementById(strCalendar).style.width;
		return;
	}
	div.style.display = "none";
	document.getElementById(strFrame).style.height = '0';
}

//Valida el formato de las fechas en dd/mm/yyyy
//---------------------------------------------------
function validateDate(fld) 
{
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	//var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormay mm/dd/yyyy.';
	if ((fld.value.match(RegExPattern)) && (fld.value!='')) 
	{
		return true; 
	} 
	else 
	{
		return false;	
	} 
}

//Habilitamos y deshabilita controles
//---------------------------------------------------
function HibilitarDeshabilitarControles(controlsHabilita, controlsDeshabilita)
{
	//Habilitamos
	var arr = controlsHabilita.split('~');   
    for(var i=0; i < arr.length; i++)
    {	
		//alert(arr[i]);	
		document.getElementById(arr[i]).disabled = false;
    }
    //Deshabilitamos
    arr = controlsDeshabilita.split('~');   
    for(var i=0; i < arr.length; i++)
    {	
		document.getElementById(arr[i]).value = "";	
		document.getElementById(arr[i]).disabled = true;
    }
}


//Valida el formato de las fechas en dd/mm/yyyy
//--------------------------------------------------- 
function esFechaValida(fecha){


	if(fecha.value == "")
		{return true}
 
    if (fecha != undefined && fecha.value != "" ){
 
        if (!/^\d{2}\/\d{2}\/\d{4}$/.test(fecha.value)){
 
            //alert("formato de fecha no válido (dd/mm/aaaa)");
 
            return false;
 
        }
 
        var dia  =  parseInt(fecha.value.substring(0,2),10);
 
        var mes  =  parseInt(fecha.value.substring(3,5),10);
 
        var anio =  parseInt(fecha.value.substring(6),10);
 
 
 
    switch(mes){
 
        case 1:
 
        case 3:
 
        case 5:
 
        case 7:
 
        case 8:
 
        case 10:
 
        case 12:
 
            numDias=31;
 
            break;
 
        case 4: case 6: case 9: case 11:
 
            numDias=30;
 
            break;
 
        case 2:
 
            if (comprobarSiBisisesto(anio)){ numDias=29 }else{ numDias=28};
 
            break;
 
        default:
 
            //alert("Fecha introducida errónea");
 
            return false;
 
    }
 
 
 
        if (dia>numDias || dia==0){
 
            //alert("Fecha introducida errónea");
 
            return false;
 
        }
 
        return true;
 
    }
 
}
 
 
 
function comprobarSiBisisesto(anio){
 
if ( ( anio % 100 != 0) && ((anio % 4 == 0) || (anio % 400 == 0))) {
 
    return true;
 
    }
 
else {
 
    return false;
 
    }
 
}


//Comprobamos el rango de las fechas
//--------------------------------------------------- 
function comprobarRangoFechas(arrFechas)
{
	//debugger;
	var fecs = arrFechas.split("~");
	for(var i=1; i <= fecs.length - 1; i++)
	{		
		var arr = fecs[i-1].split("/");		
		var arr2 = fecs[i].split("/");
		
		
		//Comparamos los años
		if(arr[2] < arr2[2])
		{
			true;
		}
		else if( arr[2] == arr2[2])
		{
			//Comparamos los meses
			if(arr[1] < arr2[1])				
			{
				true;
			}
			else if(arr[1] == arr2[1])
			{
				//Comparamos los dias
				if(arr[0] <= arr2[0])
				{
					true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}	
		else 
		{
			return false;
		}
			
		
	}
	
	return true;
}


function ietruebody()
{
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(thetext, thecolor, thewidth, frame)
{	
	var obj =  document.getElementById(thetext)
	
	if(obj.selectedIndex != -1 && obj.options[obj.selectedIndex].text != "")
	{
		if (ns6||ie)
		{
			if (typeof thewidth!="undefined" && thewidth != "") tipobj.style.width=thewidth+"px"
			if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
			
			document.getElementById(frame).style.height = obj.offsetHeight + 'px' ;
			document.getElementById(frame).style.width = obj.offsetWidth +  'px';				
			
			//ToolTip
			tipobj.style.zIndex = 9999999; 
  			tipobj.style.display = "inline"; 
  			tipobj.style.position = "absolute"; 
 			tipobj.style.border =  "ActiveBorder  1px	solid"; 
			tipobj.style.padding =   "3px"; 
			tipobj.style.fontSize =  "10px"; 
			tipobj.style.fontFamily = "Verdana"; 
			tipobj.style.backgroundColor = "LemonChiffon"; 
			
			tipobj.style.width = 250 +"px";				
			tipobj.innerHTML=obj.options[obj.selectedIndex].text;
			
			enabletip=true			
			
		}
	}
	else
		enabletip=false
		
	return false
}

function positiontip(e)
{
	if (enabletip)
	{
		var curX=(ns6)?e.pageX : event.x+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.y+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
		var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<tipobj.offsetWidth)
			//move the horizontal position of the menu to the left by it's width
			tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
		else if (curX<leftedge)
			tipobj.style.left="5px"
		else
			//position the horizontal position of the menu where the mouse is positioned
			tipobj.style.left=curX+offsetxpoint+"px"

		//same concept with the vertical position
		if (bottomedge<tipobj.offsetHeight)
			tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
		else
			tipobj.style.top=curY+offsetypoint+"px"
		tipobj.style.visibility="visible"
	}
}

function hideddrivetip(frame)
{
	if (ns6||ie)
	{
		enabletip=false
		tipobj.style.visibility="hidden"
		tipobj.style.left="-1000px"
		tipobj.style.backgroundColor=''
		tipobj.style.width=''
		document.getElementById(frame).style.height = '0';
	}
}

//Devolvemos la fecha del sistema en un string
function GetFechaSistema()
{
	var dtSistema = new Date();
	var strSistema;
	var dia,mes,anno;
	
	anno = dtSistema.getFullYear();
	
	//El día
	if(dtSistema.getDate() > "9")
	{
		dia = dtSistema.getDate();
	}
	else
	{
		dia = "0" + dtSistema.getDate();
	}
	
	//El mes
	if(dtSistema.getMonth() >= "9")
	{
		mes = dtSistema.getMonth() + 1;
	}
	else
	{
		mes = "0" + (dtSistema.getMonth() + 1);
	}		
	
	return dia + "/" + mes + "/" + anno;
}

//Validamos la obligatoriedad de los campos del
//formulario a través de las etiquetas lblR
function ValidarFormulario(frm)
{
	
	var elementos = frm.elements;
	var correcto = true;		
	//debugger;	
	//for (var i=0; i < elementos.length; i++) 
	for (var i=elementos.length - 1; i > 0; i--) 
	{		
		//Validamos los campos obligatorios marcados con "lblR"
		if(elementos[i].id.indexOf("lblR") != -1)
		{		
			if(!CurruCucuc(elementos[i]))
				correcto = false;								
			
		}
		//Validamos los obligatorios que pueden estar ocultos marcados con "lblVR"
		else if(elementos[i].id.indexOf("lblVR") != -1)
		{
			var arr = elementos[i].id.split("_");			
			var obj =  document.getElementById(arr[1]);							
			if(obj.style.display == 'inline')
			{
				if(!CurruCucuc(elementos[i]))
					correcto = false;			
			}
							
		}
		//Validamos los campos que son numéricos marcados con "lblN"
		else if(elementos[i].id.indexOf("lblN") != -1)
		{	
			var obj = document.getElementById(elementos[i].id.substring(4));
			if(obj.value != "")
			{
				document.getElementById(elementos[i].id).style.display = "none";
				if(!IsNumeric(obj.value))
				{
					correcto = false;
					document.getElementById(elementos[i].id).style.display = 'inline';
					document.getElementById(elementos[i].id).innerText = "no se permiten letras.";
					try
					{
						obj.focus();
					}
					catch(err)
					{
					//Handle errors here
					}
				}				
			}
		}	
		//Validamos los campos alafanuméricos "lblA". Al menos un dato debe de ser número		
		else if(elementos[i].id.indexOf("lblA") != -1)
		{			
			document.getElementById(elementos[i].id).style.display = "none";
			var obj = document.getElementById(elementos[i].id.substring(4));
			if(obj.value != "")
			{
				if(!IsAlphaNumeric(obj.value))
				{
					correcto = false;
					document.getElementById(elementos[i].id).style.display = 'inline';	
					document.getElementById(elementos[i].id).value = "Datos alfanumericos";					
					try
					{
						obj.focus();
					}
					catch(err)
					{
					//Handle errors here
					}
				}				
			}
		}
		//Validamos formato email
		else if(elementos[i].id.indexOf("lblFC") != -1)
		{			
			document.getElementById(elementos[i].id).style.display = "none";
			var obj = document.getElementById(elementos[i].id.substring(5));
			
			if(obj.value != "")
			{
				//if(!ValidamosEmail(obj))
				if(!checkEmail(obj.value))
				{
					correcto = false;
					document.getElementById(elementos[i].id).style.display = 'inline';
					document.getElementById(elementos[i].id).innerText = "Formato xxx@xxx.xx";
					try
					{
						obj.focus();
					}
					catch(err)
					{
					//Handle errors here
					}
				}				
			}
			
							
		}					
		//Validamos el tipo de empresa	 
		else if(elementos[i].id.indexOf("lblSR") != -1)
		{			
			var arr = elementos[i].id.substring(5).split("__");
			var chk1, chk2;
			chk1 = document.getElementById(arr[0]);
			chk2 = document.getElementById(arr[1]);
			
			var lbl;
			lbl = document.getElementById(elementos[i].id);
			lbl .style.display = "none";
			if(!chk1.checked && !chk2.checked)
			{
				correcto = false;
				lbl.style.display = 'inline';
				lbl.innerText = '*';		
				try
				{
					lbl.focus();
				}
				catch(err)
				{
				//Handle errors here
				}
			}				
		}
		//Es un validador de un control
		else if(elementos[i].id.indexOf("lblCT") != -1)
		{	
			if(!CurruCucucControles(elementos[i]))
				correcto = false;
		}		
		//Validamos el campo que además de ser obligatorio tenga 5 caractéres
		else if(elementos[i].id.indexOf("3CR") != -1)
		{
			document.getElementById(elementos[i].id).style.display = "none";			
			var obj = document.getElementById(elementos[i].id.substring(0,elementos[i].id.length-3));
			
			if(obj.value.length != 3)
			{
				correcto = false;
				document.getElementById(elementos[i].id).style.display = 'inline';
				//document.getElementById(elementos[i].id).innerText = "3 caracteres obligatorios";
				try
				{
					obj.focus();
				}
				catch(err)
				{
				//Handle errors here
				}
			}									
		}	
		//Validadores dentro de controles
		else if(elementos[i].id.indexOf("ctrl") != -1 && elementos[i].id.indexOf("RRR") != -1)
		{							
			if(!CurruCucucControles(elementos[i]))
				correcto = false;
		}
    }   
    return correcto;
}

function CurruCucuc(obj1)
{
	var obj;
		
	if(obj1.id.indexOf("_") != -1)
		obj = document.getElementById(obj1.id.substring(5,obj1.id.indexOf("_")));
	else
		obj = document.getElementById(obj1.id.substring(4));

	return TiposDeObjeto(obj, obj1);		
}

function CurruCucucControles(obj1)
{
	var obj;
	
	if(obj1.id.indexOf("lblCT") == 0)
		obj = document.getElementById(obj1.id.substring(3));
	else if(obj1.id.indexOf("RRR") != -1)
		obj = document.getElementById(obj1.id.substring(0,obj1.id.length-3));
	else
	{
		var nombre = obj1.id.substring(0,obj1.id.indexOf("lblCT")) + obj1.id.substring(obj1.id.indexOf("lblCT")+5);
		obj = document.getElementById(nombre);
		if(obj == null)
			obj = document.getElementById(nombre.replace("dtg","tb"));
	}
		
	return TiposDeObjeto(obj, obj1);
}

function TiposDeObjeto(obj, obj1)	
{
	var correcto = true;
	
	//TextBox
	if(obj.id.indexOf("txt") != -1)		
	{
		if(obj.value == "")
			correcto = false;
	}
	//DropDownList
	else if(obj.id.indexOf("ddl") != -1)	
	{				
		if(obj.value == "" || obj.value == "0")
			correcto = false;
	}
	//Select
	else if(obj.id.indexOf("sel") != -1)	
	{
		if(obj.length == 0)
			correcto = false;
	}	
	//Tablas
	else if(obj.id.indexOf("dtg") != -1)	
	{	
		if(obj.rows.length <= 1)
			correcto = false;					
	}	
	else if(obj.id.indexOf("tb") != -1)
	{
		correcto = false;
	}
	
	try
	{
		if(!correcto)
		{
			obj1.style.display = 'inline';
			//Si ya tiene texto asociado el controlo se lo dejamos
			if(obj1.accessKey != "~")
				obj1.innerText = '*';
			obj.focus();
		}
		else
			obj1.style.display = "none";
	}
	catch(err)
	{
	//Handle errors here
	}
	
	return correcto;		
}

function isValidCif(texto)
{
	var pares = 0;
    var impares = 0;
    var suma;
    var ultima;
    var unumero;
    var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
    var xxx;
        
    texto = texto.toUpperCase();
    
    var regular = new RegExp(/^[ABCDEFGHJKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g);
        if (!regular.exec(texto)) return false;
            
        ultima = texto.substr(8,1);

        for (var cont = 1 ; cont < 7 ; cont ++){
            xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0";
            impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
            pares += parseInt(texto.substr(cont,1));
        }
        xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0";
        impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
        
        suma = (pares + impares).toString();
        unumero = parseInt(suma.substr(suma.length - 1, 1));
        unumero = (10 - unumero).toString();
        if(unumero == 10) unumero = 0;
        
        if ((ultima == unumero) || (ultima == uletra[unumero]))
            return true;
        else
            return false;


/*par = 0;

non = 0;

letras = "ABCDEFGHKLMNPQS";

let = abc.charAt(0);

 

if (abc.length!=9) {

//alert('El Cif debe tener 9 dígitos');

return false;

}

 

if (letras.indexOf(let.toUpperCase())==-1) {

//alert("El comienzo del Cif no es válido");

return false;

}

 

for (zz=2;zz<8;zz+=2) {

par = par+parseInt(abc.charAt(zz));

}

 

for (zz=1;zz<9;zz+=2) {

nn = 2*parseInt(abc.charAt(zz));

if (nn > 9) nn = 1+(nn-10);

non = non+nn;

}

 

parcial = par + non;

control = (10 - ( parcial % 10));

if (control==10) control=0;

 

if (control!=abc.charAt(8)) {

//alert("El Cif no es válido");

return false;

}

//alert("El Cif es válido");

return true;*/

}

function validarNIF(abc)
{
	dni = abc.substring(0,abc.length-1);
	let = abc.charAt(abc.length-1);
	if (!isNaN(let))
	{		
		return false;
	}
	else
	{
		cadena="TRWAGMYFPDXBNJZSQVHLCKET";
		posicion = dni % 23;
		letra = cadena.substring(posicion,posicion+1)
		if (letra!=let.toUpperCase())
		{					
			return false;
		}
	}
	return true;
}

//Función encargada de controlar los formatos y rangos de las fechas
function ChekeamosLasFechas(dtAutorizacion, dtVencimiento, dtRenovacion, dtInactivaBaja,
							lblFormato, lblRango, lblFormatoInactivaBaja, 
							lblRangoInactivaBaja, txtMotivoInactivoBaja, ddlInacBaja)
{
	var correcto = true;
	var arrFechas;

	if(esFechaValida(dtAutorizacion) && esFechaValida(dtVencimiento) && esFechaValida(dtRenovacion))
	{
		lblFormato.style.display = 'none';
		
		//Rango FA <= FS
		//---------------------------------------------------------
		arrFechas = dtAutorizacion.value + "~" + GetFechaSistema();
		if(comprobarRangoFechas(arrFechas))
		{
		
			//Rango FA <= FV <= FR
			//---------------------------------------------------------
			if(dtRenovacion.value != "" && dtVencimiento.value == "")
			{
				correcto = false;
				lblRango.style.display = 'inline';
				lblRango.innerText = 'Debes rellenar la fecha de vencimiento.';
			}
			else
			{				
				if(dtVencimiento.value != "" && dtRenovacion.value != "")
				{
					//Si se cimple FA <= FV <= FR
					arrFechas = dtAutorizacion.value + "~" + dtVencimiento.value + "~" + dtRenovacion.value;
					if(comprobarRangoFechas(arrFechas))
					{
						lblRango.style.display = 'none';
					}
					else
					{							
						correcto = false;
						lblRango.style.display = 'inline';
						lblRango.innerText = 'El rango de fechas no es correcto.';
					}
				}
				else if(dtVencimiento.value != "" && dtRenovacion.value == "")
				{
					//Si se cimple FA <= FV
					arrFechas = dtAutorizacion.value + "~" + dtVencimiento.value;
					if(comprobarRangoFechas(arrFechas))
					{
						lblRango.style.display = 'none';
					}
					else
					{							
						correcto = false;
						lblRango.style.display = 'inline';
						lblRango.innerText = 'El rango de fechas no es correcto.';
					}
				}
				else
					lblRango.style.display = 'none';
				
			}		
			
		}
		else
		{
			correcto = false;
			lblRango.style.display = 'inline';
			lblRango.innerText = 'El rango de fechas no es correcto.';
		}		
	}	
	else
	{
		correcto = false;
		lblFormato.style.display = 'inline';
		lblFormato.innerText = 'Datos erroneos';
	}
	
	//--------------------------------------------------------------------------------	
	if(ddlInacBaja != null && ddlInacBaja.value != 1)	
	{
		//Controlamos la obligatoriedad								
		if(dtInactivaBaja.value != "" && txtMotivoInactivoBaja.value != "")
		{
			if(esFechaValida(dtInactivaBaja))
			{
				//Si INACTIVIDAD
				if(ddlInacBaja.value == 3)
				{
					//Rango FA <= FI <= FS
					arrFechas = dtAutorizacion.value + "~" + dtInactivaBaja.value +	"~" +  GetFechaSistema();
									
					if(comprobarRangoFechas(arrFechas))
					{
						
							lblRangoInactivaBaja.style.display = 'none';						
					}
					else
					{
						correcto = false;
						lblRangoInactivaBaja.style.display = 'inline';
						lblRangoInactivaBaja.innerText = 'El rango de fechas no es correcto';
					}
				}
				//------------------------------------------------------------------------------
				//Si BAJA
				else if(ddlInacBaja.value == 2)
				{					
					arrFechas = dtAutorizacion.value + "~" + dtInactivaBaja.value +	"~" + GetFechaSistema();	
											
					if(comprobarRangoFechas(arrFechas))
					{
						lblRangoInactivaBaja.style.display = 'none';
					}
					else
					{
						correcto = false;
						lblRangoInactivaBaja.style.display = 'inline';
						lblRangoInactivaBaja.innerText = 'El rango de fechas no es correcto';
					}
				}
			}
			else
			{
				correcto = false;
				lblFormatoInactivaBaja.style.display = 'inline';
				lblFormatoInactivaBaja.innerText = 'Datos erroneos';
			}
			
		}
		else
		{
			correcto = false;
			lblFormatoInactivaBaja.style.display = 'inline';
			lblFormatoInactivaBaja.innerText = 'La fecha y el motivo son obligatorios.';	
		}
	}
	
	
	return correcto;

}

function ValidamosControlTitular(lblObligatoriedadTitular)
{	
	lblObligatoriedadTitular.style.display = 'none';
	
	var correcto = true;
	
	var nomControl = lblObligatoriedadTitular.id.substring(0,lblObligatoriedadTitular.id.indexOf("_"));
	var arr = lblObligatoriedadTitular.src.split("_");
	
	var nomTitular = document.getElementById(nomControl + "_" + arr[0]);
	var nifTitular = document.getElementById(nomControl + "_" + arr[1]);
	
	var razon = document.getElementById(nomControl + "_" + arr[2]);
	var cifEmpresa = document.getElementById(nomControl + "_" + arr[3]);
	var responsable = document.getElementById(nomControl + "_" + arr[4]);
	var nifResponsable = document.getElementById(nomControl + "_" + arr[5]);
	
	if(nomTitular.value == "" || nifTitular.value == "")
	{
		if(razon.value == "" || cifEmpresa.value == "" || responsable.value == "")
		{			
			lblObligatoriedadTitular.style.display = 'inline';
			lblObligatoriedadTitular.innerText = 'Debe cumplimentar los datos del Titular o Responsable.';
			try
			{
				lblObligatoriedadTitular.focus();
			}
			catch(err)
			{
			//Handle errors here
			}
			
			return false;
		}
	}			
		
	if(nifTitular.value != "")		
		if(!validarNIF(nifTitular.value))
			if(!isValidCif(nifTitular.value))
				correcto = false;
			
	if(cifEmpresa.value != "")		
		if(!isValidCif(cifEmpresa.value))
			correcto = false;	
			
	if(nifResponsable.value != "")		
		if(!validarNIF(nifResponsable.value))
			correcto = false;			
	
			
	if(correcto)
	{
		lblObligatoriedadTitular.style.display = 'none';
		return true;
	}
	else
	{		
		lblObligatoriedadTitular.style.display = 'inline';
		lblObligatoriedadTitular.innerText = 'NIF/CIF incorrecto.';
		try
		{
			lblObligatoriedadTitular.focus();
		}
		catch(err)
		{
		//Handle errors here
		}
		
		return false;
	}			
	
}


//Validamos el NIF Y CIF
function ValidamosTitular(nomTitular, nifTitular, razon, 
							nomResponsable, nifResponsable, lblTitular)
{
	var correcto = true;

	if((nomTitular.value != "" && nifTitular.value) || 
		(razon.value != "" && nomResponsable.value != "" && nifResponsable.value != ""))
	{
		//debugger;
		var nifCIF;
		
		nifCIF = nifTitular.value == "" ? nifResponsable.value : nifTitular.value;
		
		//Validamos NIF
		if(validarNIF(nifCIF))
		{
			lblTitular.style.display = 'none';
		}
		else
		{
			//debugger;
			//Validamos CIF
			if(isValidCif(nifCIF))
			{
				lblTitular.style.display = 'none';
			}
			else
			{
				correcto = false;
				lblTitular.style.display = 'inline';
				lblTitular.innerText = 'CIF o NIF incorrectos.';
				lblTitular.focus();
			}
		}
	}
	else
	{
		correcto = false;
		lblTitular.style.display = 'inline';
		lblTitular.innerText = 'Hay que rellenar los datos del titular o del responsable.';
		lblTitular.focus();
	}
	
	return correcto;
}

//Validamos el código postal
function ValidamosCP(cp, lblCP)
{
	var correcto = true;
	
	//Validamos el CP
	if(cp.value.length == 5)
	{
		lblCP.style.display = 'none';
	}
	else
	{
		correcto = false;
		lblCP.style.display = 'inline';
		lblCP.innerText = '5 caracteres';			
	}
	return correcto;
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
      }
      
   return IsNumber;
   
  }
function checkEmail(email)
{	
    var pattern=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    
    if(pattern.test(email))             
		return true;    
    else   
		return false;    
}

function ValidamosEmail(email) 
{
	//debugger;
	var a = email.value;
	var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+.[A-Za-z0-9_.]+[A-za-z]$/;
	
	//lblMes.style.display = 'none';
	
	if (a.length == 0 )
		return true;
		
	if (filter.test(a))
		return true;
	else
	{	
		//Mensaje de error de validación del correo electrónico
		//lblMes.innerText = 'Formato xxxx@xxxx.xx'
		//lblMes.style.display = 'inline';
		return false;
	}
}

function IsAlphaNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber = true;
   var Char;
 
   for (i = 0; i < sText.length; i++) 
      { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
		else
		{
			IsNumber = true;
			break;
		}
      }
      
   return IsNumber;
   
  }
  
function ValidNumerEnOnKeyPress(caractExtra)
{		
	tecla = event.keyCode;
	if(caractExtra != null)	
	{
		if(caractExtra.charCodeAt(0) == tecla)
		{
			event.returnValue = true;	
			return;
		}
	}	
	if ((tecla < 48 || tecla > 57) && tecla!=8 && tecla!=9 && tecla!=37 && tecla!=39)	
		event.returnValue = false;	
	
}

function MostrarOcultarDiv(elDiv)
{
	if(elDiv != null)
		elDiv.style.display == 'none' ? (elDiv.style.display = 'block') : ((elDiv.style.display = 'none'));
}
//Mostramos mensajes de alert segun el valor que recibimos
function MostramosAlerts(valor)
{
	if(valor == '56')
		alert("Seleccione la categoria de mayor riesgo para la que este  autorizado el establecimiento.");
		
	if(valor == '51')
		alert("Pueden utilizar subproductos procesados y sin procesar.");
}

function ClickEnterFoco(controlFoco)
{		
	tecla = event.keyCode;
	//debugger;
	if(tecla == 13)
	{
		controlFoco.click();					
		return false;
	}
}

function PlegarDesplegarDivs()
{
	arrObjeto = new Enumerator(document.all);
	for(arrObjeto.moveFirst(); !arrObjeto.atEnd(); arrObjeto.moveNext()) 
	{    		
		if(arrObjeto.item().id.indexOf("tbl") == 0)
			arrObjeto.item().style.display = document.getElementById("hnd" + arrObjeto.item().id).value;							
	}	
}

//Fuerza el evento click de boton enviar, cuando se pulsa un enter en alguna caja de texto
function noenter(nomBtn) 
{
	if (window.event && window.event.keyCode == 13)
	{
		ClickEnterFoco(document.getElementById(nomBtn));
		return !(window.event && window.event.keyCode == 13);
	}
	else
		return true;			
}

//Deshabilita la tecla pulsda excepto el tabulador
function DeshabilitarTeclasPulsadas(evt, obj)
{
	var charCode = (evt.which) ? evt.which : evt.keyCode																		
	if (charCode != 9)
			return false;
			
	return true;
}