/*array para la validacion de fechas*/
var arrayNombreFecha = new Array();
/*arrays para la validacion de rangos de fechas*/
var arrayObjFechaInicio = new Array();
var arrayObjFechaFin = new Array();
var contFechas=0;
var contFechasTotal=0;

/*funciones para saber entre que campos hay que validar los rangos y las fechas a validar*/
function anadirComprobacion(nombreFecha){
	arrayNombreFecha[contFechasTotal] = nombreFecha;
	contFechasTotal++;
	if (nombreFecha.indexOf("Fin")!=-1){/*Se hace si es un campo de fecha Fin*/
		var nombreFechaFin = nombreFecha;
		var nombreFechaInicio = nombreFechaFin.replace("Fin","Inicio");
		if ( typeof( eval("document.forms[0].elements['Mostrar"+nombreFechaInicio+"']") )!='undefined' ){
			arrayObjFechaInicio[contFechas] = eval("document.forms[0].elements['Mostrar"+nombreFechaInicio+"']");
			arrayObjFechaFin[contFechas] = eval("document.forms[0].elements['Mostrar"+nombreFechaFin+"']");
			contFechas++;
		}	
	}
}

function comprobarFechas(){
	var ok=true;
	for (var i=0; i<arrayNombreFecha.length; i++ ){
		aux = validacionCampoFecha(arrayNombreFecha[i]);
		if (aux!=0 && aux!=3){
			ok = false;
		}
	}
	return ok;
}

function comprobarRangosFechas(){
	var ok=true;
	for (var i=0; i<arrayObjFechaInicio.length; i++ ){
		aux = validacionRango (arrayObjFechaInicio[i],arrayObjFechaFin[i],'_cast');
		if (aux!=0 && aux!=3){
			ok = false;
		}
	}
	return ok;
}

function ponCalendario(nombreCampo){
	var tope=((screen.height-200)/2)-25;
	var lefe=(screen.width-300)/2;
	window.open('ContentServer?pagename=UniversidadDeusto/admin/comun/calendario&campo='+escape(escape(nombreCampo)), 'calendario', 'width=190,height=153, screenX='+lefe+',left='+lefe+',screenY='+tope+',top='+tope+',scroll=no');
}
						
/*---------------------------------------------	VALIDACIONES ------------------------------------------------------------------------------------*/

// Comprueba que una cadena está vacía
function isEmpty(txt){
	return isLength(txt,0);
}

// Comprueba que la longitud máxima de una cadena sea n 
function isLength(txt,n){
	return (txt.length <= n)
}

function isNumero(txt){
	var reg = new RegExp("[^0-9]+");	
	return (!reg.test(txt));
}

function isTelefono(txt){
	return (isNumero(txt) && (txt.length >= 9 && txt.length <= 13 ));
}

// Comprueba si tiene formato de dirección e-mail
function isMail(email){
	var arr = email.indexOf('@');
	var pto = email.lastIndexOf('.');
	var longit = email.length;

	if(arr<1 || 
	   arr>(pto-2) ||
	   arr>(longit-5)) 
	   return false;
	var especial = true;
	var i= arr+1;
	for(; i<longit;i++){
		var c = email.charAt(i).toLowerCase();
		if((c>='0'&&c<='9') || (c>='a'&&c<='z')) 
			especial = false;
		else if(c=='-' || c=='.'){
			if(especial) 
				return false;
			especial = true; 
		}else 
			return false;
	}

	if(especial) 
		return false;	
	return true;
}


function isDNI(dni){
	var letra = dni.substring( dni.length-1, dni.length);
	var numero = dni.substring(0,dni.length-1);
	if (!isNumero(numero)){
		return false;
	}
	var d =(numero/23);
	d = Math.floor(d);
	var e=d*23;
	var r=numero-e;
	var correspondencia = new Array();
	correspondencia[0] = "T";
	correspondencia[1] = "R";
	correspondencia[2] = "W";
	correspondencia[3] = "A";
	correspondencia[4] = "G";
	correspondencia[5] = "M";
	correspondencia[6] = "Y";
	correspondencia[7] = "F";
	correspondencia[8] = "P";
	correspondencia[9] = "D";
	correspondencia[10] = "X";
	correspondencia[11] = "B";
	correspondencia[12] = "N";
	correspondencia[13] = "J";
	correspondencia[14] = "Z";
	correspondencia[15] = "S";
	correspondencia[16] = "Q";
	correspondencia[17] = "V";
	correspondencia[18] = "H";
	correspondencia[19] = "L";
	correspondencia[20] = "C";
	correspondencia[21] = "K";
	correspondencia[22] = "E";
	if ( (dni.length != 9) || correspondencia[r]!=letra.toUpperCase()) {
	 	return false;
	}
	return true;
}

function isFecha(date){
	fecha = trim(date);
	descomponerFechaString(fecha);
	return validacionDias(dia_mes_anyo[0],dia_mes_anyo[1],dia_mes_anyo[2]);
}


// Funcion que valida si un file de un formulario es correcto
function isFile(fichero){
	var extensionesPermitidas=new Array();
	extensionesPermitidas[0]=".txt";
	extensionesPermitidas[1]=".pdf";
	extensionesPermitidas[2]=".doc";
	extensionesPermitidas[3]=".htm";
	extensionesPermitidas[4]=".html";
	extensionesPermitidas[5]=".gif";
	extensionesPermitidas[6]=".jpg";
	extensionesPermitidas[7]=".jpeg";
	extensionesPermitidas[8]=".xls";
	extensionesPermitidas[9]=".ppt";
	extensionesPermitidas[10]=".bmp";
	extensionesPermitidas[11]=".png";

	// Validar la extension
	if (fichero.indexOf(".")==-1) {
		return false;
	}
	var ext=fichero.substr(fichero.lastIndexOf(".")).toLowerCase();
	var extensionPermitida=false;
	for (var i=0; i<extensionesPermitidas.length;i++)
	if (ext==extensionesPermitidas[i]){
		extensionPermitida=true;
		break;
	}

	return extensionPermitida;
}

/*
 Comprueba contiene caracteres numéricos.
 Entrada: cadena con el valor que se desea comprobar.
 Return: true: si el campo contiene exclusívamente caracteres numéricos.
		 false: en caso contrario.
*/
function esNumero(texto){	
	i=0;
	numero = trim(texto);
	
	while (i < numero.length ){
		if  ( (numero.charCodeAt(i)<48 ) || (numero.charCodeAt(i)>57 ) ){  
			return false;
		}
		i++;
	}
	return true;
}

/*
	Comprueba si un año es bisiesto	
	Entrada: el año que se desea testear
	Return: true: si es bisiesto
			false: si no lo es
*/
function anyoBisiesto(anyo){
	/** si el año introducido es de dos cifras lo pasamos al periodo de 1900. Ejemplo: 25 > 1925 */
	if (anyo < 100)
		var fin = anyo + 1900;
	else
		var fin = anyo ;

	/*
	* primera condicion: si el resto de dividir el año entre 4 no es cero > el año no es bisiesto
	* es decir, obtenemos año modulo 4, teniendo que cumplirse anyo mod(4)=0 para bisiesto
	*/
	if (fin % 4 != 0)
		return false;
	else{
		if (fin % 100 == 0){
			/** si el año es divisible por 4 y por 100 y divisible por 400 > es bisiesto */
			if (fin % 400 == 0){
				return true;
			}else{	
				/** si es divisible por 4 y por 100 pero no lo es por 400 > no es bisiesto */
				return false;
			}
		}else{
			/** si es divisible por 4 y no es divisible por 100 > el año es bisiesto */
			return true;
		}
	}
}

/*
	Comprueba si una fecha es anterior a otra 
	Entrada: objDate1: fecha que se quiere comprobar
			 objDate2: fecha con la que se quiere comparar
	Return: true: si es anterior
			false:si no es anterior
*/
function antes(objDate1,objDate2){
	if ( objDate1.getFullYear()  > objDate2.getFullYear() ){
		return false;
	}

	if ( objDate1.getFullYear()  < objDate2.getFullYear() ){
		return true;
	}

	if ( objDate1.getFullYear() == objDate2.getFullYear() ){
		if (objDate1.getMonth()  < objDate2.getMonth()){
			return true;
		}
		if (objDate1.getMonth()  >  objDate2.getMonth()){
			return false;
		}
		if (objDate1.getMonth() == objDate2.getMonth()){
			if (objDate1.getDate() <= objDate2.getDate()){
				return true;
			}else{
				return false;
			}
		}
	}
}

function descomponerFecha(objFecha,strIdioma){
	fecha = trim(objFecha.value);

	desgloseFecha = new Array();
	desgloseFecha = fecha.split("/");
	
	dia_mes_anyo = new Array();
	if (desgloseFecha.length!=3){
		desgloseFecha[0]="0";
		desgloseFecha[1]="0";
		desgloseFecha[2]="0";
	}
		
	if (strIdioma == "_eusk"){
		dia_mes_anyo[0] = trim(desgloseFecha[2]);
		dia_mes_anyo[1] = trim(desgloseFecha[1]);
		dia_mes_anyo[2] = trim(desgloseFecha[0]);
	}else{
		dia_mes_anyo[0] = trim(desgloseFecha[0]);
		dia_mes_anyo[1] = trim(desgloseFecha[1]);
		dia_mes_anyo[2] = trim(desgloseFecha[2]);
	}
	
	return dia_mes_anyo;
}

function descomponerFechaString(fecha){

	desgloseFecha = new Array();
	desgloseFecha = fecha.split("/");

	dia_mes_anyo = new Array();
	if (desgloseFecha.length!=3){
		desgloseFecha[0]="0";
		desgloseFecha[1]="0";
		desgloseFecha[2]="0";
	}
		
	if (strIdioma=="_cast"){
		dia_mes_anyo[0] = trim(desgloseFecha[0]);
		dia_mes_anyo[1] = trim(desgloseFecha[1]);
		dia_mes_anyo[2] = trim(desgloseFecha[2]);
	}else{
		dia_mes_anyo[0] = trim(desgloseFecha[2]);
		dia_mes_anyo[1] = trim(desgloseFecha[1]);
		dia_mes_anyo[2] = trim(desgloseFecha[0]);
	}

	return dia_mes_anyo;
}


/**
    Funcion principal de validacion de la fecha para campos separados de día, mes y año. 
	Comprueba la validez de una fecha desde el punto de vista de la coherencia de la misma y si se desea testea si se encuentra dentro de un rango.
	Si es incorrecta alerta y devuelve el foco al campo.
	Entrada: objFecha: campo con la fecha
			 strIdioma: campo con el idioma
 */

function descomponerFechaString2(fecha){
	desgloseFecha = new Array();
	desgloseFecha = fecha.split("/");
	

	dia_mes_anyo = new Array();
	if (desgloseFecha.length!=3){
		desgloseFecha[0]="0";
		desgloseFecha[1]="0";
		desgloseFecha[2]="0";
		dia_mes_anyo[0] = trim(desgloseFecha[0]);
		dia_mes_anyo[1] = trim(desgloseFecha[1]);
		dia_mes_anyo[2] = trim(desgloseFecha[2]);
		
	}else{
		dia_mes_anyo[0] = trim(desgloseFecha[0]);
		dia_mes_anyo[1] = trim(desgloseFecha[1]);
		dia_mes_anyo[2] = trim(desgloseFecha[2]);
		
	}

	return dia_mes_anyo;
}



 function validacionDias(diaObtenido,mesObtenido,anyoObtenido){
	
	dia = diaObtenido;
	mes = mesObtenido;
	anyo = anyoObtenido;

	if ( (typeof(dia)!='undefined')&&!(dia.length=="2") ){
		return 1;
	}
		
	if ( (typeof(mes)!='undefined')&&!(mes.length=="2") ){
		return 1;
	}
		
	if ( (typeof(anyo)!='undefined')&&!(anyo.length=="4") ){
		return 1;
	}
		
	if (!esNumero(dia)){
		return 1;
	}
		
	if (!esNumero(mes)){
		return 1;
	}
		
	if (!esNumero(anyo)){
		return 1;
	}
		
	if(anyoBisiesto(anyo))
	   febrero=29;
	else
	   febrero=28;

	/**
	 * si el mes introducido es negativo, 0 o mayor que 12 > alertamos y detenemos ejecucion
	 */
	if ((mes<1) || (mes>12)){
		return 1;
	}
		
	/**
	 * si el mes introducido es febrero y el dia es mayor que el correspondiente 
	 * al año introducido > alertamos y detenemos ejecucion
	 */
	if ((mes==2) && ((dia<1) || (dia>febrero))){
		return 1;
	}
		
	/**
	 * si el mes introducido es de 31 dias y el dia introducido es mayor de 31 > alertamos y detenemos ejecucion
	 */
	if (((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && ((dia<1) || (dia>31))){
		return 1;
	}
		
	/**
	 * si el mes introducido es de 30 dias y el dia introducido es mayor de 31 > alertamos y detenemos ejecucion
	 */
	if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30))){
		return 1;
	}
	
	return 0;
 }
 
 function validacionDias2(diaObtenido,mesObtenido,anyoObtenido){
	
	dia = diaObtenido;
	mes = mesObtenido;
	anyo = anyoObtenido;

	if ( (typeof(dia)!='undefined')&&!(dia.length=="2") ){
		return false;
	}
		
	if ( (typeof(mes)!='undefined')&&!(mes.length=="2") ){
		return false;
	}
		
	if ( (typeof(anyo)!='undefined')&&!(anyo.length=="4") ){
		return false;
	}
		
	if (!esNumero(dia)){
		return false;
	}
		
	if (!esNumero(mes)){
		return false;
	}
		
	if (!esNumero(anyo)){
		return false;
	}
		
	if(anyoBisiesto(anyo))
	   febrero=29;
	else
	   febrero=28;

	/**
	 * si el mes introducido es negativo, 0 o mayor que 12 > alertamos y detenemos ejecucion
	 */
	if ((mes<1) || (mes>12)){
		return false;
	}
		
	/**
	 * si el mes introducido es febrero y el dia es mayor que el correspondiente 
	 * al año introducido > alertamos y detenemos ejecucion
	 */
	if ((mes==2) && ((dia<1) || (dia>febrero))){
		return false;
	}
		
	/**
	 * si el mes introducido es de 31 dias y el dia introducido es mayor de 31 > alertamos y detenemos ejecucion
	 */
	if (((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && ((dia<1) || (dia>31))){
		return false;
	}
		
	/**
	 * si el mes introducido es de 30 dias y el dia introducido es mayor de 31 > alertamos y detenemos ejecucion
	 */
	if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30))){
		return false;
	}
	
	return true;
 }


 function validacion(objFecha,strIdioma){
	if (objFecha.value!=""){
		descomponerFecha(objFecha,strIdioma);
		return validacionDias(dia_mes_anyo[0],dia_mes_anyo[1],dia_mes_anyo[2]);
	}else{
		return 3;
	}
 }
 
 function isFecha(date){
	fecha = trim(date);
	descomponerFechaString(fecha);
	return validacionDias(dia_mes_anyo[0],dia_mes_anyo[1],dia_mes_anyo[2]);
 }

function isFecha2(date){
	
	fecha = trim(date);
	descomponerFechaString2(fecha);
	return validacionDias2(dia_mes_anyo[0],dia_mes_anyo[1],dia_mes_anyo[2]);

	
 }



 function validacionRango (objFechaInicio,objFechaFin,strIdioma){
	 if(objFechaInicio.value!="" && objFechaFin.value!=""){
		if ( validacion(objFechaInicio,strIdioma)==0 && validacion(objFechaFin,strIdioma)==0 ){
			descomponerFecha(objFechaInicio,strIdioma);
			objDateInicio = new Date (dia_mes_anyo[2],dia_mes_anyo[1],dia_mes_anyo[0]);
			
			descomponerFecha(objFechaFin,strIdioma);
			objDateFin = new Date (dia_mes_anyo[2],dia_mes_anyo[1],dia_mes_anyo[0]);
			
			if ( ! antes(objDateInicio,objDateFin) ){
				objFechaInicio.focus();
				alert('El rango de fechas señalado no es correcto');
				return 2;
			}
			return 0;
		 }else{
			return 1;
		 }
	 }else{
		return 3;
	 }
 }

 function validacionCampoFecha(nombreCampo){
	respuesta = validacion(eval("document.forms[0].elements['Mostrar"+nombreCampo+"']"),'_cast' );
	
	if (respuesta==0){	
		descomponerFecha(eval("document.forms[0].elements['Mostrar"+nombreCampo+"']"),'_cast');
		eval("document.forms[0].elements['"+nombreCampo+"']").value=dia_mes_anyo[2]+dia_mes_anyo[1]+dia_mes_anyo[0];
	}else if (respuesta==1){
		alert(nombreCampo+' erróneo');
		if ( eval("document.all.Capa"+nombreCampo+".style.visibility=='visible'") ){
			eval("document.forms[0].elements['Mostrar"+nombreCampo+"'].focus()");	
		}
	}else if (respuesta==3){
		eval("document.forms[0].elements['"+nombreCampo+"']").value="";
	}
	return respuesta;
 }

 function validacionAnteriorHoy (objFecha,objFechaHoy,strIdioma){
	    descomponerFecha(objFecha,strIdioma);
        objDate = new Date (dia_mes_anyo[2],dia_mes_anyo[1],dia_mes_anyo[0]);

        descomponerFecha(objFechaHoy,strIdioma);
        objDateHoy = new Date (dia_mes_anyo[2],dia_mes_anyo[1],dia_mes_anyo[0]);

        if ( ! antes(objDate,objDateHoy) || trim(objFecha.value)==""){
            return false;
        }
	    return true;

 }

 
 var cambio="no";
 function fncAbrirCambioRol(id){
	var resultado=window.showModalDialog('ContentServer?pagename=BBK/admin/solicitudes/cambioRol&#38;frID='+id, 'cambioRol', 'dialogWidth=350px;dialogHeight=150px;status=no;resizable=yes;scrollbars=no');
	if (resultado=="1"){
		window.showModalDialog('ContentServer?pagename=BBK/admin/solicitudes/existenSolWf', 'cambioRol', 'dialogWidth=350px;dialogHeight=150px;status=no;resizable=yes;scrollbars=no');
	}else{
		cambio="si";
		document.all.abrirCambio.style.visibility='hidden';
	}
 }
 
 function checkCombo(cambio){
	if (cambio=="no"){
		alert("No se permite cambiar el rol hasta que no Habilite esta propiedad. Haga click en el enlace: 'Habilitar cambio de rol'");
		document.all.Variables.AttrName.selectedIndex=Variables.indiceSeleccion;
	}
 }

 function trim(inputString) {
   /* Removes leading and trailing spaces from the passed string. Also removes
    consecutive spaces and replaces it with one space. If something besides
   a string is passed in (null, custom object, etc.) then return the input.*/
  
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { /* Check for spaces at the beginning of the string*/
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { /* Check for spaces at the end of the string*/
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { /* Note that there are two spaces in the string - look for multiple spaces within the string*/
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); /* Again, there are two spaces in each of the strings*/
   }
   return retValue; /* Return the trimmed string back to the user*/
} /* Ends the "trim" function*/

function chequearPadres(){
	if(typeof(document.forms[0].nombreParentDef)!="undefined"&&
		document.forms[0].nombreParentDef.value=='CategoriaPD'){
		var numParents = document.forms[0].elements['numParents'].value;
		/* Comprobar si existen padres */
		if (numParents==0){
			alert("No existen padres. Es obligatorio especificar un padre");
			return false;
		}

		/* totalTmpls: numero de posibles de padres que se muestran */
		var totalTmpls = document.forms[0].elements['totalParentTmpls'].value;
		var ordenPadres=new Array(totalTmpls);
		for (var i=1;i<=totalTmpls;i++){
			eval("var tipoPadre=document.forms[0].elements['_ParentDef_"+i+"_Info_'].value;");
			ordenPadres[tipoPadre.substring(tipoPadre.indexOf("CategoriaNivel")+14,tipoPadre.indexOf("CategoriaNivel")+15)]=i; 
		}

		var indicePadre=-1;
		var quitarValor = false;
		for (var i=(ordenPadres.length-1);i>=0;i--){
			if (eval("typeof(document.forms[0].elements['_ParentDef_"+ordenPadres[i]+"_SelectedParents_'])!='undefined'") && 
				eval("document.forms[0].elements['_ParentDef_"+ordenPadres[i]+"_SelectedParents_'].value!=''") ){
				if (!quitarValor){
					indicePadre=i;
					quitarValor = true;
				}else{
					eval("document.forms[0].elements['_ParentDef_"+ordenPadres[i]+"_SelectedParents_'].value='';");
				}
				
			}
		}
		if (indicePadre == -1){
			alert("Debes seleccionar algun padre");
			var i = totalTmpls;
			while ( eval("typeof(document.forms[0].elements['_ParentDef_"+i+"_SelectedParents_'])=='undefined'") && i>=0 ){
				i--;
			}
			if (i!=-1){
				eval("document.forms[0].elements['_ParentDef_"+i+"_SelectedParents_'].focus();");
			}
			return false;
		}
	}
	return true;
}

function getPosition(objid){
	var posXCapa="";
	var posYCapa="";
	if (document.all[objid]!=null){
		posXCapa=document.all[objid].offsetLeft;
		posYCapa=document.all[objid].offsetTop;
		parentEl = document.all[objid].offsetParent;
		while( parentEl != null){
			posXCapa+=parentEl.offsetLeft;
			posYCapa+=parentEl.offsetTop;
			parentEl =parentEl.offsetParent;
		}
	}
	var resultado=new Array(2);
	resultado[0]=posXCapa;
	resultado[1]=posYCapa;
	return resultado;
}




function verCapas(){
	if (typeof(document.all.cmbIdiomaEdicion)!="undefined"){
		var terminacionActiva=document.all.cmbIdiomaEdicion.value;
		for (var indice=0;indice<document.all.cmbIdiomaEdicion.options.length;indice++){
			eval("document.all.campos"+document.all.cmbIdiomaEdicion.options[indice].value+".style.visibility='hidden';");
		}
		eval("document.all.campos"+terminacionActiva+".style.visibility='visible';");
	}
}
function isFechaIdioma(date,idioma){

            descomponerFecha(date,idioma);

            return validacionDias(dia_mes_anyo[0],dia_mes_anyo[1],dia_mes_anyo[2]);

}

function isCIF(cif)
{
	var control =cif.substring( cif.length-1, cif.length);
	var numero;
	var org = cif.substring(0,1);
	if (!/^[ABCDEFGHKLMNPQS]/.test(org.toUpperCase())){
		return false;
	}else{
		numero = cif.substring(1,cif.length-1);	
	}
	if (!isNumero(numero))
	{
		return false;
	}
	if ((cif.length != 9))
	{
	 	return false;
	}

	var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
	var temp = 0; 
	var temp1;
  
	for( i = 2; i <= 6; i += 2 ) 
    {
      temp = temp + v1[ parseInt(cif.substr(i-1,1)) ];
      temp = temp + parseInt(cif.substr(i,1));
    };

	temp = temp + v1[ parseInt(cif.substr(7,1)) ];

	temp = (10 - ( temp % 10));

	var equivalencias = new Array ('A','B','C','D','E','F','G','H','I','J');

	if(isNumero(control)){
		if( temp == 10 ){
			if (control==0){
				return true;
			}else{
				return false;
			}
		}else{
			if (control==temp){
				return true;
			}else{
				return false;
			}
		}
	}else{
		if(control.toUpperCase() == equivalencias[temp-1]){
			return true;
		}else{
			return false;
		}
	}
	return true;
}


