function error(texto)
{
    alert(texto);
    window.close();
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



function writeFechaIni1(date) {
  document.form1.FECHA1.value=date;
}

function writeFechaFin1(date) {
  document.form1.FECHA2.value=date;
}

function trim(cadena){ 
	for(i=0; i<cadena.length; )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else break; 
	}
	for(i=cadena.length-1; i>=0; i=cadena.length-1)
	{
	if(cadena.charAt(i)==" ") cadena=cadena.substring(0,i);
	else break;
	}
	return cadena;
}

function anyoBisiesto(anyo)
	{	
        if (anyo < 100)
            var fin = anyo + 1900;
        else
            var fin = anyo ;

        if (fin % 4 != 0)
            return false;
        else
        {
            if (fin % 100 == 0)
            {
                if (fin % 400 == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }
    }

function validarFecha(fecha)
    {
       /**
       * obtenemos la fecha introducida y la separamos en dia, mes y año
       */
       
       
      var dia=fecha.value.split("/")[0];
      var mes=fecha.value.split("/")[1];
      var anyo=fecha.value.split("/")[2];

      
       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))
       {
           alert("El mes introducido no es valido. Por favor, introduzca un mes correcto");
           fecha.focus();
           fecha.select();
           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)))
       {
           alert("El dia introducido no es valido. Por favor, introduzca un dia correcto");
           fecha.focus();
           fecha.select();
           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)))
       {
           alert("El dia introducido no es valido. Por favor, introduzca un dia correcto");
           fecha.focus();
           fecha.select();
           return false;
       }
       /**
       * si el mes introducido es de 30 dias y el dia introducido es mayor de 301 > alertamos y detenemos ejecucion
       */
       if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30)))
       {
           alert("El dia introducido no es valido. Por favor, introduzca un dia correcto");
           fecha.focus();
           fecha.select();
           return false;
       }
       else
	  return true;
    }


function validarFormatoFecha(fecha){
	if(!/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/.test(fecha.value))
	{
		alert("Formato de fecha incorrecto dd/mm/aaaa");
		fecha.focus();
		return false;
	}
	return true;
}

function validarIntervaloFechas(fechaIni,fechaFin){
	if(!validarFormatoFecha(fechaIni)) return false;
	if(!validarFecha(fechaIni)) return false;
	if(!validarFormatoFecha(fechaFin)) return false;
	if(!validarFecha(fechaFin)) return false;
	fecha1=fechaIni.value.split("/")[2]+fechaIni.value.split("/")[1]+fechaIni.value.split("/")[0];
	fecha2=fechaFin.value.split("/")[2]+fechaFin.value.split("/")[1]+fechaFin.value.split("/")[0];
	if((parseInt(fecha1))>(parseInt(fecha2)))
	{
		alert("La fecha inicial tiene que ser anterior a la fecha de fin");
		fechaIni.focus();
		return false;
	}
	return true;
}

function validarFormatoAnno(anno){
	if(!/[0-9]{4}/.test(anno.value))
	{
		alert("Formato de año incorrecto aaaa");
		anno.focus();
		return false;
	}
	return true;
}

function esNumerico(campo){
	if(/\D/.test(campo.value))
	{
		alert("Debe introducir un valor numérico");
		campo.select();
		campo.focus();
		return false;
	}
	return true;
}

function esDecimal(campo){
        alert("PERRO");
	if(/\D[,\D]?/.test(campo.value))
	{
		alert("Debe introducir un valor decimal");
		campo.select();
		campo.focus();
		return false;
	}
	return true;
}


function tieneDato(campo){
	if(trim(campo.value)==""){
		alert("Debe introducir un valor");
		campo.focus();
		return false;
	}
	return true;
}

function testArea(area,max){
	if(area==null) 
		return;
	if(area.value.length>max){
		alert('No puede superar los '+max+' caracteres');
		area.value=area.value.substring(0,max);
	}
}

function validarFormatoHora(hora){
	if(!/[0-9]{2}:[0-9]{2}/.test(hora.value))
	{
		alert("Formato de hora incorrecto hh:mm");
		hora.focus();
		return false;
	}
	return true;
}

function validarHora(hora){
	if(!(validarFormatoHora(hora))) return;
        
        var h=hora.value.split(":")[0];
        var m=hora.value.split(":")[1];
        
        if(h>23){
        	alert("El valor máximo de HH es 23");
		hora.focus();
		return false;
        }
        if(m>59){
        	alert("El valor máximo de MM es 59");
		hora.focus();
		return false;
        }        
     	return true;
	
}

/**********************/
/* VALIDACIÓN CIF/NIF */
/**********************/

function validarNif(dni){
	var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
	var numero = dni%23;
	return letras.substring(numero,numero+1);
}
		
function comprobarDatosCif(cif) {
	var resul = false;
	var temp = cif.toUpperCase(); 		// pasar a mayúsculas
		
	if (!/^[A-Za-z0-9]{9}$/.test(temp)){  // Son 9 dígitos? 
		resul = false;
	}
	else{ 
		if (!/^[ABCDEFGHKLMNPQS]/.test(temp)){ // Es una letra de las admitidas ?
			resul = false;
		}
		else{
			resul = true;
		}
	}
	return resul;
}
	
function validarCif(cif)  { 
	var result = 0;	
  	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)); 

  	if( temp == 10 ) 
    	//alert( "El dígito de control es: J ó 0" ); 
    	result = "J";
  	else 
    	result =  temp; 
  	return result; 
}

//Esta función devuelve la url modificada que se pasa como parámetro, para que
//funcione acentos y ñ.
function generarURL(url){
  var temp=url;
  
  temp=temp.replace(/Ñ/g,'%D1');
  temp=temp.replace(/ñ/g,'%F1');
  temp=temp.replace(/Á/g,'%C1');
  temp=temp.replace(/á/g,'%E1');
  temp=temp.replace(/É/g,'%C9');
  temp=temp.replace(/é/g,'%E9');
  temp=temp.replace(/Í/g,'%CD');
  temp=temp.replace(/í/g,'%ED');
  temp=temp.replace(/Ó/g,'%D3');
  temp=temp.replace(/ó/g,'%F3');
  temp=temp.replace(/Ú/g,'%DA');
  temp=temp.replace(/ú/g,'%FA');

  return temp;
}

function validarIntervaloFechasMensaje(fechaIni,fechaFin,mensaje){
	if(!validarFormatoFecha(fechaIni)) return false;
	if(!validarFecha(fechaIni)) return false;
	if(!validarFormatoFecha(fechaFin)) return false;
	if(!validarFecha(fechaFin)) return false;
	fecha1=fechaIni.value.split("/")[2]+fechaIni.value.split("/")[1]+fechaIni.value.split("/")[0];
	fecha2=fechaFin.value.split("/")[2]+fechaFin.value.split("/")[1]+fechaFin.value.split("/")[0];
	if((parseInt(fecha1))>(parseInt(fecha2)))
	{
		alert(mensaje);
		fechaIni.focus();
		return false;
	}
	return true;
}


/* FUNCIONES AJAX */
function functionCallbackGenerica(llamadaAjax,div){
	document.body.style.cursor="progress";
// Comprobamos si la peticion se ha completado (estado 4)
	if( llamadaAjax.readyState == 4 )
	{
		// Comprobamos si la respuesta ha sido correcta (resultado HTTP 200)
		if( llamadaAjax.status == 200 )
		{
			// Escribimos el resultado en la pagina HTML mediante DHTML
			document.getElementById(div).innerHTML = llamadaAjax.responseText;							
		}
	}
	document.body.style.cursor="default";
}	

function functionCallbackPadre(llamadaAjax,div){
	document.body.style.cursor="progress";
// Comprobamos si la peticion se ha completado (estado 4)
	if( llamadaAjax.readyState == 4 )
	{
		// Comprobamos si la respuesta ha sido correcta (resultado HTTP 200)
		if( llamadaAjax.status == 200 )
		{
			// Escribimos el resultado en la pagina HTML mediante DHTML
			window.opener.document.getElementById(div).innerHTML = llamadaAjax.responseText;							
			window.close();
		}
	}
	document.body.style.cursor="default";
}

function llamaraAjax(urlCompleta,div,tiempo, sincrono, padre){	
	document.body.style.cursor="progress";
	// Creamos el control XMLHttpRequest segun el navegador en el que estemos 
	var funcion = "";
	var objetoAjax;
	var url = "";
	var parametros = "";

	// Para hacer una llamada Ajax por post, hemos de separar la url de los parámetros
	if (urlCompleta.indexOf('?') > -1){
		url = urlCompleta.substring(0,urlCompleta.indexOf('?'));
		parametros = urlCompleta.substring(urlCompleta.indexOf('?')+1,urlCompleta.length);
	}else{
		url = urlCompleta;
	}
	if( window.XMLHttpRequest )
		objetoAjax = new XMLHttpRequest(); // No Internet Explorer
	else
		objetoAjax = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
	
	// Almacenamos en el control al funcion que se invocara cuando la peticion
	// cambie de estado	
	
	if (padre != null && padre == true) {
		// estamos llamando desde un pop-up pero queremos que la salida vaya al padre
		//elem = window.opener.document.getElementById(div);
		objetoAjax.onreadystatechange = function() { functionCallbackPadre(objetoAjax,div); };
	} else
		// como siempre
		objetoAjax.onreadystatechange = function() { functionCallbackGenerica(objetoAjax,div); };

	// Enviamos la petición		

	if (sincrono != null)
		objetoAjax.open( "POST", url, sincrono );		
	else
		objetoAjax.open( "POST", url, true );
	
	objetoAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	objetoAjax.setRequestHeader("Content-length", parametros.length);
	objetoAjax.setRequestHeader("Connection", "close");
	
	window.setTimeout(function () {objetoAjax.send( parametros );}, tiempo);
	document.body.style.cursor="default";
	
}

function functionCallbackJavascript(llamadaAjax,div,nuevoScript){
	document.body.style.cursor="progress";
    if( llamadaAjax.readyState == 4 ){
	  if( llamadaAjax.status == 200 ){
			// Escribimos el resultado en la pagina HTML mediante DHTML
			//alert(llamadaAjax.responseText);
			scriptAux=document.createElement("script");
			scriptAux.text=llamadaAjax.responseText;
			
			if(nuevoScript==""){
				nuevoScript=scriptAux;
				document.getElementsByTagName('head')[0].appendChild(nuevoScript);
			}
			else{
				nuevoScript.text=scriptAux.text;
			}
	  }
    }
    document.body.style.cursor="default";
  }

function llamaraAjaxJavascript(urlCompleta,div,tiempo,nuevoScript){	
	// Creamos el control XMLHttpRequest segun el navegador en el que estemos 
	document.body.style.cursor="progress";
	var funcion = "";
	var objetoAjax;
	var url = "";
	var parametros = "";
	
	// Para hacer una llamada Ajax por post, hemos de separar la url de los parámetros
	if (urlCompleta.indexOf('?') > -1){
		url = urlCompleta.substring(0,urlCompleta.indexOf('?'));
		parametros = urlCompleta.substring(urlCompleta.indexOf('?')+1,urlCompleta.length);
	}else{
		url = urlCompleta;
	}
	if( window.XMLHttpRequest )
		objetoAjax = new XMLHttpRequest(); // No Internet Explorer
	else
		objetoAjax = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
	
	// Almacenamos en el control al funcion que se invocara cuando la peticion
	// cambie de estado	
	objetoAjax.onreadystatechange = function() { functionCallbackJavascript(objetoAjax,div,nuevoScript); };

	// Enviamos la petición				
	objetoAjax.open( "POST", url, true );
	objetoAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	objetoAjax.setRequestHeader("Content-length", parametros.length);
	objetoAjax.setRequestHeader("Connection", "close");
	window.setTimeout(function () {objetoAjax.send( parametros );}, tiempo);
	document.body.style.cursor="default";
}

function progreso() {
	document.getElementById("progresoCarga").innerHTML = "<div align='center' class='detatabla'>...:.. Subiendo Documento ..:...<br><img src='../comunes/img/barraCargando.gif' height='9' width='100'></div>";
}


// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
	cal.sel.value = date; // just update the date in the input field.

	if (cal.dateClicked)
	    cal.callCloseHandler();
}
	
// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
	if (cal.sel.onchange)
		cal.sel.onchange();
	cal.hide();                        // hide the calendar
	//cal.destroy();
	_dynarch_popupCalendar = null;
}
	
// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, id_donde) {

	var el = document.getElementById(id);
	if (_dynarch_popupCalendar != null) {
		// we already have some calendar created
	    _dynarch_popupCalendar.hide();                 // so we hide it first.
	} else {
	    // first-time call, create the calendar.
	    var cal = new Calendar(1, null, selected, closeHandler);
	    // uncomment the following line to hide the week numbers
	    cal.weekNumbers = true;
	    cal.showsTime = false;
	    cal.showsOtherMonths = true;
	    _dynarch_popupCalendar = cal;                  // remember it in the global var
	    cal.setRange(1900, 2070);        // min/max year allowed.
	    cal.create();
	}
	  
	_dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
	_dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
	_dynarch_popupCalendar.sel = el;                 // inform it what input field we use
	// the reference element that we pass to showAtElement is the button that
	// triggers the calendar.  In this example we align the calendar bottom-right
	// to the button.
	_dynarch_popupCalendar.showAtElement(document.getElementById(id_donde), "Br");        // show the calendar
	  
	return false;
}

function getRadioButtonSelectedValue(ctrl){
	for(i=0;i<ctrl.length;i++)
		if(ctrl[i].checked) return ctrl[i].value;
}

function nuevaVentana(url) {
	window.open(url,'_blank','');
}
function submitContacto() {
	if (document.getElementById("nombre").value =='') {
	   alert("El campo nombre no puede estar vacío.");
	   document.contacta.nombre.focus();
       return 0; 
	} else if (document.getElementById("apellidos").value =='') {
	   alert("El campo apellidos no puede estar vacío.");
	   document.contacta.apellidos.focus();
       return 0; 
	} else if (document.getElementById("email").value =='' || document.getElementById("email").value.indexOf('@') == -1) {
	   alert("El campo email no puede estar vacío y debe contener una dirección válida.");
	   document.contacta.email.focus();
       return 0; 
	} else if (document.getElementById("contenido").value =='') {
		alert("El campo contenido no puede estar vacío.");
		document.contacta.contenido.focus();
	    return 0; 
	} else {
		
		llamaraAjax('./jspComponents/dataManagement/insertarContacto.jsp?codigo='+document.getElementById("codigo").value+
					'&nombre='+document.getElementById("nombre").value+
					'&apellidos='+document.getElementById("apellidos").value+
					'&email='+document.getElementById("email").value+
					'&tipo='+document.getElementById("tipo").value+
					'&contenido='+document.getElementById("contenido").value, 'frameContenido');
		alert('Mensaje enviado correctamente.');
		document.contacta.nombre.value = '';
		document.contacta.apellidos.value = '';
		document.contacta.email.value = '';
		document.contacta.contenido.value = '';
		document.contacta.tipo.value = 1;
		return 1;
	}
	
}
