
// whitespace characters
var whitespace = " \t\n\r";
var defaultEmptyOK = false;

function MM_openBrWindow(theURL,winName,features)
{ //v2.0
  window.open(theURL,winName,features);
}

function Vacio(s)
{   return ((s == null) || (s.length == 0))
}

function Simbolo(aux)
{
	if (aux.indexOf("'") != -1)
	{
		return true
	}
	if (aux.indexOf(";") != -1)
	{
		return true
	}
	return false;
}

function Fecha(dateStr)
{
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
return false;
}
month = matchArray[3]; // parse date into variables
day = matchArray[1];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("El mes debe estar entre 1 y 12.");
return false;
}
if (day < 1 || day > 31) {
alert("El día debe estar entre 1 y 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("El mes "+month+" no tiene 31 dias!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("Febrero de " + year + " no tiene " + day + " dias!");
return false;
   }
}
return true;  // date is valid
}


/****************************************************************/

// Returns true if string s is empty or 
// whitespace characters only.

function EnBlanco(s)

{   var i;

    // Is s empty?
    if (Vacio(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function esFichero()
/*	Devuelve true si el Fichero tiene la extensión que se pasa como parámetro
	 Devuelve false en cualquier otro caso */
{
	var cadena,res,extensiones,i;
	
	extensiones = esFichero.arguments;
	cadena = extensiones[0];
	cadena = cadena.toUpperCase();
	res = false;
	for (i=1;i < extensiones.length; i++)
	{ 
		if (cadena.indexOf("."+ extensiones[i]) != -1 )
		{
			res = true;		
		}
	}
	return (res);
}

function FechaMayorque(datIni,datFin)
/*	Compara dos fechas
	datIni : Fecha Inicial
	datFin : Fecha Final
	Devuelve:
		True si datFin > datIni
		False en cualquier otro caso
*/
{
	var diaIni;
	var MesIni;
	var AnyoIni;
	var diaFin;
	var MesFin;
	var AnyoFin;
	
	//Fecha inicial
	diaIni = datIni.getDate();
	MesIni = datIni.getMonth();
	AnyoIni = datIni.getYear();
	
	//Fecha final
	diaFin = datFin.getDate();
	MesFin = datFin.getMonth();
	AnyoFin = datFin.getYear();
	
	if (AnyoFin > AnyoIni)
	{
		return true;
	}	
	else
	{
		if (AnyoFin == AnyoIni)
		{
			if 	(MesFin > MesIni)
				return true;
			else
			{	
				if 	(MesFin == MesIni)
				{
					if (diaFin > diaIni)
						{
						return true;
						}
					else
						{
						return false;	
						}
				}	
				else
				
					return false;
			}	
		}
		else
			return false;
	}
}
// Convierte una cadena(con Formato Fecha) a Fecha
function str2Date(strFecha)

/* Admite fechas en formato dd/mm/yy d/mm/yy dd/m/yy d/m/yy dd/mm/yyyy d/mm/yyyy dd/m/yyyy d/m/yyyy 
   dd-mm-yy d-mm-yy dd-m-yy d-m-yy dd-mm-yyyy d-mm-yyyy dd-m-yyyy d-m-yyyy 
*/
{
	var posdia,posmes,dia,mes,ano;
	
	if (strFecha.indexOf("/") != - 1)
	{
		posdia = strFecha.indexOf("/");
		dia =  strFecha.substring(0,posdia);
		posmes = strFecha.indexOf("/",posdia+1);
		mes	= strFecha.substring(posdia+1,posmes);
		ano = strFecha.substring(posmes+1,strFecha.length);	
		if (ano < 100)
		{
			ano = parseInt(ano) + 2000;
		}
		return new Date(ano,mes-1,dia);
	}
	
	if (strFecha.indexOf("-") != - 1)
	{
		posdia = strFecha.indexOf("-");
		dia =  strFecha.substring(0,posdia);
		posmes = strFecha.indexOf("-",posdia+1);
		mes	= strFecha.substring(posdia+1,posmes);
		ano = strFecha.substring(posmes+1,strFecha.length);	
		if (ano < 100)
		{
			ano = parseInt(ano) + 2000;
		}
		return new Date(ano,mes-1,dia);	
	}
	
	dia = strFecha.substring(0,2);
	mes = strFecha.substring(2,4);
	ano = strFecha.substring(4,strFecha.length);
	if (ano < 100)
		{
			ano = parseInt(ano) + 2000;
		}
	return new Date(ano,mes-1,dia);
	
}
/****************************************************************/

// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c ... in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function Email(s)
{   if (Vacio(s)) 
       if (Email.arguments.length == 1) return defaultEmptyOK;
       else return (Email.arguments[1] == true);
   
    // is s whitespace?
    if (EnBlanco(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function NIF(strNif)
{
	var arrLetra = 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');

	if (strNif.length < 9) return false;
	
	
	var n = strNif.substring(0, 8);
	if (Number(n) == NaN) return false;
		 
	var l = strNif.substring(8, 9);
	var letra = l.charCodeAt(0);
	if (!(letra >= 65 && letra <= 90)) return false;
	var position =Number(n)%23;
	if (arrLetra[position] != l) return false;
	
	return true;
}

function LongMax(strField, nLength)
{
	if (strField.length > nLength) {
		return false;
	} else
		return true;
}

function LongMin(strField, nLength)
{
	if (strField.length < nLength) {
		return false;
	} else 
		return true;
}

function Rango(valor,min,min){
   var numero=parseInt(valor);
   if (!(numero>=min && numero<=min)){
		return(false);
   }
   return(true);
}

function numero(valor){
   var nume=parseInt(valor);
   if ((nume != valor)){
	return(false);
   }
   return(true);
}

function numeroreal(valor){
   var nume = parseFloat(valor);
   if ((nume != valor)){
	return(false);
   }
   return(true);
}

function ConvertComa(objTxt){
   var strCadena = objTxt.value;
   objTxt.value = strCadena.replace(/,/g,".");
}

function ErasePunto(objCampo){
   var strCadena = objCampo.value;
   objCampo.value = strCadena.replace(/\./g,"");
}

function EraseBlank(objCampo){
   var strCadena = objCampo.value;
   objCampo.value = LTrim(RTrim(strCadena));
}

function ConvToUpper(objCampo){
	objCampo.value = objCampo.value.toUpperCase();
}

function RTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0;
	
	if (EnBlanco(str)){
		return "";
	}
	else{
		for (i = str.length - 1; i >= 0 && endpos == 0; i = i - 1) {
			c = str.charAt(i);
			if (whitespace.indexOf(c) == -1)
				endpos = i;
		}

		return str.substring(0,endpos+1);
	}
}

function LTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var pos = 0;

	if (EnBlanco(str)){
		return "";
	}
	else{
		for (i = 0; i <= str.length - 1; i = i + 1) {
			c = str.charAt(i);
			if (whitespace.indexOf(c) == -1){
				pos = i;
				break;
			}
		}
		return str.substring(pos,str.length);
	}
}

function Trim(strTrim){
	var str = new String(strTrim);
	if(EnBlanco(str))	return "";
	else{
		strTrim = RTrim(strTrim);
		strTrim = RTrim(strTrim);
		return strTrim;
	}
}


//-------------------
//MENUS DESPLEGABLES
//------------------

 /* Objeto TNavegador */
//
// function TNavegador() {
//   this.NS4 = document.layers;
//   //this.NS6 = document.getElementById;
//   this.DOM = document.getElementById;
//   this.IE4 = document.all;
//
 //  this.DHTML = this.NS4 || this.DOM || this.IE4;
  // }

 //var Navegador = new TNavegador();
//
// var Menu = new Array();
// var MenuActivo = null;  // Inicialmente no hay menús activos
//
 /* Métodos de TMenu */
 /* TMenu.Activar */
//
// function ActivarTMenu() {
//   if (Navegador.DHTML && MenuActivo != this) {
//     // Podría ser null, de ahí la comparación
  //   if (MenuActivo) MenuActivo.Ocultar();
//
  //   MenuActivo = this;
    // this.Mostrar();
//     }
//   }
//
 /* TMenu.Mostrar */

// function MostrarTMenu() {
//   eval(this.sRefCapa + this.sRefEstilo
//     + '.visibility = "visible"');
//   }

 /* TMenu.OcultarTMenu */

// function OcultarTMenu() {
//   eval(this.sRefCapa + this.sRefEstilo
//     + '.visibility = "hidden"');
//   }
//
 /* TMenu.MoverA */

// function MoverTMenuA(x, y) {
//   if (Navegador.DHTML) {
//     eval(this.sRefCapa + this.sRefEstilo
//       + this.sRefTop + ' = y');
//     eval(this.sRefCapa + this.sRefEstilo
//       + this.sRefLeft + ' = x');
//     }
  // }

 /* Objeto TMenu */

// function TMenu(IdCapa, PosX, PosY) {
//   this.Activar = ActivarTMenu;
//   this.Mostrar = MostrarTMenu;
//   this.Ocultar = OcultarTMenu;
//
//   this.MoverA = MoverTMenuA;
//
//   this.sRefCapa = Navegador.NS4 ? 'document["' + IdCapa + '"]' :
//                     'document.all["' + IdCapa + '"]';
//  this.sRefEstilo = Navegador.NS4 ? '' : '.style';
//   this.sRefLeft = Navegador.NS4 ? '.left' : '.pixelLeft';
//   this.sRefTop = Navegador.NS4 ? '.top' : '.pixelTop';
//
//   this.MoverA(PosX, PosY);
  // }


// function OcultarTMenuActivo(e) {
//   if (MenuActivo) {
//     MenuActivo.Ocultar();
//     MenuActivo = null;
//     }
//   }

// function InicializarTMenus() {
//   if (Navegador.DHTML) {
//     if (Navegador.NS4)
//       document.captureEvents(Event.MOUSEUP);
//     document.onmouseup = OcultarTMenuActivo;
//     }

  // Menu[0] = new TMenu("Menu0", 146, 129);
//   Menu[1] = new TMenu("Menu1", 146, 159);
//   }

<!-- window.onload = InicializarTMenus; -->





// Objeto de deteccion del navegador
function DetectorNavegador() {
  this.NS4 = document.layers;
  this.IE4 = document.all;
  this.DOM = document.getElementById;
  this.DHTML = this.NS4 || this.IE4 || this.DOM;
}

var soporta = new DetectorNavegador();
var menu = new Array();
var menuActivo = null;

// Objeto Menu
function activarMenu() {
  if (soporta.DHTML && menuActivo != this) {
    if (menuActivo) menuActivo.Ocultar();
    menuActivo = this;
    this.Mostrar();
  }
}

function mostrarMenu() {
  eval(this.capaRefStr + this.estiloRefStr + '.visibility = "visible"');
  if (soporta.DOM)
	this.domRef.style.display = "block";
}

function ocultarMenu() {
  eval(this.capaRefStr + this.estiloRefStr + '.visibility = "hidden"');
}

function estado_fecha_entraMenu() {
  document.all["imagen_oculta"].style.visibility = "visible"
  document.all["campo_oculta"].style.visibility = "hidden"
}

function estado_fecha_salMenu() {
  document.all["imagen_oculta"].style.visibility = "hidden"
  document.all["campo_oculta"].style.visibility = "visible"
}

function cambiarPosicionMenu(top, left) {
  eval(this.capaRefStr + this.estiloRefStr + this.topRefStr + ' = top');
  eval(this.capaRefStr + this.estiloRefStr + this.leftRefStr + ' = left');
  if (soporta.DOM)
	this.domRef.style.display = "none";
}

function Menu(capaID, top, left) {
  this.Activar = activarMenu;
  this.Mostrar = mostrarMenu;
  this.Ocultar = ocultarMenu;
  this.cambiarPosicion = cambiarPosicionMenu;
  if (soporta.DOM) {
    this.domRef = document.getElementById(capaID);
    this.domRef.style.display = "none";
  }	
  this.capaRefStr = (soporta.NS4) ?
    'document["'+capaID+'"]' :
    ((soporta.IE4) ? 'document.all["'+capaID+'"]' : 'this.domRef');
  this.estiloRefStr = (soporta.NS4) ? '' : '.style';
  this.topRefStr = (soporta.IE4) ? '.pixelTop' : '.top';
  this.leftRefStr = (soporta.IE4) ? '.pixelLeft' : '.left';
  this.cambiarPosicion(top, left);
}

// Manejo de eventos
function ocultarMenuActivo(e) {
  if (menuActivo) {
    menuActivo.Ocultar();
    menuActivo = null;
  }
}

// Inicializacion
function InicializarTMenus() {
  if (soporta.DHTML) {
    if (soporta.NS4)
      document.captureEvents(Event.MOUSEUP);
    document.onmouseup = ocultarMenuActivo;
  }
  Menu[0] = new Menu("Menu0", 185, 100);
}


function esEntero(numero)
{
	for (var i = 0; i < numero.length; i++)
		{
		var oneChar = numero.charAt(i)			
		if ((oneChar < "0" || oneChar > "9") )
			return(false)
		}
	return (true)
}

function esDecimal(numero)
{
	for (var i = 0; i < numero.length; i++)
		{
		var oneChar = numero.charAt(i)			
		if ((oneChar < "0" || oneChar > "9") && (oneChar != "," || oneChar != "."))
			return(false)
		}
	return (true)
}

function validaCorreo(valor) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
    return (true)
  } else {
    alert("La dirección de email es incorrecta.");
    return (false);
  }
}

function validaCP(valor){ 
    CPValido=true 
    //si no tiene 5 caracteres no es válido 
   if (valor.length != 5){ 
         CPValido=false; 
   }else{ 
		if (esEntero(valor)){ 
            CPValido = true;
		}else{
		 	CPValido = false;
		}
   }
   return CPValido 
} 

function validaTelefono(valor){

	if(valor.length < 9){
		return false
	}else{
		return(esEntero(valor))
	}
}

function validaTexto(valor){

	var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóú ";
  var allValid = true;
  for (i = 0;  i < valor.length;  i++)
  {
    ch = valor.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
		break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }

}

function validaNIF(valor)
{
	var arrLetra = 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');
	if (!(valor.length == 9)){
		 return false;
	}else{
		if(esEntero(valor.substring(0,1))){
			var n = valor.substring(0, 7);
			if (!esEntero(n)){
			 	return false;
			}else{
				var m = valor.substring(8, 9);
				var letra = m.toUpperCase().charCodeAt(0);
				if (!(letra >= 65 && letra <= 90)){
					 alert("3")
					 return false;
				}else{
					return true;
				}
			}
		}else{
			return CompruebaDatos(valor)	
		}
	}
}

function CompruebaDatos(elCIF)  
{ 
  var resul = false; 
  var temp = elCIF.toUpperCase(); // pasar a mayúsculas 
  if (!/^[A-Za-z0-9]{9}$/.test(temp))  // Son 9 dígitos?  

     alert ("Longitud incorrecta, un CIF consta de 9 dígitos"); 

  else if (!/^[ABCDEFGHKLMNPQS]/.test(temp)) // Es una letra de las admitidas ? 

     alert("El primer dígito del 'CIF' es incorrecto, debe ser una letra de las siguientes: A,B,C,D,E,F,G,H,K,L,M,N,P,Q,S "); 

  else  

     resul = true; 

  return resul; 
} 
  

// Función de validación del CIF, indica el dígito de control. 
// La función recibe el CIF completo: A58818501 
function ValidaCIF(F)  
{ 

  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(F.elCIF.value.substr(i-1,1)) ]; 
      temp = temp + parseInt(F.elCIF.value.substr(i,1)); 
    }; 

  temp = temp + v1[ parseInt(F.elCIF.value.substr(7,1)) ]; 

  temp = (10 - ( temp % 10)); 

  if( temp == 10 ) 
    alert( "El dígito de control es: J ó 0" ); 
  else 
    alert( "El dígito de control es: "+temp );  

  return true; 
}


function comprueba()
{
	if(document.form.producto.value == "no1")
	{
		alert("No existen productos.")		
	}else if(document.form.producto.value == "no2"){
			alert("Producto erroneo.")
	}else if(document.form.unidades.value > 1000){
			alert("La cifra máxima de unidades es 1000")
	}else{
		if(document.form.unidades.value == ""){
			alert("Debes poner una cantidad.")
		}else{
			if(esEntero(document.form.unidades.value)){
				document.form.action = "./añade.asp"
				document.form.submit()
			}else{
			 	alert("Solo puedes poner numeros.")	
			}
		}
	}		
}