
	var dtCh= "/";
	var minYear=2000;  
	var maxYear=2050;
	
	
	function esNumerico(string) {
		var Chars = "0123456789";
	
		for (var i = 0; i < string.length; i++) {
			if (Chars.indexOf(string.charAt(i)) == -1) {
				return false;
			}
		}
		return true;
	}
	
	
	function isInteger(s){
		var i;
	    for (i = 0; i < s.length; i++){   
	        // Check that current character is number.
	        var c = s.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }
	    // All characters are numbers.
	    return true;
	}
	
	function stripCharsInBag(s, bag){
		var i;
	    var returnString = "";
	    // Search through string's characters one by one.
	    // If character is not in bag, append to returnString.
	    for (i = 0; i < s.length; i++){   
	        var c = s.charAt(i);
	        if (bag.indexOf(c) == -1) returnString += c;
	    }
	    return returnString;
	}
	
	function daysInFebruary (year){
		// February has 29 days in any year evenly divisible by four,
	    // EXCEPT for centurial years which are not also divisible by 400.
	    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}

	function DaysArray(n) {
		for (var i = 1; i <= n; i++) {
			this[i] = 31;
			if (i==4 || i==6 || i==9 || i==11) {
				this[i] = 30;
			}
			if (i==2) {
				this[i] = 29;
			}
	   } 
	   return this
	}
	
	function isDate(dtStr){
	
		// La fecha no es obligatoria
		if (dtStr == "") {
			return true;
		}
		
		var daysInMonth = DaysArray(12);
		var pos1 = dtStr.indexOf(dtCh);
		var pos2 = dtStr.indexOf(dtCh,pos1+1);
		var strDay = dtStr.substring(0,pos1);
		var strMonth = dtStr.substring(pos1+1,pos2);
		var strYear = dtStr.substring(pos2+1);
		strYr = strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) {
			strDay = strDay.substring(1);
		}
		if (strMonth.charAt(0)=="0" && strMonth.length>1) {
			strMonth = strMonth.substring(1);
		}
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) {
				strYr = strYr.substring(1);
			}
		}
		month = parseInt(strMonth);
		day = parseInt(strDay);
		year = parseInt(strYr);
		if (pos1==-1 || pos2==-1) {
			alert("El formato de la fecha debe ser: dd/mm/aaaa");
			return false;
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			alert("Introduzca un día válido");
			return false;
		}
		if (strMonth.length<1 || month<1 || month>12) {
			alert("Introduzca un mes válido");
			return false;
		}
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			alert("El año debe estar comprendido entre " + minYear + " y " + maxYear);
			return false;
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			alert("Por favor, introduzca una fecha correcta");
			return false;
		}
		return true;
	}
	
	// Comparar fechas
	function dateDiff(d1,d2) {
	  	var dt1 = new Date(d1);
        	var dt2 = new Date(d2)
      
      		if ((d1 == "") || (d2 == "" )) {
      			return true;
      		}
      		alert("dt1.getTime(): " + dt1.getTime());
      		alert("dt2.getTime(): " + dt2.getTime());
      		
		diffMilli = dt2.getTime() - dt1.getTime();
		//alert("diff: " + diffMilli);
		if (Math.round(diffMilli/(1000*60*60*24))>=0) {
			return true;
		} else {
			return false;
		}
	}
	
	// Compara dos fechas en formato dd/mm/aaaa
	function dateIsBefore(date1, date2) {
		
		// Las fechas no son obligatorias
		if ((date1 == "") || (date2 == "" )) {
      		return false;
      	}
      		
		var pos1 = date1.indexOf(dtCh);
		var pos2 = date2.indexOf(dtCh,pos1+1);
		var strDay1 = date1.substring(0,pos1);
		var strMonth1 = date1.substring(pos1+1,pos2);
		var strYear1 = date1.substring(pos2+1);
		var strDay2 = date2.substring(0,pos1);
		var strMonth2 = date2.substring(pos1+1,pos2);
		var strYear2 = date2.substring(pos2+1);
		
		// Reordenamos la fecha en formato mm/dd/aaaa
		ndate1 = strMonth1 + "/" + strDay1 + "/" + strYear1;
		ndate2 = strMonth2 + "/" + strDay2 + "/" + strYear2;
		
		var d1 = new Date(ndate1);
		var d2 = new Date(ndate2);
		if (d1 <= d2) {
			//alert(d1 + " es menor que " + d2 + " (true)");
			return false;
		} else {
			//alert(d1 + " es mayor que " + d2 + " (false)");
			return true;
		} 
	}
	
	function nuevo(form, pagDestino) {
		form.p.value = pagDestino;
		form.submit();
	}
	 
	function modificar(form, pagDestino) {
	
		contadorElementosPulsados = 0;
		NumChecked = form.elements.length;
  		// Contar el número de elementos seleccionados en el formulario
  		for (i=0; i < NumChecked; i++) {
	     	if ((form.elements[i].type == 'checkbox') && (form.elements[i].name != 'detallado') && (form.elements[i].checked == 1)) {
	     		// Almacenamos el código del elemento seleccionado
				selectedCod = form.elements[i].name;
				contadorElementosPulsados++;
	     	}
  		}
  		if (contadorElementosPulsados == 0) {
        	alert('Debe seleccionar una fila');
  		} else if (contadorElementosPulsados > 1) {
        	alert('Debe seleccionar sólo una fila');
  		} else {
  			form.selectedCod.value = selectedCod;
  			form.p.value = pagDestino;
  			form.submit();
  		}
 	
 	}

	function borrar(form, pagDestino) {
	
		contadorElementosPulsados = 0;
		listaBorrar = "";
		NumChecked = form.elements.length;
  		// Contar el número de elementos seleccionados en el formulario
  		for (i=0; i < NumChecked; i++) {
	     	if ((form.elements[i].type == 'checkbox') && (form.elements[i].checked == 1)) {
				var selectedCod = form.elements[i].name;
				listaBorrar = listaBorrar + "," + selectedCod;
				contadorElementosPulsados++;
	     	}
  		}
  		if (contadorElementosPulsados < 1) {
        	alert('Debe seleccionar al menos una fila');
		} else {
 			if (confirm('¿Está seguro de que desea borrar estos elementos?')) {
		 		form.selectedCod.value = listaBorrar.substring(1, listaBorrar.length);
		 		form.p.value = pagDestino;
		 		form.submit();
   			}
  		}
 	
 	}
 	
 	function enviarSeleccionados(form, pagDestino) {
		var listaSeleccionados = "";
		contadorElementosPulsados = 0;		
		NumChecked = form.elements.length;
  		// Contar el número de elementos seleccionados en el formulario
  		for (i=0; i < NumChecked; i++) {
	     	if ((form.elements[i].type == 'checkbox') && (form.elements[i].checked == 1)) {
				var selectedCod = form.elements[i].name;
				listaSeleccionados = listaSeleccionados + "," + selectedCod;
				contadorElementosPulsados++;
	     	}
  		}
  		if (contadorElementosPulsados < 1) {
        	alert('Debe seleccionar al menos una fila');
		} else {
 			if (confirm('¿Está seguro de que desea copiar estos elementos?')) {
		 		form.selectedCod.value = listaSeleccionados.substring(1, listaSeleccionados.length);
		 		form.p.value = pagDestino;
		 		form.submit();
   			}
  		}
 	
 	}


    function correo(form, pagDestino) {
	
		contadorElementosPulsados = 0;
		listaEnviar = "";
		NumChecked = form.elements.length;
  		// Contar el número de elementos seleccionados en el formulario
  		for (i=0; i < NumChecked; i++) {
	     	if ((form.elements[i].type == 'checkbox') && (form.elements[i].checked == 1)) {
				var selectedCod = form.elements[i].name;
				listaEnviar = listaEnviar + "," + selectedCod;
				contadorElementosPulsados++;
	     	}
  		}
  		if (contadorElementosPulsados < 1) {
        	alert('Debe seleccionar al menos una fila');
		} else {
		 	form.selectedCod.value = listaEnviar.substring(1, listaEnviar.length);
		 	form.p.value = pagDestino;
		 	form.submit();
  		}
 	
 	}
 
  
	function selectMultiple(form,nombreSelectMultiple,nombreCampoCadena,permiteVacio) {

		contadorElementosPulsados = 0;
		listaSeleccionados = "";
	   	if (form.elements[nombreSelectMultiple].type == 'select-multiple') {
			for (j=0; j < form.elements[nombreSelectMultiple].length; j++) {
				if (form.elements[nombreSelectMultiple].options[j].selected) {
					listaSeleccionados = listaSeleccionados + ',' + form.elements[nombreSelectMultiple].options[j].value;
					contadorElementosPulsados++;							
				}
			}
	    }
  		if (!permiteVacio && contadorElementosPulsados == 0) {
       		return false;
  		} else {
  			form.elements[nombreCampoCadena].value = listaSeleccionados.substring(1, listaSeleccionados.length);
  			return true;
  		}
 	
 	}
 	
    function isTextAreaMultipleExcesivo(formulario,campo,longitudMaxima) {

		var f= formulario.elements;
	    
		for (i=0; i < f.length; i++){
			if (igual(f[i].name,campo)) {
				if ((f[i].value.length)>longitudMaxima) {
					 f[i].focus();
					return true;
				}
			}
		}
		return false;
    }
 	
    /**
     * Tamaño de la cadena, contando los retornos de carro, que la función length solo los calcula con 1 (en java son 2).
     */
    stringLength = function(str) {
    	 if (!str)
    		 return 0;
    	 else
    		 return str.length + (str.split(/\r/).length - 1) + (str.split(/\n/).length - 1);
    };

    
	function contadoresCaracteres(objCampo, idEscritos, idRestantes, maximo) {			
		//n = objCampo.value.length +	(objCampo.value.split(/\r/).length - 1) + (objCampo.value.split(/\n/).length - 1);
		n = stringLength(objCampo.value);

		
		if (n > maximo) {
			objCampo.value = objCampo.value.substring(0,objCampo.value.length - (n-maximo));
			n=maximo;
		}
		
		escritos = document.getElementById(idEscritos);
		if(escritos != null){
			escritos.value = n;
		}

	    restantes = document.getElementById(idRestantes);
	    if(restantes != null){
	    	restantes.value = (maximo - n);
	    }
	}
 	

  //----------------------------------------------------------------------------------------------------------------
  
	function vacioRadio(form,nombreRadio){
  
		vacio= true;
		for (j=0; j < form.elements[nombreRadio].length; j++) {
			if ( (form.elements[nombreRadio][j].checked) ) { 
            	vacio= false;     
        	}
     	}      
     	return vacio;
  
	}
  
  //----------------------------------------------------------------------------------------------------------------
  
	function vacioSelect(form,nombreSelect){
  
		vacio= false;
		if ( (form.elements[nombreSelect].value == '') ) { 
			vacio= true;     
	 	}     
		return vacio;

	}
  
 //---------------------------------------------------------------------------------------------------------------------
 
	function selectIdiomaDefecto(form,listaIdioma,defecto){
 
		valido= false;
		for (j=0; j < form.elements[listaIdioma].length; j++) {
			if (form.elements[listaIdioma][j].value == defecto) {
				return form.elements[listaIdioma][j].selected;
			}
		}
	
	} 
 
 //---------------------------------------------------------------------------------------------------------------------
  
	function selectIdioma(form,listaIdioma,nombreIdiomaDefecto) {

		valido= false;
		for (j=0; j < form.elements[listaIdioma].length; j++) {
		   if ((form.elements[nombreIdiomaDefecto].value) == (form.elements[listaIdioma][j].value) &&
		       (form.elements[listaIdioma][j].selected) ) {
				valido= true;
			}
		}
		return valido;

	}

 //-----------------------------------------------------------------------------------------------------------------
 
	function tieneBlancos(palabra){
   
		for (j=0; j < palabra.length; j++) {
			if (palabra.charAt(j) == " ") {
				return true;
			}   
		}
		return false;      
   
	}

 //-----------------------------------------------------------------------------------------------------------------

	function esVacioMultiple(form,campo){
    
		for (j=0; j < form.elements[campo].length; j++) {
			if (form.elements[campo][j].selected) {
				return false;
			}
		}
		return true;
	
	}

 //-----------------------------------------------------------------------------------------------------------------  
	function replace(cadena,caracter1,caracter2){
 
		salida = "";
		for ( i=0;i<cadena.length;i++ ){
			if ( cadena.charAt(i) == caracter1 ) {
				salida = salida + caracter2;
			} else {
				salida = salida + cadena.charAt(i);
			}
		}
		return salida;

	}	

//---------------------------------------------------------------------------------------------------------------------

	function esNulo(campo){
		if ( replace(campo.value,' ','').length == 0 ) { 
			return true;
		} else {
			return false;
		}
	}

//-------------------------------------------------------------------------------------------------------------------

	function trim(str) { 
		var st1 = str.replace(/^\s*/, ''); 
		var st2 = st1.replace(/\s*$/, '');

		return st2;
	} 

//--------------------------------------------------------------------------------------------------------------------

	function crearVentana(nombreFormulario,nombreCampo,pagina,nombre,opciones){
		ventana= window.open(pagina+"&nomFormulario="+nombreFormulario+"&nomCampo="+nombreCampo,nombre,opciones);
	}

//--------------------------------------------------------------------------------------------------------------------

	function abrirPopPup(pagina,nombre,opciones){
		ventana = window.open(pagina,nombre,opciones);
	}


//---------------------------------------------------------------------------------------------------------------------

	function escribirValor(nombreFormulario,nombreCampo,valor) {
		opener.document.forms[nombreFormulario].elements[nombreCampo].value=valor;
		window.close();
	}


   
//----------------------------------------------------------------------------------------------------------------------

	function igual(campo1,campo2){

		for (j=0; j<campo2.length; j++){
			if (campo1.charAt(j) != campo2.charAt(j)) {
				return false;
			}
		}
		return (campo1.charAt(j) == "."); 
   
	}
	
	function endWith(campo1,campo2){
		
		if (campo1.length<campo2.length) return false;
		k1 = campo1.length;
		k2 = campo2.length;

		for (j=1;j<=k2; j++){

			if (campo1.charAt(k1-j) != campo2.charAt(k2-j)) {
				return false;
			}
		}
		return true; 
   
	}
	
	
//----------------------------------------------------------------------------------------------------------------------

	function igualValor(campo1,campo2){
	
		if (campo1.length != campo2.length){
		   return false;
		}
		
		for (j=0; j<campo1.length; j++){
			if (campo1.charAt(j) != campo2.charAt(j)) {
				return false;
			}
		}
		return true; 
   
	}

//----------------------------------------------------------------------------------------------------------------------

	function igualCampo(campo1,campo2){

		if (campo1.length != campo2.length) {
			return false;
		} else {   
			for (j=0; j<campo2.length; j++) { 
				if (campo1.charAt(j) != campo2.charAt(j)) { 
					return false;
				}
			}
		}
  
		return true; 
   
	}
	
//----------------------------------------------------------------------------------------------------------------------

	
	function isMultiple(formulario,campo){
	
		var f= formulario.elements;
	    
		for (i=0; i < f.length; i++){
	     
			if (igual(f[i].name,campo)) {
				if (trim(f[i].value)== "") {
					return false;
				}
			}
		}
		return true;
	
	}

//------------------------------------------------------------------------------------------------------------------------

	function isDistintas(clave1,clave2) {
		return (clave1 != clave2);
	}


//------------------------------------------------------------------------------------------------------------------------
	function isPrecio(precio) {
		var exp_precio = /^\s*\d+(,\d+)?\s*$/;
		return exp_precio.test(precio);
	}

//------------------------------------------------------------------------------------------------------------------------
	function isPorcent(porcent) {
		var exp_porcent = /^\s*\d\d?(,\d+)?\s*$/;
		return exp_porcent.test(porcent);
	}

//------------------------------------------------------------------------------------------------------------------------
	function isDecimal(decimal) {
		var exp_decimal = /^\s*\d\d?(,\d+)?\s*$/;
		return exp_decimal.test(decimal);
	}

//------------------------------------------------------------------------------------------------------------------------

	function isPrecioMultiple(formulario,campo,permiteVacio){

		var f= formulario.elements;
		var regexp_decimal = /^\s*\d+(,\d+)?\s*$/;
 
		for (i=0; i < f.length; i++) {
			if (igual(f[i].name,campo)) {
				if (!permiteVacio || f[i].value!='') {
					if (!regexp_decimal.test(f[i].value)) {
						alert('El precio '+f[i].value+' no es válido');		     
						f[i].focus();
						f[i].select();
						return false;	  	
					}
				}
			}
		}
	
		return true;
	
	}   

//------------------------------------------------------------------------------------------------------------------------

	function isCotaMultiple(formulario,campo,permiteVacio){

		var f= formulario.elements;
		var regexp_decimal = /^\s*\d+(,\d+)?\s*$/;
 
 		for (i=0; i < f.length; i++) {
			if (igualCampo(f[i].name,campo)) {
				if (!permiteVacio || f[i].value!='') {
					if (!regexp_decimal.test(f[i].value)) {
						alert('La cota '+f[i].value+' no es válida');		     
						f[i].focus();
						f[i].select();
						return false;	  	
					}
				}
			}
		}
	
		return true;
	
	}
	
//------------------------------------------------------------------------------------------------------------------------

	function isValorMultiple(formulario,campo,permiteVacio){

		var f= formulario.elements;
		var regexp_decimal = /^\s*\d+(,\d+)?\s*$/;
 
		for (i=0; i < f.length; i++) {
			if (igualCampo(f[i].name,campo)) {
				if (!permiteVacio || f[i].value!='') {
					if (!regexp_decimal.test(f[i].value)) {
						alert('El valor '+f[i].value+' no es válido');		     
						f[i].focus();
						f[i].select();
						return false;	  	
					}
				}
			}
		}
	
		return true;
	
	}
//------------------------------------------------------------------------------------------------------------------------

	function isPorcentMultiple(formulario,campo,permiteVacio){
	
		var f= formulario.elements;
		var regexp_decimal = /^\s*\d\d?(,\d+)?\s*$/;
 
		for (i=0; i < f.length; i++) {
			if (igual(f[i].name,campo)) {
				if (!permiteVacio || f[i].value!='') {
					if (!regexp_decimal.test(f[i].value)) {
						f[i].focus();
						alert('El porcentaje '+f[i].value+' no es válido');
						return false;	  	
					}
				}
			}
		}

		return true;
	
	}  

//------------------------------------------------------------------------------------------------------------------------

	function ChequearTodos(chkbox){

		for (var i=0;i < document.forms[0].elements.length;i++){
			var elemento = document.forms[0].elements[i];
			if (elemento.type == "checkbox") {
				elemento.checked = chkbox.checked
			}
		}
	}

//----------------------------------------------------------------------------------------------------------------------

	function igualGrupo(campo1,campo2){
		
		
		ik=0;
		
		if ((campo1.charAt(0) == 'p') && (campo1.charAt(1) == 'r') && (campo1.charAt(2) == 'e') && (campo1.charAt(3) == 'c') && (campo1.charAt(4) == 'i') && (campo1.charAt(5) == 'o')){
			j=7;
			for (j=7; j<campo1.length; j++) {
			    if (campo1.charAt(j) != campo2.charAt(ik)){
			        return false;
			    }
			    ik++;
			}
		
		}else{
		   return false;
		}
		
		return true;
		     
	}


//------------------------------------------------------------------------------------------------------------------------

	function comprobarPrecioGrupo(formulario,grupo){

		var f= formulario.elements;
		var valor='-1';
		
		for (i=0; i < f.length; i++){
			
			if (igualGrupo(f[i].name,grupo)){
				
				if (f[i].value == ''){
				   alert('El precio asignado al grupo base no puede estar vacío ');
				   return false;
			   	}
				
			}
		}
		return true;
		
	}
	

//------------------------------------------------------------------------------------------------------------------------

function comprobarListaEmail(cadenaMail){

   /* Inicialización de las variables*/
       var i= 0;
       var mail= "";
   
   /* Extraemos los correos de la cadena de correos */
       while (i <= cadenaMail.length ){
            if (cadenaMail.charAt(i) == ','){
                if (!validarEmail(mail)){
                  return false;
               }
               
               mail= "";
            }else{
               if (cadenaMail.charAt(i) != ' '){
                    mail= mail + cadenaMail.charAt(i);
               }     
            }
            i++;   
       }
     
  /* Comprobamos el ultimo correo */
      if (!validarEmail(mail)){
         return false;
      }
       
      return true;
       

}	

//------------------------------------------------------------------------------------------------------------------------

	function validarEmail(emailStr){

		/* Verificar si el email tiene el formato user@dominio. */
		var emailPat=/^(.+)@(.+)$/ 
		
		/* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" 
		
		/* Verifica los caracteres que son válidos en una dirección de email */
		var validChars="\[^\\s" + specialChars + "\]" 
		
		var quotedUser="(\"[^\"]*\")" 
		
		/* Verifica si la dirección de email está representada con una dirección IP Válida */ 
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
		
		/* Verificar caracteres inválidos */ 
		var atom=validChars + '+'
		var word="(" + atom + "|" + quotedUser + ")"
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
		  
		//domain, as opposed to ipDomainPat, shown above. 
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
		
		var matchArray=emailStr.match(emailPat)
		
		if (matchArray==null) {
			//alert("La direcci-on de email no parece ser correcta")
			return(false); 
		}
		var user=matchArray[1]
		var domain=matchArray[2]
		
		// Si el user "user" es valido 
		if (user.match(userPat)==null) {
			// Si no
			//alert("La dirección de email no parece ser correcta")
			return(false);
		}
		
		// Si la dirección IP es válida 
		var IPArray=domain.match(ipDomainPat)
		
		if (IPArray!=null) {
			for (var i=1;i<=4;i++) {
				if (IPArray[i]>255) {
					//alert("La dirección de email no parece ser correcta")
					return(false);
				}
			}
			return(true);
		}
		
		var domainArray=domain.match(domainPat)
		if (domainArray==null) {
			//alert("La dirección de email no parece ser correcta")
			return(false);
		}
		
		var atomPat=new RegExp(atom,"g")
		var domArr=domain.match(atomPat)
		var len=domArr.length
		if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) { 
			//alert("La dirección de email no parece ser correcta")
			return(false);
		}
		
		if (len<2) {
			var errStr="La dirección de email no parece ser correcta"
			//alert(errStr)
			return(false);
		}
		
		// La dirección de email es valida
		return(true);

	}

