// PLOU
// Me comprueba la cantidad de caracteres en un textarea y tal
function jsCuenta(campo,maxvalor){
if (document.getElementById(campo).value.length<=(maxvalor-1))
	document.getElementById("char"+campo).value=document.getElementById(campo).value.length;
else{
	alert ("Maximun characters exceeded at "+document.getElementById(campo).title);
	document.getElementById(campo).value = document.getElementById(campo).value.substring(0,maxvalor) ;
	document.getElementById("char"+campo).value=document.getElementById(campo).value.length;
	return false;
	}
}
// VALIDAR CORREOS
function emilio(contcorreo){
        //compruebo el emilio
                var correo=contcorreo;
                var fallo_correo = 0;
                var pos = correo.indexOf("@");
                
                if (pos == -1){
                        equivoc=1;
                        fallo_correo = 1;
                }
        
        //compruebo q tenga al menos 1 carácter antes y después de le arroba y el punto
                if ((pos == 0)||(pos == correo.length-1)) {
                        equivoc=1;
                        fallo_correo = 1;
                }
                
                var pos2 = correo.lastIndexOf(".");
                if((pos2 < pos+1)||(pos2 == correo.length-1)){
                        equivoc=1;
                        fallo_correo = 1;        
                }

                for (i=0; i<correo.length; i++){
                        if (correo.charAt(i)==" ") {
                        equivoc=1;
                        fallo_correo = 1;
                        }
                }
                
                if (fallo_correo==1){
                        //msje+="Se requiere una dirección de correo válida.\n";
						return false;
                }
}
// VALIDAR FECHAS
function valida_fecha(field){
        //compruebo la fecha mientras la mete el usuario
		var checkstr = "0123456789";
        var DateField = field;
        var Datevalue = "";
        var DateTemp = "";
        var seperator = "/";
        var day;
        var month;
        var year;
        var leap = 0;
        var err = 0;
        var i;
	   err = 0;
   DateValue = DateField.value;
   /* borra todos los caracteres excepto 0..9 */
   for (i = 0; i < DateValue.length; i++) {
          if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
             DateTemp = DateTemp + DateValue.substr(i,1);
          }
   }
   DateValue = DateTemp;
   /* Siempre cambio la fecha a 8 dígitos - cadena */
   /* si el año tiene 2 digitos/ se asume 20xx */
   if (DateValue.length == 6) {
      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
   if (DateValue.length != 8) {
      err = 19;}
   /* año incorrecto si es = 0000 */
   year = DateValue.substr(4,4);
   if (year == 0) {
      err = 20;
   }
   /* valido mes*/
   month = DateValue.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* valido día*/
   day = DateValue.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* validación de año bisiesto */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* validacion de otros meses */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* Si se mete 00, directamente borro */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
	if ((isNaN(day)==true) || (isNaN(month)==true) || (isNaN(year)==true)){
		err = 27;
		return false;
	}
   /* si no hay error, lo meto en el campo */
   if (err == 0) {
      DateField.value = day + seperator + month + seperator + year;
   }
   /* Si el error es != 0 , mensaje */
   else {
	return false;
   }
}
// PARA SUBIDA DE IMAGENES
extArray = new Array('jpg','jpeg','gif','png','bmp'); // <---- Extensiones válidas
function extension(file) {
	allowSubmit = false;
	if (!file) return;
	file = file.slice(file.lastIndexOf("\\")+1);
	// Sacamos el nombre del archivo (y solucionamos bug Opera 6)
	if (file.indexOf('"') != -1) {
		var archivo = file.substring(0,file.indexOf('"'));
		file = file.substring(0,file.indexOf('"'));
	} else {
		var archivo = file;
	}
	// Sacamos la extension del archivo y la pasamos a minusculas
	file = file.slice(file.lastIndexOf(".")+1);
	var ext = file.toLowerCase();
	// Comparamos con los elementos del array
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { 
			allowSubmit = true;
			break;
		}
	}
	// Si la extension no es válida, avisamos	
	if (!allowSubmit) {
		alert("Se permiten únicamente archivos de imagen con la extensión:\n" + (extArray.join(", ")) + "\n\nEl archivo " + archivo + " no es válido. Por favor, seleccione otro archivo e intente de nuevo.");
		allowSubmit = false;
		}
	return allowSubmit;
}
// PARA SUBIDA DE ARCHIVOS
extArray2 = new Array('pdf','doc','word','rtf','xls','jpg','jpeg','gif','png', 'bmp', 'zip', 'rar', 'pps', 'ppt' ); // <---- Extensiones válidas
function extension2(file) {
	allowSubmit = false;
	if (!file) return;
	file = file.slice(file.lastIndexOf("\\")+1);
	// Sacamos el nombre del archivo (y solucionamos bug Opera 6)
	if (file.indexOf('"') != -1) {
		var archivo = file.substring(0,file.indexOf('"'));
		file = file.substring(0,file.indexOf('"'));
	} else {
		var archivo = file;
	}
	// Sacamos la extension del archivo y la pasamos a minusculas
	file = file.slice(file.lastIndexOf(".")+1);
	var ext = file.toLowerCase();
	// Comparamos con los elementos del array
	for (var i = 0; i < extArray2.length; i++) {
		if (extArray2[i] == ext) { 
			allowSubmit = true;
			break;
		}
	}
	// Si la extension no es válida, avisamos	
	if (!allowSubmit) {
		alert("Se permiten únicamente archivos de documentación con la extensión:\n" + (extArray2.join(", ")) + "\n\nEl archivo " + archivo + " no es válido. Por favor, seleccione otro archivo e intente de nuevo.");
		allowSubmit = false;
		}
	return allowSubmit;
}
// FIN PLOU
//funcion encarga de crear el objeto, que se usará para ajax
function http_request(){
	try{
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}catch (e) {
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch (E){
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp
}
function valida_login(){
	_objetus=http_request()
	//Obtengo los valores del formulario a enviar
	_user=document.getElementById('user').value
	_pass=document.getElementById('pass').value
	//obtengo el nombre de la etiqueta que mostrará las alertas
	_target=document.getElementById('mensaje')
	//variables a enviar
	_values_send="nada=nada&user="+_user+"&pass="+_pass
	//url de destino
	_URL_="./includes/valida.php?"
	//Método de envío
	_objetus.open("POST",_URL_,true);
	//Líonea necesaria si se envía por POST, envío de las cabeceras
	_objetus.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	//adjuntamos las variables que se enviaran
	_objetus.send('&'+_values_send);
	// El manejador del evento llamado en cada cambio de estado del objeto
	_objetus.onreadystatechange=function(){
		// Entero que indica el estado del objeto
		//(0=sin inicializar, 1=cargando, 2=fin de la carga, 3=actualizando la información, 4=Operación completada)
		if (_objetus.readyState==1){
			_target.innerHTML="<p class=alerta><img src=./images/cargando.gif alt=alerta width=16 height=16 /> Comprobando.......</p>";
		}else if(_objetus.readyState==4){
			// 404 si la página no se encuentra,200 si todo ha ido bien, etc.
			if(_objetus.status==200){
				if(_objetus.responseText==" verdad" || _objetus.responseText=="verdad"){
					document.location.href="./contenido.php";
				}else{
					_target.innerHTML = _objetus.responseText;
				}
			}else{
				_target.innerHTML = "Error: "._objetus.status;
			}
		}
	}
	_objetus.send(null);
	//return
}

function limpiarURL(){
	_target=document.getElementById('mensaje')
	_target.innerHTML="";
}

function nuevoAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
} 

function eliminaEspacios(cadena)
{
	while(cadena.charAt(cadena.length-1)==" ") cadena=cadena.substr(0, cadena.length-1);
	while(cadena.charAt(0)==" ") cadena=cadena.substr(1, cadena.length-1);
	return cadena;
}

function cargaDatos(elemento)
{
	var valor=document.getElementById("input_"+elemento).value;

	// Elimino todos los espacios en blanco al principio y al final de la cadena
	valor=eliminaEspacios(valor);
	
	// Valido con una expresion regular el contenido de lo que el usuario ingresa
	var reg=/(^[a-zA-Z0-9._áéíóúñ¡!¿? -]{1,30}$)/;
	if(!reg.test(valor)) 
	{ 
		// Si hay error muestro el div que contiene el error
		document.getElementById("error").style.display="block";
	}
	else
	{
		// Si no hay error oculto el div (por si se mostraba) y procedo a guardar los datos
		document.getElementById("error").style.display="none";
		document.getElementById("fila_"+elemento).innerHTML=valor;
	
		ajax=nuevoAjax();
		ajax.open("GET", "ingreso_sin_recargar_proceso.asp?dato="+valor+"&actualizar="+elemento, true);			
		ajax.send(null);
	}
}


function creaInput(elemento)
{
	/* Funcion encargada de cambiar el texto comun de la fila por un campo input que conserve
	el valor que tenia ese campo */
	if(!document.getElementById("input_"+elemento) && document.getElementById("error").style.display!="block")
	{
		/* Solo mostramos el input si ya no esta siendo mostrado y si ademas el div del error no
		esta en pantalla */
		var fila=document.getElementById("fila_"+elemento);
		fila.innerHTML="<input onBlur=\"cargaDatos('"+elemento+"')\" value=\""+fila.innerHTML+"\" id='input_"+elemento+"' type='text' class='form'>";
		document.getElementById("input_"+elemento).focus();
	}
}

function ConfBorr(direccion,titular){
	if (confirm(titular)){
		window.location = direccion
	}	
}

<!--
function CargarFoto(img, ancho, alto){
derecha=(screen.width-ancho)/2;
arriba=(screen.height-alto)/2;
string="toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+ancho+",height="+alto+",left="+derecha+",top="+arriba+"";
fin=window.open(img,"",string);
}

function muestra_logo(misource){
	misourcearray = misource.split('\\');
	misource=misourcearray.join('/');
	misourcearray = misource.split(':');
	misource=misourcearray.join('|');
	misourcearray = misource.split(' ');
	misource=misourcearray.join('%20');	
	
	document.form1.logotipo.src="file:///"+misource;
}

//función que permite la transparencia de los archivos png en el pxxx explorer

function PNG_loader() {
   for(var i=0; i<document.images.length; i++) {
      var img = document.images[i];
      var imgName = img.src.toUpperCase();
      if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
         var imgID = (img.id) ? "id='" + img.id + "' " : "";
         var imgClass = (img.className) ? "class='" + img.className + "' " : "";
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
         var imgStyle = "display:inline-block;" + img.style.cssText;
         if (img.align == "left") imgStyle += "float:left;";
         if (img.align == "right") imgStyle += "float:right;";
         if (img.parentElement.href) imgStyle += "cursor:hand;";
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
         img.outerHTML = strNewHTML;
         i--;
      }
   }
}
//window.attachEvent("onload", PNG_loader);

// función para iluminar las celdas del menu en el evento onmouseover
function fondoIluminado(objeto) {
objeto.className = "subcategoriamenuover";
}

// función para establecer el fondo de la celda tras el evento onmouseout
function fondoFijo(objeto) {
objeto.className = "subcategoriamenu";
}

//función para cambiar el color de fondo de los elementos de formulario
function cambiaFondo(objeto) {
objeto.style.backgroundColor = "#dedede";
}

//función para abrir una ventana centrada (popup)
function abreVentanaCentradaScroll(url, ancho, alto) {
var izquierda = (screen.width - ancho ) / 2;
var arriba = (screen.height - alto ) / 2;	
window.open(url, null, "top =" + arriba + ",left=" + izquierda + ",width=" + ancho + ",height=" + alto + ",scrollbars=yes");
}

//función para abrir una ventana centrada (popup)
function abreVentanaCentrada(url, ancho, alto) {
var izquierda = (screen.width - ancho ) / 2;
var arriba = (screen.height - alto ) / 2;	
window.open(url, null, "top =" + arriba + ",left=" + izquierda + ",width=" + ancho + ",height=" + alto );
}

//función para abrir una imagen centrada (popup)
function abrirImagen(ancho,alto,direccion){   
   var top;
   var left;
   top=(window.screen.height-alto)/2;
   left=(window.screen.width-ancho)/2
   
   var contenido;   
   contenido="<html><head>";
   contenido+="<title>Royal Classics</title>";
   contenido+="</head>";
   contenido+="<body style='margin:0px;' scroll='no'>";
   contenido+="<img src="+direccion+">";   
   contenido+="</body>";
   contenido+="</html>";
   var popup;
   popup=window.open("","popup","width="+ancho+", height="+alto+", top="+top+", left="+left+"");
   popup.document.write(contenido);
  }
  
  //función para abrir un .swf centrado (Flash)
  function abrirFlash(alto,ancho,direccion){   
   var top;
   var left;
   top=(window.screen.height-alto)/2;
   left=(window.screen.width-ancho)/2
   
   var contenido;   
   contenido="<html><head>";
   contenido+="<title>Royal Classics</title>";
   contenido+="</head>";
   contenido+="<body style='margin:0px'>";
   contenido+="<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='"+ancho+"' height='"+alto+"'>" 
   contenido+="<param name='movie' value='"+direccion+"'>";
   contenido+="<param name='quality' value='high'>";
   contenido+="<embed src='"+direccion+"' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='"+ancho+"' height='"+alto+"'></embed>";
   contenido+="</object>";
   contenido+="</body>";
   contenido+="</html>";
   var popup;
   popup=window.open("","popup","width="+ancho+", height="+alto+", top="+top+", left="+left+"");
   popup.document.write(contenido);
  }
// JavaScript Document

//validacion de la fecha
function esDigito(sChr){
var sCod = sChr.charCodeAt(0);
return ((sCod > 47) && (sCod < 58));
}

function valSep(oTxt){
var bOk = false;
bOk = bOk || ((oTxt.value.charAt(2) == "-") && (oTxt.value.charAt(5) == "-"));
bOk = bOk || ((oTxt.value.charAt(2) == "/") && (oTxt.value.charAt(5) == "/"));
return bOk;
}

function finMes(oTxt){
var nMes = parseInt(oTxt.value.substr(3, 2), 10);
var nRes = 0;
switch (nMes){
case 1: nRes = 31; break;
case 2: nRes = 29; break;
case 3: nRes = 31; break;
case 4: nRes = 30; break;
case 5: nRes = 31; break;
case 6: nRes = 30; break;
case 7: nRes = 31; break;
case 8: nRes = 31; break;
case 9: nRes = 30; break;
case 10: nRes = 31; break;
case 11: nRes = 30; break;
case 12: nRes = 31; break;
}
return nRes;
}

function valDia(oTxt){
var bOk = false;
var nDia = parseInt(oTxt.value.substr(0, 2), 10);
bOk = bOk || ((nDia >= 1) && (nDia <= finMes(oTxt)));
return bOk;
}

function valMes(oTxt){
var bOk = false;
var nMes = parseInt(oTxt.value.substr(3, 2), 10);
bOk = bOk || ((nMes >= 1) && (nMes <= 12));
return bOk;
}

function valAno(oTxt){
var bOk = true;
var nAno = oTxt.value.substr(6);
bOk = bOk && ((nAno.length == 2) || (nAno.length == 4));
if (bOk){
for (var i = 0; i < nAno.length; i++){
bOk = bOk && esDigito(nAno.charAt(i));
}
}
return bOk;
}

function valFecha(oTxt){
var bOk = true;
if (oTxt.value != ""){
bOk = bOk && (valAno(oTxt));
bOk = bOk && (valMes(oTxt));
bOk = bOk && (valDia(oTxt));
bOk = bOk && (valSep(oTxt));
if (!bOk){
alert("Fecha incorrecta");
oTxt.value = "";
oTxt.focus();
}
}
}
function move(fbox, tbox) {
	fbox = document.getElementById(fbox);
	tbox = document.getElementById(tbox);
	
	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	for (i = 0; i < tbox.options.length; i++) {
	arrLookup[tbox.options[i].text] = tbox.options[i].value;
	arrTbox[i] = tbox.options[i].text;
	}
	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
	arrLookup[fbox.options[i].text] = fbox.options[i].value;
	if (fbox.options[i].selected && fbox.options[i].value != "") {
	arrTbox[tLength] = fbox.options[i].text;
	tLength++;
	}
	else {
	arrFbox[fLength] = fbox.options[i].text;
	fLength++;
	   }
	}
	arrFbox.sort();
	arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;
	var c;
	for(c = 0; c < arrFbox.length; c++) {
	var no = new Option();
	no.value = arrLookup[arrFbox[c]];
	no.text = arrFbox[c];
	fbox[c] = no;
	}
	for(c = 0; c < arrTbox.length; c++) {
	var no = new Option();
	no.value = arrLookup[arrTbox[c]];
	no.text = arrTbox[c];
	tbox[c] = no;
   }
}
function pasa_tarea(origen,destino){
	origen = document.getElementById(origen);
	destino = document.getElementById(destino);

	var patron = /fin/i;
	
	existe=destino.value.search(patron);
		
	if(existe==-1){
		for (i=0;i < origen.options.length; i++){
			destino.value+=origen[i].value+";";
		}
		destino.value+="fin";
	}
/*
	texto=""
	if(document.form1.tar_nombre.value==""){
		texto+="- Debe insertar el nombre de la tarea.\n";
	}
	if(Comparar_Fecha(document.form1.tar_estima_fini.value,document.form1.tar_estima_ffin.value)==false){
		texto+="- La fecha de inicio no puede ser superior a la fecha de fin.\n";
	}
	if(texto==""){
		document.form1.submit();
	}else{
		alert(texto);
	}
*/
}	