/*
  -------------------------------------------------------------------------
	                    JavaScript Form Validator 
                                Version 2.0.2
	Copyright 2003 JavaScript-coder.com. All rights reserved.
	You use this script in your Web pages, provided these opening credit
    lines are kept intact.
	The Form validation script is distributed free from JavaScript-Coder.com

	You may please add a link to JavaScript-Coder.com, 
	making it easy for others to find this script.
	Checkout the Give a link and Get a link page:
	http://www.javascript-coder.com/links/how-to-link.php

    You may not reprint or redistribute this code without permission from 
    JavaScript-Coder.com.
	
	JavaScript Coder
	It precisely codes what you imagine!
	Grab your copy here:
		http://www.javascript-coder.com/
    -------------------------------------------------------------------------  
*/
function Validator(frmname)
{
  this.formobj=document.forms[frmname];
	if(!this.formobj)
	{
	  alert("BUG: couldnot get Form object "+frmname);
		return;
	}
	if(this.formobj.onsubmit)
	{
	 this.formobj.old_onsubmit = this.formobj.onsubmit;
	 this.formobj.onsubmit=null;
	}
	else
	{
	 this.formobj.old_onsubmit = null;
	}
	this.formobj.onsubmit=form_submit_handler;
	this.addValidation = add_validation;
	this.setAddnlValidationFunction=set_addnl_vfunction;
	this.clearAllValidations = clear_all_validations;
}
function set_addnl_vfunction(functionname)
{
  this.formobj.addnlvalidation = functionname;
}
function clear_all_validations()
{
	for(var itr=0;itr < this.formobj.elements.length;itr++)
	{
		this.formobj.elements[itr].validationset = null;
	}
}
function form_submit_handler()
{
	for(var itr=0;itr < this.elements.length;itr++)
	{
		if(this.elements[itr].validationset &&
	   !this.elements[itr].validationset.validate())
		{
		  return false;
		}
	}
	if(this.addnlvalidation)
	{
	  str =" var ret = "+this.addnlvalidation+"()";
	  eval(str);
    if(!ret) return ret;
	}
	return true;
}
function add_validation(itemname,descriptor,errstr)
{
  if(!this.formobj)
	{
	  alert("BUG: the form object is not set properly");
		return;
	}//if
	var itemobj = this.formobj[itemname];
  if(!itemobj)
	{
	  alert("BUG: Couldnot get the input object named: "+itemname);
		return;
	}
	if(!itemobj.validationset)
	{
	  itemobj.validationset = new ValidationSet(itemobj);
	}
  itemobj.validationset.add(descriptor,errstr);
}
function ValidationDesc(inputitem,desc,error)
{
  this.desc=desc;
	this.error=error;
	this.itemobj = inputitem;
	this.validate=vdesc_validate;
}
function vdesc_validate()
{
 if(!V2validateData(this.desc,this.itemobj,this.error))
 {
    this.itemobj.focus();
		return false;
 }
 return true;
}
function ValidationSet(inputitem)
{
    this.vSet=new Array();
	this.add= add_validationdesc;
	this.validate= vset_validate;
	this.itemobj = inputitem;
}
function add_validationdesc(desc,error)
{
  this.vSet[this.vSet.length]= 
	  new ValidationDesc(this.itemobj,desc,error);
}
function vset_validate()
{
   for(var itr=0;itr<this.vSet.length;itr++)
	 {
	   if(!this.vSet[itr].validate())
		 {
		   return false;
		 }
	 }
	 return true;
}
function validateEmailv2(email)
{
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    if(email.length <= 0)
	{
	  return true;
	}
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}
function V2validateData(strValidateStr,objValue,strError) 
{ 
    var epos = strValidateStr.search("="); 
    var  command  = ""; 
    var  cmdvalue = ""; 
    if(epos >= 0) 
    { 
     command  = strValidateStr.substring(0,epos); 
     cmdvalue = strValidateStr.substr(epos+1); 
    } 
    else 
    { 
     command = strValidateStr; 
    } 
    switch(command) 
    { 
        case "req": 
        case "required": 
         { 
           if(eval(objValue.value.length) == 0) 
           { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : Dato obligatorio"; 
              }//if 
              alert(strError); 
              return false; 
           }//if 
           break;             
         }//case required 
        case "maxlength": 
        case "maxlen": 
          { 
             if(eval(objValue.value.length) >  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : "+cmdvalue+"  caracteres maximo "; 
               }//if 
               alert(strError + "\n[Current length = " + objValue.value.length + " ]"); 
               return false; 
             }//if 
             break; 
          }//case maxlen 
        case "minlength": 
        case "minlen": 
           { 
             if(eval(objValue.value.length) <  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : " + cmdvalue + " caracteres minimo  "; 
               }//if               
               alert(strError + "\n[Current length = " + objValue.value.length + " ]"); 
               return false;                 
             }//if 
             break; 
            }//case minlen 
        case "alnum": 
        case "alphanumeric": 
           { 
              var charpos = objValue.value.search("[^A-Za-z0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
               if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Solo se permiten caracteres alfanumericos"; 
                }//if 
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric": 
           { 
              var charpos = objValue.value.search("[^0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Solo se permiten digitos numericos "; 
                }//if               
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break;               
           }//numeric 
        case "alphabetic": 
        case "alpha": 
           { 
              var charpos = objValue.value.search("[^A-Za-z]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Solo se permiten caracteres alfabeticos "; 
                }//if                             
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//alpha 
		case "alnumhyphen":
			{
              var charpos = objValue.value.search("[^A-Za-z0-9\-_]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": los caracteres permitidos son A-Z,a-z,0-9,- _"; 
                }//if                             
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 			
			break;
			}
        case "email": 
          { 
               if(!validateEmailv2(objValue.value)) 
               { 
                 if(!strError || strError.length ==0) 
                 { 
                    strError = objValue.name+": Introduzca una direccion de email correcta "; 
                 }//if                                               
                 alert(strError); 
                 return false; 
               }//if 
           break; 
          }//case email 
        case "lt": 
        case "lessthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Debe ser un numero "); 
              return false; 
            }//if 
            if(eval(objValue.value) >=  eval(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : el valor debe ser menor que "+ cmdvalue; 
              }//if               
              alert(strError); 
              return false;                 
             }//if             
            break; 
         }//case lessthan 
        case "gt": 
        case "greaterthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Debe ser un numero "); 
              return false; 
            }//if 
             if(eval(objValue.value) <=  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : el valor debe ser mayor que "+ cmdvalue; 
               }//if               
               alert(strError); 
               return false;                 
             }//if             
            break; 
         }//case greaterthan 
        case "regexp": 
         { 
		 	if(objValue.value.length > 0)
			{
	            if(!objValue.value.match(cmdvalue)) 
	            { 
	              if(!strError || strError.length ==0) 
	              { 
	                strError = objValue.name+": Se han encontrado caracteres no validos "; 
	              }//if                                                               
	              alert(strError); 
	              return false;                   
	            }//if 
			}
           break; 
         }//case regexp 
        case "dontselect": 
         { 
            if(objValue.selectedIndex == null) 
            { 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex == eval(cmdvalue)) 
            { 
             if(!strError || strError.length ==0) 
              { 
              strError = objValue.name+": Por favor, selecione una opcion "; 
              }//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselect 
    }//switch 
    return true; 
}
/*
	Copyright 2003 JavaScript-coder.com. All rights reserved.
*/



function logaction(form,urllogin,urllogout) {
  var accion;
  accion = form.accion.value;
  if (accion=="login") {
      var errorStr = "";
      if (form.email.value.length==0) errorStr="Debe introducir su email de registro";
      else if (form.pwd.value.length==0) errorStr="Debe introducir su contraseña de acceso";
      if (errorStr=="") {
        form.action=urllogin;
        form.submit();
      }
      else {
         alert(errorStr);
      }
  }
  else {
    form.action=urllogout;
    form.submit();  
  }
}


function checkCantidad(cant){
   var ic = parseInt(cant)
   if(isNaN(ic))
      return false;
   else
      return (ic>0 && ic<=99)
}


function alCarrito(aform,url,idproducto,cantidad) {
   aform.action = url;
   aform.op.value = 'add';
   aform.idproducto.value = idproducto;
   aform.cantidad.value = cantidad;
   aform.urlretorno.value = location.href;
   aform.submit();
}

function borrarProducto(aform,url,idproducto) {
   aform.action = url;
   aform.op.value = 'del';
   aform.idproducto.value = idproducto;
   aform.urlretorno.value = location.href;
   aform.submit();
}

function irACarrito(aform,url) {
   aform.action = url;
   aform.op.value = "show";
   aform.urlretorno.value = location.href;
   aform.submit();
}

function vaciarCarrito(aform,url) {
   aform.action = url;
   aform.op.value = "clear";
   aform.urlretorno.value = location.href;
   aform.submit();
}


function sendDatosEnvio(aform,actionurl,returnurl) {
   aform.action = actionurl;
   aform.op.value = "datosenvio";
   aform.urlretorno.value = returnurl;
   aform.submit();
}



function modCantidad(aform,url,idproducto,cantField) {
   if (checkCantidad(cantField.value)) { 
       aform.action = url;
       aform.op.value = "modcant";
       aform.idproducto.value = idproducto;
       aform.cantidad.value = parseInt(cantField.value);
       aform.urlretorno.value = location.href;
       aform.submit();   
   }
   else {
       alert("Introduzca una cantidad correcta");
       cantField.value = "1";
       cantField.focus();
       cantField.select();       
   }
}

function escribirFecha() {
    hoy=new Date()
    dia=hoy.getDay()
    dian=hoy.getDate()
    mes=hoy.getMonth()
    urte=hoy.getFullYear()
    if (dia==0) {dia="Domingo"}
    if (dia==1) {dia="Lunes"}
    if (dia==2) {dia="Martes"}
    if (dia==3) {dia="Mi&eacute;rcoles"}
    if (dia==4) {dia="Jueves"}
    if (dia==5) {dia="Viernes"}
    if (dia==6) {dia="S&aacute;bado"}
    if (mes==0) {mes="Enero"}
    if (mes==1) {mes="Febrero"}
    if (mes==2) {mes="Marzo"}
    if (mes==3) {mes="Abril"}
    if (mes==4) {mes="Mayo"}
    if (mes==5) {mes="Junio"}
    if (mes==6) {mes="Julio"}
    if (mes==7) {mes="Agosto"}
    if (mes==8) {mes="Septiembre"}
    if (mes==9) {mes="Octubre"}
    if (mes==10) {mes="Noviembre"}
    if (mes==11) {mes="Diciembre"}
    document.write(dia+", "+dian+" de "+mes+" de "+urte)
}

function SwitchMenu(obj){
    
    if(document.getElementById){
    var el = document.getElementById(obj);
    var ar = document.getElementById("tbmenucatalogo").getElementsByTagName("div"); 
        if(el.style.display != "block"){ 
            for (var i=0; i<ar.length; i++){
                if (ar[i].className=="capasubmenu") 
                ar[i].style.display = "none";
                familiaactual=null;
            }
            el.style.display = "block";
            familiaactual=obj;
        }else{
            el.style.display = "none";
            familiaactual=null;
        }
    }
}



function abrirVentana(wvar,name) {
     if (wvar == null) {
        wvar = window.open('', name, 'directories=no,resizeable=yes,location=no,status=no,menubar=NO,dependent=yes,scrollbars=no,toolbar=no,width=360,height=390');
     }
     else {
       wvar.close();
       wvar = window.open('', name, 'directories=no,resizeable=yes,location=no,status=no,menubar=NO,dependent=yes,scrollbars=no,toolbar=no,width=360,height=390');
    }
}


function reDimension() {
	var w = this.width;
    var h = this.height;

	if (this.height==0)
	{
		h=90;
	}
	if (this.width==0)
	{
		w=90;
	}

	//alert ("w"+w + "h"+h);

    if (h>90 || w>90) 
        if(h>w){
            w = w*90/h;
            h = 90;	
        }
        else {
            h = h*90/w;
            w = 90;
        }
    this.width = w;
    this.height = h;
	//alert (e.width)
}


function cargarImagen(e,src) {
if (navigator.appName.indexOf("Explorer") > -1)
	{
	   if (e.height>e.width)
	   {
			e.height = 90;
	   }
	   else {
			e.width = 90;
	   }
	}
	   e.onload = reDimension;
	   e.src = src
}




function addEvent( obj, type, fn ) {
      if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) {
     if ( obj.detachEvent ) {
       obj.detachEvent( 'on'+type, obj[type+fn] );
       obj[type+fn] = null;
     } else
       obj.removeEventListener( type, fn, false );
}




function imprSelec(nombre)
{
  var ficha = document.getElementById(nombre);
  var ventimp = window.open(' ', 'popimpr');
  ventimp.document.write( ficha.innerHTML );
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();
}


function calcularNIF(dni) {
dni=dni.toUpperCase();
if (dni.length!=9) return false;
if (!/^(\d{8})(\w)$/.test(dni)) {
    //puede ser que sea un cif
	if (!/^(\w)(\d{7})((\d{1})|(\w{1}))$/.test(dni)) return false;
	else { //estamos ante un cif
		var ncif=dni.substring(1,8);
		var lcif=dni.substring(0,1);
		var fcif=dni.substring(8,9);
		if (lcif=='N') {return true;}
		var suma=parseInt(ncif.substring(1,2))+parseInt(ncif.substring(3,4))+parseInt(ncif.substring(5,6));
		var sumainter=0;
		for (j=0;j<=6;j+=2){
		var inte=parseInt(ncif.substring(j,j+1))
		inte=2*inte;
		suma=suma+(inte%10)+(parseInt(inte/10));
		}
		var control = 10 - (suma % 10);
		var correcto = false;
		if (lcif=='P' || lcif=='S' || lcif=='Q' || lcif=='G') {
			correcto = fcif.charCodeAt(0) == 64 + control;
		}
	   	if (!correcto){
			  //Resto de tipos de CIF, Control tipo número
		     if (control == 10)  control = 0; 
		     correcto = parseInt(fcif) == control;
		     }
		   return correcto;
		}
    }
else { //estamos ante un dni
var ldni=dni.substring(8,9);
var ndni=dni.substring(0,8);
var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
var numero = ndni%23;
 if((letras.substring(numero,numero+1)!=ldni))  return false;
 else return true;
}
return true;
}

function esDNI(dni) {
dni=dni.toUpperCase();
if (!/^(\d{8})(\w)$/.test(dni)) {
    var lcif=dni.substring(0,1);
    if (lcif=='X') {return true;}
    else {return false;}
}
else {return true;}
}

function telefonoCorrecto(tfno){
if(tfno.length!=9) return false;
if (!/^(9|6|8)\d{8}/.test(tfno)) return false;
else return true;
}


function validarNIE(valor){
	
	total = valor.length;
	
	if(total==10){
		
		if(valor.substring(0,1) != "0" && valor.substring(0,1) != " ")	{
			
			return false;
		}else{
		
		valor=valor.substring(1,10);
		}
		
	}
	
	var letraInicio = valor.substring(0,1);
        
        if (letraInicio != "X" && letraInicio != "P"){
        	
		return false;
	}
	total = valor.length;
	
	dni = valor.substring(1,total -1);
	
	
	if(!esnumero(dni)){
		return false;
		
	}	
	

        // Letra recibida
        var letra = valor.charAt(valor.length - 1).toUpperCase();
        
        if (esnumero(letra,1))
        {
            return false;
        }
        
    	// definir el array de letras
    	
    	        var nif_letras = "TRWAGMYFPDXBNJZSQVHLCKEU"
        	            
		var res = parseInt(dni, 10);
		
    	
    	        var pos = (parseInt(res) - Math.floor(parseInt(res)/23) * 23) + 1;

    	        var n_letra = nif_letras.substring(pos - 1, pos);
    	        

            	if (n_letra != letra)
            	{
    	            return false;
    	        }
return true;	

}



//Array de strings internacionalizados
var interStrings=new Array();
var contI=0;

//Variable de Error
var errorS="";
var errorStrings=new Array();
var contE=0;




//Variables de paises y provincias
var provincias=new Array();
var paises=new Array();
var paisesProvincias=new Array();
var codigosPostales=new Array();
var contPa=0;
var contPaa=1;
var contPr=0;

//Variables de direcciones
var cdire=1;
var direcciones=new Array();
var ddirecciones=new Array();
var dpoblacion=new Array();
var dcpostal=new Array();
var dprovincia=new Array();
var dpais=new Array();
var dcliente=new Array();
var identificativos=new Array();
var didentificativo=new Array();
var dnombre=new Array();
var dapellidos=new Array();
var dtipo=new Array();
var dtelefono1=new Array();
var dtelefono2=new Array();

function anadirPais(elpais){
    paises[contPa]=elpais;
    contPa++;
}

function anadirProvincia(nprov,laprov,codPostal){
    var pr=new Option(nprov,laprov);
    provincias[contPr]=pr;
    codigosPostales[laprov]=codPostal;
    contPr++;
}

function getProvincias(){
    return provincias;
}

function inicializarProvincias(){
    provincias=new Array();
    contPr=0;
}

function anadirPaisProvincias(form,elpais,npais,provs){
    paisesProvincias[elpais]=provs;
    var pob=new Option(npais,elpais);
    form.paises.options[contPaa]=pob;
    contPaa++;
}

function seleccionarPais(form,elpais,laprov){
for (cont=0;cont<form.paises.options.length;cont++){
    if (form.paises.options[cont].value==elpais) paiss=cont;
 }
 form.paises.options.selectedIndex=paiss;
  if (elpais!=0){
   var pro=paisesProvincias[elpais];
   for (cont1=0;cont1<pro.length;cont1++){
    form.provincias.options[cont1]=pro[cont1];
    if (pro[cont1].value==laprov) provs=cont1;
   }
   }
 form.provincias.options.selectedIndex=provs;

}

function cambiarProvs(form,elpais){
    var numoptions=form.provincias.options.length;
    for (optionCounter = 0; optionCounter < numoptions; optionCounter++) {
       form.provincias.options[1]=null;
    }
   if (elpais!=0){
   var pro=paisesProvincias[elpais];
   for (cont1=0;cont1<pro.length;cont1++){
    form.provincias.options[cont1]=pro[cont1];
   }
   }
   form.provincias.options.selectedIndex=0;
  
}

function anadirError(ind,elError){

	errorStrings[ind]=elError;
	contE++;
    
}

function anadirTexto(elTexto){

	interStrings[contI]=elTexto;
	contI++;
    
}

function anadirTextoProv(elTexto){
    opcionP=elTexto;    
}

function getTextos(){
	return interStrings;
}



////////////////////////////////////////////////////////////////////////////////
function emailCorrecto(ind,emailStr) {
////////////////////////////////////////////////////////////////////////////////

var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]áéíóúÁÉÍÓÚâêîôû^ÂÊÎÔÛàèìòùÀÈÌÒÙÄËÏÖÜëïü¨"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
        errorS=errorStrings[ind];
        return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    errorS=errorStrings[ind+1];
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
          for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                errorS=errorStrings[ind+2];
                return false
            }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
        errorS=errorStrings[ind+3];
    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) { 
   errorS=errorStrings[ind+4];
   return false;
}

if (len<2) {
   errorS=errorStrings[ind+5];
   return false
}
return true;
}


function passwordCorrecto(pass){
allowed =  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890._-';
return isValid(pass,allowed);
}

function nomCorrecto(ape){
allowed =  'abcdefghijklmnñopqrstuvwxyzáéíóú ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ,-.';
return isValid(ape,allowed);
}

function dirCorrecto(ape){
allowed =  'abcdefghijklmnñopqrstuvwxyzáéíóú ABCDEFGHIJKLMNÑOPQRSTUVWXYZ\\:.,/ºª0123456789-ÁÉÍÓÚ-';
return isValid(ape,allowed);
}

function validarLogin(ind,form,accion){
         if (form.identificativo.options[form.identificativo.selectedIndex].value==1) {
            if (form.email.value=="") errorS=errorStrings[ind+10];
            else if (!calcularNIF(form.email.value)) errorS=errorStrings[ind+11];
            }
        else{
            if (form.email.value=="") errorS=errorStrings[ind];
            else if (!emailCorrecto(ind+4,form.email.value)) errorS=errorStrings[ind+1]+errorS;
            }
        if (errorS==""){
	if (form.password.value=="") errorS=errorStrings[ind+2];
	else if (!passwordCorrecto(form.password.value)) errorS=errorStrings[ind+3];
	}
        if (errorS=="") {
		form.action="/UserLogin";
                form.accion.value=accion;
		form.submit();
	}
	else {alert(errorS);errorS="";}
}

function Alta(form,accion){
                form.accion.value=accion;
                form.action="/UserLogin";
				form.submit();
	
}

function validarTipo(form){
    if (form.tipo_cliente[0].checked) return 'P';
    else return 'E';
}

function validarCodigoP(form,codigo){
 
  var sProv=form.provincias[form.provincias.selectedIndex].value;
  var patronCod=codigosPostales[sProv];
  var patronJ="";
  for (pc=0;pc<patronCod.length;pc++){
    if (patronCod.charAt(pc)=='?') patronJ+="\\d{1}";
    else patronJ+=patronCod.charAt(pc);
  }
    var patronMask=new RegExp("^" + patronJ + "$")
    var maskArray=codigo.match(patronMask)
        if (maskArray==null) return false;
        else return true;
 }

function esBisiesto(anio){
   return (((anio % 4 == 0) && (anio % 100 != 0)) || (anio % 400 == 0));

}


function esEsosMeses(mes){
    return ((mes==11)||(mes==4)||(mes==6)||(mes==9));
}



function fechaCorrecta(ano,mes,dia){
    if (dia>31) return false;
	else if (mes>12) return false;
    else if (dia>30&&esEsosMeses(mes)) return false;
    else if ((dia>29&&(mes==2))||(dia>28&&!esBisiesto(ano)&&(mes==2))) return false;
    return true;

}

function fechaNacCorrecta(fecha){
     var patronfecha=/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/
     var fechaArray=fecha.match(patronfecha)
     if (fechaArray==null) return false;
     else {
		
        var ano=fechaArray[3];
        var mes=fechaArray[2];
        var dia=fechaArray[1];
        hoy=new Date();
		anoSistema=hoy.getYear();
		if (anoSistema<1900) anoSistema=1900+anoSistema;
        if (!fechaCorrecta(ano,mes,dia)) return false;
        if ((ano>anoSistema)||((anoSistema==ano)&&(mes>(hoy.getMonth()+1)))||((anoSistema==ano)&&(mes==(hoy.getMonth()+1))&&(dia>hoy.getDate()))) return false;
        if (ano<(anoSistema-150)) return false;
        }
     return true;
}

function fechaEntCorrecta(fecha){
     var patronfecha=/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/
     var fechaArray=fecha.match(patronfecha)
     if (fechaArray==null) return false;
     else {
		
        var ano=fechaArray[3];
        var mes=fechaArray[2];
        var dia=fechaArray[1];
        hoy=new Date();
		anoSistema=hoy.getYear();
		if (anoSistema<1900) anoSistema=1900+anoSistema;
        if (!fechaCorrecta(ano,mes,dia)) return false;
      }
     return true;
}

function razonSocialCorrecto(nom,tempresa){
if (nom==tempresa) return false;
else{
allowed =  'abcdefghijklmnñopqrstuvwxyzáéíóú ABCDEFGHIJKLMNÑOPQRSTUVWXYZ\\:./ºª0123456789-ÁÉÍÓÚ-';
return isValid(nom,allowed);
    }
}

function validarRecordarPwd(ind,form,accion){
        var ind2=ind;
        var errorS="";
        if (form.email.value=="") errorS=errorStrings[ind];
        else if (!emailCorrecto(ind+4,form.email.value)) errorS=errorStrings[ind+1]+errorS;
        if (errorS=="") {
            form.action=accion;
		    form.submit();
	    }
	else {alert(errorS);errorS="";}
}


function validarDatos(ind,form,accion,tempresa){
        var tipo=validarTipo(form);
        var ind2=ind;
        if (tipo=='E')  ind2=ind+18;
        if (form.email.value=="") errorS=errorStrings[ind];
        else if (!emailCorrecto(ind+4,form.email.value)) errorS=errorStrings[ind+1]+errorS;
        else if (form.password.value=="") errorS=errorStrings[ind+2];
        else if (!passwordCorrecto(form.password.value)) errorS=errorStrings[ind+3];
        else if (!(form.password.value==form.rpassword.value)) errorS=errorStrings[ind+10];
		else if (form.password.value.length<4) errorS=errorStrings[ind+36];
        else if (form.nombre.value=="") errorS=errorStrings[ind2+14];
        else if (!razonSocialCorrecto(form.nombre.value,tempresa)) errorS=errorStrings[ind2+15];
        else if (form.apellidos.value=="") errorS=errorStrings[ind2+12];
        else if (!nomCorrecto(form.apellidos.value)) errorS=errorStrings[ind2+13];
        else if (form.dni.value=="") errorS=errorStrings[ind+16];
        else if ((tipo=='E')&&(esDNI(form.dni.value) || validarNIE(form.dni.value))) errorS=errorStrings[ind+38];
        else if ((tipo=='P')&&(!esDNI(form.dni.value) && !validarNIE(form.dni.value))) errorS=errorStrings[ind+37];
        else if (!calcularNIF(form.dni.value)) errorS=errorStrings[ind+17];
        else if (form.direccion.value=="") errorS=errorStrings[ind+18];
        else if (!dirCorrecto(form.direccion.value)) errorS=errorStrings[ind+19];
        else if (form.paises[form.paises.selectedIndex].value==0) errorS=errorStrings[ind+20];
        else if (form.poblacion.value=="") errorS=errorStrings[ind+21];
        else if (!nomCorrecto(form.poblacion.value)) errorS=errorStrings[ind+22];
        else if (form.provincias[form.provincias.selectedIndex].value==-1) errorS=errorStrings[ind+24];
        else if (form.telefono1.value=="") errorS=errorStrings[ind+23];
        else if (!telefonoCorrecto(form.telefono1.value)) errorS=errorStrings[ind+25];
        else if ((form.telefono2.value!="")&&(!telefonoCorrecto(form.telefono2.value))) errorS=errorStrings[ind+26];
        else if (form.cp.value=="") errorS=errorStrings[ind+27];
        else if (!validarCodigoP(form,form.cp.value)) errorS=errorStrings[ind+28];
        else {if (form.fecha_nacimiento.value!="dd/mm/aaaa") {if (!fechaNacCorrecta(form.fecha_nacimiento.value)){ errorS=errorStrings[ind+29];}}
             else {form.fecha_nacimiento.value="";}}
        if (errorS=="") {
            if (form.recibir.checked) 
               form.mailing.value='S';
            else
               form.mailing.value='N';
            
            form.action=accion;
		    form.submit();
	    }
	else {alert(errorS);errorS="";}
}

//Variables globales para el tipo
var nombreTipo=new Array();
var apellidoTipo=new Array();
var dniTipo=new Array();
var ejeTipo=new Array();
var tNnombreTipo=new Array();

function anadirTipo(tipo,nom,ape,dni,eje,tnom){
    nombreTipo[tipo]=nom;
    apellidoTipo[tipo]=ape;
    dniTipo[tipo]=dni;
    ejeTipo[tipo]=eje;
    tNnombreTipo[tipo]=tnom;
}

function anadirTipoDir(tipo,nom,ape,tnom){
    nombreTipo[tipo]=nom;
    apellidoTipo[tipo]=ape;
    tNnombreTipo[tipo]=tnom;
}

function cambiarTipoDir(form,nombre){
    if(form.tipo_dir[0].checked){
        form.tnombre.value=nombreTipo[0];
        form.tapellidos.value=apellidoTipo[0];
        form.nombre.value="";
        form.apellidos.value="";
    }
    else{
        form.tnombre.value=nombreTipo[1];
        form.tapellidos.value=apellidoTipo[1];
        form.nombre.value=tNnombreTipo[1];
        form.apellidos.value="";
    }

}

function cambiarTipo(form,nombre){
    if(form.tipo_cliente[0].checked){
        form.tnombre.value=nombreTipo[0];
        form.nombre.value="";
        form.apellidos.value="";
        form.tapellidos.value=apellidoTipo[0];
        form.dni.value=dniTipo[0];
        form.teje.value=ejeTipo[0];
    }
    else{
        form.tnombre.value=nombreTipo[1];
        form.nombre.value=tNnombreTipo[1];
        form.apellidos.value="";
        form.tapellidos.value=apellidoTipo[1];
        form.dni.value=dniTipo[1];
        form.teje.value=ejeTipo[1];
    }

}
function inicializarTipo(form){ 
   if(form.tipo_cliente[0].checked){
        form.tnombre.value=nombreTipo[0];
        form.tapellidos.value=apellidoTipo[0];
        form.dni.value=dniTipo[0];
        form.teje.value=ejeTipo[0];
    }
    else{
        form.tnombre.value=nombreTipo[1];
        form.tapellidos.value=apellidoTipo[1];
        form.dni.value=dniTipo[1];
        form.teje.value=ejeTipo[1];
    }
}

var dentro = 0;
function campobuscar_dentro(field){
    if (dentro == 0){
        field.select();
        field.focus();
        dentro=1;
    }
}
function campobuscar_fuera(field){
    if (dentro == 1){
        dentro = 0;
 field.blur();
    }
}   
function isValid(string,allowed){
    for (var i=0; i< string.length; i++){
        if (allowed.indexOf(string.charAt(i)) == -1) return false;
    }
    return true;
}
function trim(cadena){
 cadena=cadena.replace(/^[\s]+/g,"");
 cadena=cadena.replace(/[\s]+$/g, ""); 
   return cadena;
}



