//*********************************************************************************
//FUNCIONES DE APLICACION
//*********************************************************************************
function abrir(theURL,winName,features) {
  window.open(theURL,winName,features);
}

function cambioImg(imagen){
	//alert(imagen);
	//id -> imagenTocha
	document.imagenTocha.src=imagen;
}

function ConfirmarPop(titular,direccion,propiedades){
        if (confirm(titular)){
                abrir(direccion,'',propiedades);
        }        
}

function crearNuevo(idform,campo,url,opcion,cat,tipo,campo2){
	
	aux_bfk_proyecto_tipo=eval('document.'+idform+'.'+campo+'.value');
	aux_bproyecto_anyo=eval('document.'+idform+'.'+campo2+'.value');
	document.location.href=url+"?opcion="+opcion+"&cat="+cat+"&"+campo+"="+aux_bfk_proyecto_tipo+"&"+campo2+"="+aux_bproyecto_anyo;
}
//para reenviar algo a trav�s de un check
/*function casilla(campo,id,url,formulario){
		valor=0;
		if(eval("document."+formulario+"."+campo+".checked")){
			valor=1;
		}
        document.location.href=url+"&pk="+id+"&valor="+valor;
}*/
function saltocasilla(id,campo){
	document.formulario.aux_casilla.value=0;
	document.formulario.aux_pk.value=id;
	if(eval('document.formulario.'+campo+'.checked')){
		document.formulario.aux_casilla.value=1;
	}
	document.formulario.submit();
}

function saltolistado(id,campo,opcion){
	eval('document.formulario.'+campo+'.value='+id);
	document.formulario.aux_opcion.value=opcion;
	document.formulario.submit();
}

function borrolistado(mje,id){
	if(confirm(mje)){
		document.formulario.aux_pk.value=id;
		document.formulario.aux_opcion.value='borrar';
		document.formulario.submit();
	}
}

//para pasar valor cero o uno a un campo desde un check
function valorcheck(campo,formulario,destino){
		if(eval("document."+formulario+"."+campo+".checked")){
			eval("document."+formulario+"."+destino+".value=1");
		}else{
			eval("document."+formulario+"."+destino+".value=0");
		}
}

function asignarCliente(valor,capa){
	if(valor==0){
		document.getElementById(capa).style.display='none';
	}else{
		document.getElementById(capa).style.display='inline';
	}
}

function mostrarSec(valor,id){
	if(valor==1){
		eval(id+".style.display='inline';");
	}else{
		eval(id+".style.display='none';");
	}
}

function combo(formulario,id,nombrecampo,url,campoweb){
        aux_valorcambio=eval('document.'+formulario+'.'+nombrecampo+'.value');
        document.location.href=url+"&id_registro="+id+"&campo="+campoweb+"&valor="+aux_valorcambio;
}

anterior="";
function mostrar(id){
	//Anulado por la reunion &&(anterior!="subm_4")&&(anterior!="subm_7")
        if (((anterior!="")||(anterior==id))) {
                var queoculto=anterior+'.style.display="none"';
                eval(queoculto);
        }
        if ((id!='subm_0')&&(anterior!=id)&&(id!='subm_26')&&(id!='subm_27')){
                var quemuestro=id+'.style.display="inline"';
                eval(quemuestro);
                anterior=id;
        }else{
                anterior="";
        }
}

function salto(formulario){
        eval("document."+formulario+".submit()");
}

function ConfirmarBorrado(mje,id,direccion,opcion,masquery){
	if(confirm(mje)){
		document.location.href=direccion+"?pk="+id+"&opcion="+opcion+""+masquery;
	}
}

//*********************************************************************************
//VALIDACION DE FORMULARIOS
//*********************************************************************************

msje="Por favor, revise los errores en los siguientes campos:\n\n";
equivoc=0;

function replaceChars(cadena,quito,pongo) {
	out = quito;
	add = pongo;
	temp = "" + cadena;
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
	}
	return temp;
}

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 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+="� El campo '"+nombrecampo+"' requiere una direcci�n de correo v�lida.\n";
                }
}

function validar_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 = "";
   }
   /* 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,sobra){
	/*
	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. Y sobra es lo q se quita al nombre del campo para
	mostrar la alerta: ejemlo: "t_datos_contacto" se queda en "datos contacto", xq el valor de sobra es "t_"
	*/
	var obligatorio=new Array();
	obligatorio=campo.split("!");
	var aux_cadena=eval("document."+form+"."+obligatorio[0]+".value");
	var nombrecampo=replaceChars(obligatorio[0],sobra,'');
	nombrecampo=replaceChars(nombrecampo,'_',' ');
        
	switch (tipo) {
		case 1:
		//numero
			if (isNaN(aux_cadena)) {
					equivoc=1;
					msje+="� El campo '"+nombrecampo+"' debe ser un n�mero.\n";
			}
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+="� El campo '"+nombrecampo+"' 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 n�mero.\n";
			}*/
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+="� El campo '"+nombrecampo+"' es obligatorio.\n";
			}
		break;
		case 4:
		//fecha corta
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+="� El campo '"+nombrecampo+"' 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 '"+nombrecampo+"' es obligatorio.\n";
				}
			}else{
				if ( (aux_cadena!="") && ((aux_cadena.search(expresion))!=1) ) {
						equivoc=1;
						//msje+="� El campo '"+obligatorio[0]+"' debe contener una hora v�lida.\n";
						msje+="� El campo '"+nombrecampo+"' debe contener una hora v�lida.\n";
				}
			}
		break;
	
		default:
		//texto
			if ( (aux_cadena=="") && (obligatorio[1]==1) ) {
					equivoc=1;
					msje+="� El campo '"+nombrecampo+"' 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')
*/
function validar(valor,nombreform,sobra){

        var matriz_obligatorios=new Array();
        matriz_obligatorios=valor.split("#");
        var longitud=(matriz_obligatorios.length)-1;
        var matriztipo=new Array(2);
        var matrizcampos=new Array();
		var cadenita='';
		
      
        for (i=0;i<longitud;i++){
                matriztipo=matriz_obligatorios[i].split("|");
				cadenita+=matriz_obligatorios[i];
                matrizcampos[i]=matriztipo;
        }
		
        for (i=0;i<longitud;i++){
				
                eval("checkeacampo("+matrizcampos[i][1]+",'"+matrizcampos[i][0]+"','"+nombreform+"','"+sobra+"')");
        }
		
        if (equivoc==0){
                eval("document."+nombreform+".submit()");
        }else{
                alert(msje);
                equivoc=0;
                msje="Por favor, revise los errores en los siguientes campos:\n\n";
        }
}


letras = new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
function calculonif() {
		cad = new String(document.formulario.dni.value);
		while(cad.substring(0,1)=="0" && cad.length>1){
								  cad=cad.substring(1,cad.length);}
		indice=(document.formulario.dni.value)-(parseInt(cad/23)*23); 
		if (isNaN(document.formulario.dni.value)){
				document.formulario.nif.value="";
		}else{
				document.formulario.nif.value=letras[indice];
		}
}

//*********************************************************************************
//funciones marcianas
//*********************************************************************************
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 validarform2() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=validarform2.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' debe ser una direcci�n de correo v�lida.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' debe ser un n�mero.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' debe contener un n�mero entre '+min+' y '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es obligatorio.\n'; }
  
  } if (errors) {
  	alert('Por favor, revise el formulario:\n'+errors);
  	return false;
  }else{
  	return true;
  }
}



				var frase="1 - Residencial<br/>";
				frase=frase+"2 - Deportivo<br/>";
				frase=frase+"3 - Comerciales<br/>";
				frase=frase+"4 - Universitario<br/>";
				frase=frase+"5 - Escolar<br/>";
				frase=frase+"6 - Sanitario<br/>";
				frase=frase+"7 - Hosteleria<br/>";
				frase=frase+"8 - Industrial<br/>";
				frase=frase+"9 - Terciario<br/>";
				frase=frase+"10 - Urbanizacion";
				var opcionElegida;

			function printpdf() {
			Sexy.prompt('<h1>Generar PDF obras por tipo</h1>Ingresa el tipo de obra:<br/>'+frase,'pdf' ,{ onComplete:
			  function(returnvalue) {
			    if(returnvalue)
			    {
				opcionElegida=returnvalue;
				if (IsNumeric(returnvalue)){
				
			      Sexy.confirm('<h1>ha elegido el tipo '+returnvalue+',</h1><p>Se va a generar el pdf</p><p>Pulsa "Ok" para continuar, o pulsa "Cancelar" para salir.</p>', { onComplete:
				function(returnvalue) {
				      if(returnvalue)
				      {
						location.href = "http://www.cgtecnica.es/html2ps/samples/cgTecnicaPDF.php?idSec=2&tipoP=" + opcionElegida ;
				      }
				       else
					{
					  Sexy.error('<h1>Ha cancelado la operación.</p>');
					}
				}
			      });
			      }else{
				  Sexy.error('<h1>Error al intentar generar el pdf</h1><p>Para continuar, debe introducir el numero del tipo deseado.</p><p>Inténtalo de nuevo.</p>');
			      }
			    }
			    else
			    {
			      Sexy.error('<h1>Ha cancelado la operación.</p>');
			    }
			  }
			});
		    }

			function printpdfNO()
			{
				frase="Introduca el numero tipo de proyecto:\n\n";
				frase=frase+"1 - Residencial\n";
				frase=frase+"2 - Deportivo\n";
				frase=frase+"3 - Comerciales\n";
				frase=frase+"4 - Universitario\n";
				frase=frase+"5 - Escolar\n";
				frase=frase+"6 - Sanitario\n";
				frase=frase+"7 - Hosteleria\n";
				frase=frase+"8 - Industrial\n";
				frase=frase+"9 - Terciario\n";
				frase=frase+"10 - Urbanizacion";
				tipo=window.prompt(frase, "");


				if (tipo!="") generaPDF(tipo);

			}


			function IsNumeric(sText)
			{
			   var ValidChars = "0123456789";
			   var IsNumber=true;
			   var Char;



			   for (i = 0; i < sText.length && IsNumber == true; i++)
			      {
			      Char = sText.charAt(i);
			      if (ValidChars.indexOf(Char) == -1)
			         {
			         IsNumber = false;
			         }
			      }
			   return IsNumber;

			   }


				function generaPDF(idP)
			{

				if (IsNumeric(idP)){
						alert("http://www.cgtecnica.es/html2ps/samples/cgTecnicaPDF.php?idSec=2&tipoP=" + idP);
						location.href = "http://www.cgtecnica.es/html2ps/samples/cgTecnicaPDF.php?idSec=2&tipoP=" + idP ;
				}else{
					alert('El valor debe ser numerico');
				}
			}

