
function valida_cif(texto)
{
		var pares = 0;
		var impares = 0;
		var suma;
		var ultima;
		var unumero;
		var uletra = new Array('J', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I');
		var xxx;
		
		texto = texto.toUpperCase();
		
		var regular = new RegExp(/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g);
		if (!regular.exec(texto)) return false;
				
		ultima = texto.substr(8,1);
	
		for (var cont = 1 ; cont < 7 ; cont ++){
				xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + '0';
				impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
				pares += parseInt(texto.substr(cont,1));
		}
		xxx = (2 * parseInt(texto.substr(cont,1))).toString() + '0';
		impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
		
		suma = (pares + impares).toString();
		unumero = parseInt(suma.substr(suma.length - 1, 1));
		unumero = (10 - unumero).toString();
		if(unumero == 10) unumero = 0;
		
		if ((ultima == unumero) || (ultima == uletra[unumero]))
				return true;
		else
				return false;
	
} 
function valida_nif(nif)
{
	var 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','T');
	var expnif = /^\s*([0-9]{8})\s*([TRWAGMYFPDXBNJZSQVHLCKE])\s*$/;
	nif = nif.toUpperCase();
	if (expnif.test(nif))
	{
		campos = nif.split('');
		total = '';
		for (var i=0;i< campos.length -1; i++)
		{
			total += campos[i];	
		}
		total = total % 23;
		letra = letras[total];
		
		if (letra == campos[campos.length -1])
		{
			return true;
		}
	}
	return false;
}
function getElementsByClass(searchClass) 
{
	var classElements = new Array();
	node = document;
	tag = '*';
	var els = node.getElementsByTagName(tag);
	j = 0;
	var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)")
	for (i = 0; i < els.length; i++) 
	{
		if ( pattern.test(els[i].className) ) 
		{
		
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function ensanchar()
{

	var ele = $('cabecera');
	var caja = $('caja');
	var centro = $('centro');
	var maxheight = ($('content').offsetHeight + 5 > $('menu').offsetHeight) ? $('content').offsetHeight + 5 : $('menu').offsetHeight;
	maxheight = ($('centro').offsetHeight > maxheight) ? $('centro').offsetHeight : maxheight;
	caja.style.width = ele.width + 'px';
	var newheight = maxheight + $('cabecera').offsetHeight + $('pie').offsetHeight;
	caja.style.height = newheight + 'px';

}
function pause(millisecondi)
{
    var now = new Date();
    var exitTime = now.getTime() + millisecondi;

    while(true)
    {
        now = new Date();
        if(now.getTime() > exitTime) return;
    }
}
function muestra(cod)
{
	var el = document.getElementById(cod);
	if (el.style.display == '') 
	{
		el.style.display = 'none';
	}
	else
	{
		el.style.display = '';
	}
	ensanchar();
}

function check_contacto()
{
	var result = '';

	if (document.enviar.nombre.value == '') result += 'Indique un nombre'+"\n";

	if (! mail.test(document.enviar.mail.value)) result += 'E-Mail incorrecto'+"\n";

	if (document.enviar.consulta.value == '') result += 'Indique una consulta a realizar'+"\n";
	
	if (result == '')
	{
		document.enviar.sub.value = 'enviar';
		document.enviar.submit();
	}
	else
	{
		alert (result);
	}
}

function op(variable,m){
   var i;
   for(i=0;i<document.productes.elements.length;i++)
      if( document.productes.elements[i].name == variable)
      {
         var s = document.productes.elements[i].value;
         var v = parseInt(s);
         if( v < 0 || isNaN(v) || isNaN(s) ){
            v = 0;
         }else{
            if( m == '+' )
               v ++;
            if( m == '-' && v > 0)
               v --;
         }
      document.productes.elements[i].value = v;
   }
}


function compra( id )
{
   var i;
   var quantitat = 0;
   for(i=0;i<document.productes.elements.length;i++)
      if( document.productes.elements[i].name == 'prod_'+id )
      {
         var s = document.productes.elements[i].value;
         quantitat = parseInt(s);
         if( quantitat <= 0 || isNaN(quantitat) || isNaN(s) )
            quantitat = 0;
      }


   if( quantitat > 0 )
   {
      document.productes.pid.value = id;
      document.productes.operacio.value = 'comprar';
      document.productes.submit();
   }
   else
   {
      alert('Debe seleccionar un numero de unidades mayor de cero');
   }
}

function esborra( id )
{
   document.productes.pid.value = id;
   document.productes.operacio.value = 'esborrar';
   document.productes.submit();
}

function ordenar( elm, dir )
{
   document.productes.orderby.value = elm;
   document.productes.sentit.value  = dir;
   document.productes.submit();
}

function compratinc( id )
{
   document.productes.pid.value = id;
   document.productes.operacio.value = 'incrementar';
   document.productes.submit();
}

function changePopup()
{
  if (avisoCompra == 0)
  	{
		avisoCompra = 1;
	}
	else avisoCompra = 0;
	
	new Ajax.Request('/scripts/ajax.php?alertCarro=change');
}

function compra_unitat( id )
{
	if (avisoCompra == 1)
		{
	Dialog.confirm("<strong>Añadir al Carro</strong><p>Se dispone a añadir producto indicado a la cesta de la compra.</p><p>Puede ver en todo momento su contenido pulsando en el enlace \"Ver Cesta\", o bien directamente en la lista a la derecha de su pantalla.</p><div align='center'><img src='/botiga_ima/miniCesta.jpg' alt='Cesta'><br><input type='checkbox' checked='true' id='alertCompra' name='alertCompra' onClick='javascript:changePopup()'/>Mostrar este aviso la próxima vez</div>", 
				   { width:500, height:300, cancelLabel: "No Añadir", okLabel: "¡Confirmar y Añadir a la Cesta!", className:"alphacube", id: "dialog"+id, 
				   cancel:function(win)
				   		{
						}, 
					ok:function(win) 
						{	
					 	document.productes.pid.value = id;
					  	document.productes.operacio.value = 'comprar';
					  	document.productes.submit(); 
						return true;
						} 
					});
		}
		else
		{
			document.productes.pid.value = id;
			//alert (document.productes.pid.value);
			document.productes.operacio.value = 'comprar';
			document.productes.submit(); 
			//return true;
		}
}

function compratdec( id , num )
{
   if( num < 2 )
   {
      esborra(id);
   }
   else
   {
      document.productes.pid.value = id;
      document.productes.operacio.value = 'decrementar';
      document.productes.submit();
   }
}
function openPWResize(href, title, width, height) {
	var x = (screen.availWidth - width)/2;
	var y = (screen.availHeight - height)/2;
	var w = window.open(href, title, "width=" + width + ",height=" + height + ",top=" + y + ",left=" + x + ",scrollbars=yes,resizable=yes");
	w.focus();
}

function closePW() { self.close(); }

var alfa = /^[,\.a-zA-Z\xE1\xE0\xE9\xE8\xED\xF1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FC\xC1\xC0\xC7\xC8\xCD\xD1\xD2\xD3\xCF\xDA\xDC\xAA\xBA\s\-/'\\])+$/;

function IsNIF(nif)
{
	nif = nif.replace(/\-/g, "");
	nif = nif.replace(/\./g, "");
	nif = nif.replace(/\s/g, "");
	if (nif.length != 9) return false;
	else if (!/^\d+$/.test(nif.substring(0, 8))) return false;
	else if (!/^[a-zA-Z]$/.test(nif.substring(8, 9))) return false;
	else
	{
		var ControlValue = 0 
		var NIFCharIndex = 0 
		var NIFChars = 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')
		var NIFNumber = nif.substring(0, 8) 
		var NIFChar = nif.substring(8, 9) 
		NIFChar = NIFChar.toUpperCase() 
		ControlValue = NIFNumber / NIFChars.length
		ControlValue = Math.floor(ControlValue);
		ControlValue = ControlValue * NIFChars.length
		NIFCharIndex = NIFNumber - ControlValue
		return (NIFChar == NIFChars[NIFCharIndex]) ? true : false;
	}
}



function IsCIF(cif)
{
	cif = cif.replace(/\-/g, "");
	cif = cif.replace(/\./g, "");
	cif = cif.replace(/\s/g, "");
	//Comprueba que tenga 9 d�gitos, el primero debe ser una letra y el resto n�meros
	if (!/^([A-Z]\d{8})|([PX]\d{7}[A-J])$/.test(cif.toUpperCase()))
		return false;
	//Comprueba que la letra sea una de las posibles
	if (!/^[ABCDEFGHKLMPQSX]/.test(cif.toUpperCase()))
		return false;

	//Comprueba el d�gito de control del CIF
	return ComprobarDigitoControlCIF(cif);
}

function ComprobarDigitoControlCIF(cif)
{
	var arrayCIF
	var sumaDigitosPares = 0;
	var sumaDigitosImpares = 0;
	var numero;
	var arrayNumero;
	var digitoControl;
	//mete el cif en un array
	arrayCIF = cif.split("");
	
	//Suma los d�gitos pares de la cadena resultante de quitar el primer y �ltimo caracter del CIF
	for(i = 2; i < arrayCIF.length - 1; i = i + 2)
	{
		sumaDigitosPares = sumaDigitosPares + parseInt(arrayCIF[i]);
	}
	//Multiplicar por 2 los d�gitos impares de la cadena resultante de quitar el primer y �ltimo caracter del CIF y con cada resultado, sumar sus d�gitos.
	//Sumarlo todo
	for(i = 1; i < arrayCIF.length - 1; i = i + 2)
	{
		numero = arrayCIF[i] * 2;
		if (numero > 9)
		{
			numero = (numero % 10) + 1
		}
		sumaDigitosImpares = sumaDigitosImpares + numero;
	}

	//Sumar la suma de d�gitos pares y la de d�gitos impares, Coger la �ltima cifra del n�mero obtenido y restarle 10
	numero = sumaDigitosPares + sumaDigitosImpares
	for (i = numero; i >= 0; i = i - 10)
	{
		numero = i;
	}
	digitoControl = 10 - numero;
	//Para los tipos de sociedades P y X el d�gito de control debe ser una letra
	if (arrayCIF[0].toUpperCase() == "P" || arrayCIF[0].toUpperCase() == "X")
	{
		digitoControl = String.fromCharCode(digitoControl + 64);
	}

	//Comprueba si el d�gito de control se corresponde correctamente
	if (digitoControl.toString() == arrayCIF[8])
		return true;
	else
		return false;
}


