function jsValidaFormulario(){

	if (document.form1.nombre.value==''){
		alert('Debe indicar su nombre');
		return false;
	}
	if (document.form1.empresa.value==''){
		alert('Debe indicar su empresa');
		return false;
	}
	if (document.form1.cp.value==''){
		alert('Debe indicar su c.postal');
		return false;
	}		
	if (document.form1.email.value==''){
		alert('Debe indicar una direccion de correo electronico');
		return false;
	}
	else if (emilio(document.form1.email.value)==false){
		alert('Debe indicar un correo electronico vlido');
		return false;
	}	
}

function jsValidaFormulario2(){
		var Fnombre;
		var Fempresa;
		var Fdireccion;
		var Femail;
		var Finformacion;
		var Ferrores;
		Fnombre=" - Debe rellenar el campo Nombre.\n";
		Fempresa=" - Debe rellenar el campo Empresa.\n";
		Fdireccion=" - Debe rellenar el campo Direccion.\n";
		Femail=" - Debe rellenar el campo Email.\n";
		Ftelefono=" - Debe rellenar el campo Telefono.\n"
		Ferrores="Este formulario no puede ser enviado debido a los siguientes errores: \n";

		errores = "";
		if (document.form1.nombre.value==''){
			errores += Fnombre;
		}
		if (document.form1.empresa.value==''){
			errores += Fempresa;
		}
		if (document.form1.direccion.value==''){
			errores += Fdireccion;
		}
		if (document.form1.telefono.value==''){
			errores += Ftelefono;
		}
	
		if (document.form1.email.value==''){
			errores += Femail;
		}
		
		if (errores == "") {
			document.form1.submit(); 
		}
		else {
			errores = Ferrores + errores;
			alert(errores);
		}

}





function saltodetema(url,opcion,id){
	auxid="";
	if (id!=0){
		auxid=id;
	}
	auxzona="";
	if (url=="areas.asp"){
		auxzona=document.formarea.zona.value;
	}
	document.location.href=url+"?opcion="+opcion+"&id="+auxid+"&zona="+auxzona;
}

function abrir(theURL,winName,features) {
  window.open(theURL,winName,features);
}

/************************************************************************
FUNCIONES DE VALIDACION DE FORMULARIOS
**************************************************************************/
msje="Por favor, revise los errores en los siguientes campos:\n\n";
equivoc=0;
function emilio(contcorreo,nombrecampo){
        //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 carcter antes y despus 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;        
                }

				if(correo.length>5){
					for (i=0; i<correo.length; i++){
							if (correo.charAt(i)==" ") {
							equivoc=1;
							fallo_correo = 1;
							}
					}
				}
                
                if (fallo_correo==1){
                        msje+=" El campo '"+nombrecampo+"' requiere una direccin de correo vlida.\n";
                }
}

function validar_fecha(field){
	//compruebo la fecha mientras la mete el usuario; la funcin se la asigno directamente al campo
	//llamada a la funcion: onBlur="validar_fecha(caducidad)" el nombre del campo, sin comillas
	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 dgitos - cadena */
	/* si el ao 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;
	}
	/* ao 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 da*/
	day = DateValue.substr(0,2);
	if (day < 1) {
		err = 22;
	}
	/* validacin de ao 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 = "";
	}
	/* 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 {
		alert("La fecha es incorrecta");
		DateField.select();
		DateField.focus();
	}
}

function checkeacampo(tipo,campo,form){
	/*
	validacion de campos; "tipo" nos dice si es cadena, numero, fecha, dni,... Con "campo" le paso dos
	cosas: el nombre del campo y  si es o no obligatorio. por eso lo primero que hago es esplitear cada
	valor en la matriz "obligatorio"; la cadena que llega es as: "campo_n!1". 1 es obligatorio y 0, no. 
	Y finalmente, "form" es el nombre del formulario.
	*/
	var obligatorio=new Array();
	obligatorio=campo.split("!");
	var aux_cadena=eval("document."+form+"."+obligatorio[0]+".value");
	switch (tipo) {
		case 1:
		//numero
			if (isNaN(aux_cadena)) {
					equivoc=1;
					msje+=" El campo '"+obligatorio[0]+"' debe ser un nmero.\n";
			}
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+=" El campo '"+obligatorio[0]+"' es obligatorio.\n";
			}
		break;
		case 21:
		//numero DNI; quito la validacion de numero porque se flipa
			/*if (isNaN(eval("document."+form+"."+obligatorio[0]+".value"))) {
					equivoc=1;
					msje+=" El campo '"+obligatorio[0]+"' debe ser un nmero.\n";
			}*/
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+=" El campo '"+obligatorio[0]+"' es obligatorio.\n";
			}
		break;
		case 4:
		//fecha corta
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+=" El campo '"+obligatorio[0]+"' es obligatorio.\n";
			}
		break;
		case 20:
			//correo
			if (obligatorio[1]==1) {
					emilio("'"+aux_cadena+"'","'"+obligatorio[0]+"'");
			}else if (aux_cadena!=""){
					emilio("'"+aux_cadena+"'","'"+obligatorio[0]+"'");
			}
		break;
		case 12:
		//editor
		break;
		case 25:
		//hora: 21:30
			var expresion=new RegExp("[0-23]:[0-59]");
			if (obligatorio[1]==1){
				if ( (aux_cadena=="") && ((aux_cadena.search(expresion))!=1) ) {
						equivoc=1;
						msje+=" El campo '"+obligatorio[0]+"' es obligatorio.\n";
				}
			}else{
				if ( (aux_cadena!="") && ((aux_cadena.search(expresion))!=1) ) {
						equivoc=1;
						msje+=" El campo '"+obligatorio[0]+"' debe contener una hora vlida.\n";
				}
			}
		break;
	
		default:
		//texto
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+=" El campo '"+obligatorio[0]+"' es obligatorio.\n";
			}
		break;
	}
}

/*ejempo de cadena:
validar('Idestado_civil!0|10#numero_hijos!0|1#f_nac!1|4#email!0|20#email2!0|20#Idlugar_nacimiento!0|10#','formulario')
siendo: nombre de campo!obligatorio|tipo de campo#; los tipos, los que hay arriba en la funcin checkeacampo
*/
function validar(valor,nombreform){

	var matriz_obligatorios=new Array();
	matriz_obligatorios=valor.split("#");
	var longitud=(matriz_obligatorios.length)-1;
	var matriztipo=new Array(2);
	var matrizcampos=new Array();
	
	for (i=0;i<longitud;i++){
		matriztipo=matriz_obligatorios[i].split("|");
		matrizcampos[i]=matriztipo;
	}
	
	for (i=0;i<longitud;i++){
		eval("checkeacampo("+matrizcampos[i][1]+",'"+matrizcampos[i][0]+"','"+nombreform+"')");
	}

	if (equivoc==0){
		eval("document."+nombreform+".submit()");
	}else{
		alert(msje);
		equivoc=0;
		msje="Por favor, revise los errores en los siguientes campos:\n\n";
	}
}

function cambioestado(ide,direccion){
	aux_estado=eval("document.form1.envio_"+ide+".checked");
	valor="0";
	if(aux_estado==true){
		valor="1";
	}
	document.location.href=direccion+'&id='+ide+"&estado="+valor;
}


extArray = new Array('jpg','jpeg','gif','png','bmp'); 
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 vlida, avisamos	
	if (!allowSubmit) {
		alert("Se permiten nicamente archivos de imagen con la extensin:\n" + (extArray.join(", ")) + "\n\nEl archivo " + archivo + " no es vlido. Por favor, seleccione otro archivo e intente de nuevo.");
		allowSubmit = false;
		}
	return allowSubmit;
}

/************************************************************************
FUNCIONES MARCIANAS
**************************************************************************/
function MM_swapImgRestore() {
  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() {
  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) {
  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() { 
  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];}
}
// Funciones Scroll
// Ahora est para scroll vertical, izquierda manda subir, derecha  bajar. Para ponerlo en horizontal, donde pone top, que ponga left
var activacion;
function derecha(valor){
var valornuevo;
valornuevo = valor.split ("px");
document.getElementById("contenido").style.top = ((valornuevo[0]*1)-1)+"px" ;
document.getElementById("coordenada").value = ((valornuevo[0]*1)-1) ; 
document.getElementById("niveledge").value = ((valornuevo[0]*1)-200) ; 
document.getElementById("edge").style.top = ((valornuevo[0]*1)-200)+"px" ;
}

function izquierda(valor){
var valornuevo;
valornuevo = valor.split ("px");
document.getElementById("contenido").style.top = ((valornuevo[0]*1)+1)+"px" ; 
document.getElementById("coordenada").value = ((valornuevo[0]*1)+1) ; 
document.getElementById("niveledge").value = ((valornuevo[0]*1)+200) ; 
document.getElementById("edge").style.top = ((valornuevo[0]*1)+200)+"px" ;
}
function derecha2(){
var valornuevo
valornuevo = document.getElementById("coordenada").value.split ("px");
activacion = setInterval("derecha3()",10);
document.getElementById("coordenada").value = ((valornuevo[0]*1)-1) 
document.getElementById("niveledge").value = ((valornuevo[0]*1)-200) 
}

function izquierda2(){
var valornuevo
valornuevo = document.getElementById("coordenada").value.split ("px");
activacion = setInterval("izquierda3()",10);
document.getElementById("coordenada").value = ((valornuevo[0]*1)+1) ; 
document.getElementById("niveledge").value = ((valornuevo[0]*1)+200) ; 
}
function derecha3(){
if (document.getElementById('muevederecha').value==1){
	derecha(document.getElementById('contenido').style.top);
}
else {
clearInterval (activacion);
	}	
}
function izquierda3(){
if ((document.getElementById('mueveizquierda').value==1)&&(document.getElementById("coordenada").value<=0)){
	izquierda(document.getElementById('contenido').style.top);
}
else {
	clearInterval (activacion);
	}	
}
// hasta aca


//////////////////////////////////////////////
// 			FUNCIONES AJAX
//////////////////////////////////////////////

//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 enc_alcargar(fk_pre){
	_objetus=http_request()
	//obtengo el nombre de la etiqueta que mostrar las alertas
	_target=document.getElementById('mensaje')
	//variables a enviar
	_values_send="nada=nada"
	//url de destino
	_URL_="./respuesta.asp?fk_pre="+fk_pre
	//Mtodo de envo
	_objetus.open("GET",_URL_,true);
	//Lonea necesaria si se enva por POST, envo 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 informacin, 4=Operacin completada)
		if (_objetus.readyState==1){
			_target.innerHTML="Cargando.......";
		}else if(_objetus.readyState==4){
			// 404 si la pgina no se encuentra,200 si todo ha ido bien, etc.
			if(_objetus.status==200){
				_target.innerHTML = _objetus.responseText;
			}else{
				_target.innerHTML = "Error: "._objetus.status;
			}
		}
	}
}

function enc_inserta_respuesta(){
	_objetus=http_request()
	_respuesta=document.getElementById('respuesta').value
	_fk_pre=document.getElementById('fk_pre').value
	_target=document.getElementById('mensaje')
	_values_send="&nada=nada&"
	_URL_="./respuesta.asp?op=2&respuesta="+_respuesta+"&fk_pre="+_fk_pre+"&";
	_objetus.open("GET",_URL_,true);
	_objetus.send('&'+_values_send);
	_objetus.onreadystatechange=function(){
		if (_objetus.readyState==1){
			_target.innerHTML="Cargando.......";
		}else if(_objetus.readyState==4){
			if(_objetus.status==200){
				_target.innerHTML = _objetus.responseText;
				_respuesta=""
			}else{
				_target.innerHTML = "Error: "._objetus.status;
			}
		}
	}
}

function accede_url(url){
	_objetus=http_request()
	_target=document.getElementById('mensaje')
	_values_send="&nada=nada&"
	_URL_=url;
	_objetus.open("GET",_URL_,true);
	_objetus.send('&'+_values_send);
	_objetus.onreadystatechange=function(){
		if (_objetus.readyState==1){
			_target.innerHTML="Cargando.......";
		}else if(_objetus.readyState==4){
			if(_objetus.status==200){
				_target.innerHTML = _objetus.responseText;
				_respuesta=""
			}else{
				_target.innerHTML = "Error: "._objetus.status;
			}
		}
	}
}

function enc_actualiza_respuesta(url, campo){
	_objetus=http_request()
	_respuesta=document.getElementById(campo).value
	_target=document.getElementById('mensaje')
	_values_send="&nada=nada&"
	_URL_=url+"respuesta="+_respuesta+"&";
	_objetus.open("GET",_URL_,true);
	_objetus.send('&'+_values_send);
	_objetus.onreadystatechange=function(){
		if (_objetus.readyState==1){
			_target.innerHTML="Cargando.......";
		}else if(_objetus.readyState==4){
			if(_objetus.status==200){
				_target.innerHTML = _objetus.responseText;
				_respuesta=""
			}else{
				_target.innerHTML = "Error: "._objetus.status;
			}
		}
	}
}

function limpiarURL(){
	_target=document.getElementById('mensaje')
	_target.innerHTML="";
}
