// JavaScript Document
function colocaStage(){
	


	/* iconos del menu */
	if(getWidth()>1000){
	inicioContenido = Math.floor((getWidth()-1000)/2);
	}else{
	inicioContenido = 0;	
	}
	posIconos = inicioContenido+605
	document.getElementById("iconos").style.left = posIconos+"px";
	if(navigator.appName.indexOf("osoft")>-1){
		posCarrito = inicioContenido+925;
	}else{
		posCarrito = inicioContenido+915;
	}
	document.getElementById("icoVercesta").style.left = posCarrito+"px";
	document.getElementById("iconos").style.display="inline";
	if(String(self.location).indexOf("articulo.php")>0){
		muestraConfigEstampacion(document.getElementById("cantidadserigrafia").value);
	}

}

window.onload = colocaStage;
window.onresize = colocaStage;

function getHeight() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}


function getWidth() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myWidth;
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
	
}
function setColor(id,pack){
	
	document.getElementById("cantidadSubtotal").innerHTML = "0.00\u20AC";
	document.getElementById("cantidadSubtotal2").innerHTML = "0.00\u20AC";

	objcolor = document.getElementById("color-"+id);
	objok = document.getElementById("marca-color");
	color1 = document.getElementById("color-"+id+"-1").title;
	if(objcolor.className=="colorCompleto"){
		color2 = document.getElementById("color-"+id+"-2").title;
		posx = findPos(objcolor)[0]+12;
		posy = findPos(objcolor)[1]+15;
		document.getElementById("colorActual").innerHTML = "["+color1+"/"+color2+"]";
	}else{
		posx = findPos(objcolor)[0]+12;
		posy = findPos(objcolor)[1]+5;
		document.getElementById("colorActual").innerHTML = "["+color1+"]";	
	}

	objok.style.top = posy+"px";
	objok.style.left = posx+"px";
	objok.style.display="inline";
	
	FAjax ("get-tallas.php","celdaTallas","articulo="+idArticulo+"&color="+id+"&pack="+pack,"POST",muestraTallas);
	
	
	datos = "articulo="+idArticulo+"&color="+id;
	FAjax ("get-stocktallas.php","txtStock",datos,"POST");
	FAjax ("get-stocktallas.php","txtStock2",datos,"POST");
	
	idColor = id;
	document.getElementById("inp_color").value = idColor;
	
}

function muestraTallas(){
	document.getElementById("tr-tituloTallas").style.display="";
	document.getElementById("tr-contenidoTallas").style.display="";
	if(document.getElementById("tr-tituloNombres")!=null){
		document.getElementById("tr-tituloNombres").style.display="";
	}
	document.getElementById("tr-contenidoNombres").style.display="";	
	
	if(tallas){
		total_tallas = document.getElementById("total_tallas").value
		for(i=1;i<=total_tallas;i++){
			nombretalla = document.getElementById("talla-"+i).value

			for(j=0;j<tallas.length;j++){
				if(tallas[j][0] == nombretalla){
					document.getElementById("cantidadtalla-"+i).value = tallas[j][1];
				}
			}
		}
		tallas=null;
	}
	if(document.getElementById("seri_nombres")!=null){
		if(document.getElementById("seri_nombres").checked || document.getElementById("seri_numeros").checked ){
			actualizaTablaNombres();
		}
	}
}

function ocultaTallas(){
	
	if(document.getElementById("seri_nombres")!=null) document.getElementById("seri_nombres").checked=false
	if(document.getElementById("seri_nombres")!=null) document.getElementById("seri_numeros").checked=false
	if(document.getElementById("tablaConfigNombresNumeros")!=null) document.getElementById("tablaConfigNombresNumeros").style.display="none";		
	if(document.getElementById("colorNumActual")!=null) document.getElementById("colorNumActual").innerHTML = "&nbsp;";	
	if(document.getElementById("marca-colornum")!=null) document.getElementById("marca-colornum").style.display="none";
	
	
	
	if(document.getElementById("seri_tipo_regular")) document.getElementById("seri_tipo_regular").checked=false
	if(document.getElementById("seri_tipo_cincuenta")) document.getElementById("seri_tipo_cincuenta").checked=false
	if(document.getElementById("seri_tipo_gratis")) document.getElementById("seri_tipo_gratis").checked=false

	if(document.getElementById("donde_nombres")){
		document.getElementById("donde_nombres").selectedIndex=0;
		document.getElementById("donde_nombres").disabled=true;
		document.getElementById("donde_nombres").style.setProperty("color","#cccccc",null);
		document.getElementById("donde_nombres").style.display="none";	
	}
	
	if(document.getElementById("cual_nombres")){
		document.getElementById("cual_nombres").value="";
		document.getElementById("cual_nombres").disabled=true;
		document.getElementById("cual_nombres").style.display="none";	
	}

	if(document.getElementById("donde_numeros")){
		document.getElementById("donde_numeros").selectedIndex=0;
		document.getElementById("donde_numeros").disabled=true;
		document.getElementById("donde_numeros").style.setProperty("color","#cccccc",null);
		document.getElementById("donde_numeros").style.display="none";	
	}
	
	if(document.getElementById("cual_numeros")){
		document.getElementById("cual_numeros").value="";
		document.getElementById("cual_numeros").disabled=true;
		document.getElementById("cual_numeros").style.display="none";
	}
}


function tallaMas(talla,pack){
	
	//Si es un pack el valor será mayor que uno
	if(pack>1){
		if((Number(document.getElementById("cantidadtalla-"+talla).value)%pack)==0){
			valActual = Number(document.getElementById("cantidadtalla-"+talla).value);
			document.getElementById("cantidadtalla-"+talla).value = Number(valActual) + Number(pack);
		}else{
			alert("El valor introducido no es multiplo de "+pack);
		}
		//valActual = Number(document.getElementById("cantidadtalla-"+talla).value);
		//document.getElementById("cantidadtalla-"+talla).value = Number(valActual) + Number(pack);
	}else{
		valActual = Number(document.getElementById("cantidadtalla-"+talla).value);
		document.getElementById("cantidadtalla-"+talla).value = Number(valActual) + Number(pack);
	}
	document.getElementById("cantidadtalla-"+talla).style.color='#00b2e8';
	
	//ocultaTallas();
	actualizaStockTallas();
}
function tallaMenos(talla,pack){
	valActual = Number(document.getElementById("cantidadtalla-"+talla).value);
	if(valActual>0){
	document.getElementById("cantidadtalla-"+talla).value = Number(valActual) - Number(pack);
	}
	if(valActual>1){
		document.getElementById("cantidadtalla-"+talla).style.color='#00b2e8';
	}else{
		document.getElementById("cantidadtalla-"+talla).style.color='#505500';
	}
	//ocultaTallas();
	actualizaStockTallas();
}

function noTexto(e){
	var keynum;
	var keychar;
	var numcheck;
	
	if(window.event) // IE
	  {
	  keynum = e.keyCode;
	  }
	else if(e.which) // Netscape/Firefox/Opera
	  {
	  keynum = e.which;
	  }

	if(keynum==8 || keynum==9) return true;
	if(keynum>=48 && keynum<=57) return true;
	if(keynum>=96 && keynum<=105) return true;

	return false;
	//keychar = String.fromCharCode(keynum);
	//numcheck = /\d/;
	//return numcheck.test(keychar);
}

function pierdeFoco(obj,pack){
	
	if(pack>1){
		if((Number(obj.value)%pack)==0){
			valActual = Number(obj.value);
			obj.value=valActual;
		}else{
			alert("El valor introducido no es multiplo de "+pack);
			valActual = pack;
			obj.value=valActual;
			}
		//valActual = Number(document.getElementById("cantidadtalla-"+talla).value);
		//document.getElementById("cantidadtalla-"+talla).value = Number(valActual) + Number(pack);
	}else{
		valActual = Number(obj.value);
		obj.value=valActual;
	}
	
	if(valActual>0){
		obj.style.color='#00b2e8';
	}else{
		obj.style.color='#505500';
	}
	calculaSubtotal();
}

function setColorNum(id){
	objcolor = document.getElementById("colornum-"+id);
	objok = document.getElementById("marca-colornum");
	color1 = document.getElementById("colornum-"+id+"-1").title;
	if(objcolor.className=="colorCompleto"){
		color2 = document.getElementById("color-"+id+"-2").title;
		posx = findPos(objcolor)[0]+12;
		posy = findPos(objcolor)[1]+15;
		document.getElementById("colorNumActual").innerHTML = "["+color1+"/"+color2+"]";
	}else{
		posx = findPos(objcolor)[0]+12;
		posy = findPos(objcolor)[1]+5;
		document.getElementById("colorNumActual").innerHTML = "["+color1+"]";	
	}

	objok.style.top = posy+"px";
	objok.style.left = posx+"px";
	objok.style.display="inline";
	
	idColorNum = id;
	document.getElementById("inp_colornum").value = idColorNum;
}

function evaluaNombres(){
	var seri_nombres;
	var seri_numeros;
	
	if(document.getElementById("seri_nombres")!=null) seri_nombres = document.getElementById("seri_nombres").checked;
	else seri_nombres = false;
	
	if(document.getElementById("seri_numeros")!=null) seri_numeros = document.getElementById("seri_numeros").checked;
	else seri_numeros = false;
	
	
	if(seri_nombres){
		if(document.getElementById("donde_nombres")){
			document.getElementById("donde_nombres").disabled=false;
			document.getElementById("donde_nombres").style.setProperty("color","#00afe7",null);
			document.getElementById("donde_nombres").style.display="";
		}
	}
	else{
		if(document.getElementById("donde_nombres")){
			document.getElementById("donde_nombres").selectedIndex=0;
			document.getElementById("donde_nombres").disabled=true;
			document.getElementById("donde_nombres").style.setProperty("color","#cccccc",null);
			document.getElementById("donde_nombres").style.display="none";	
			document.getElementById("cual_nombres").value="";
			document.getElementById("cual_nombres").disabled=true;
			document.getElementById("cual_nombres").style.display="none";	
		}
	}
	if(seri_numeros){
		if(document.getElementById("donde_numeros")){
			document.getElementById("donde_numeros").disabled=false;
			document.getElementById("donde_numeros").style.setProperty("color","#00afe7",null);
			document.getElementById("donde_numeros").style.display="";	
		}
	}
	else{
		if(document.getElementById("donde_numeros")){
			document.getElementById("donde_numeros").selectedIndex=0;
			document.getElementById("donde_numeros").disabled=true;
			document.getElementById("donde_numeros").style.setProperty("color","#cccccc",null);
			document.getElementById("donde_numeros").style.display="none";	
			document.getElementById("cual_numeros").value="";
			document.getElementById("cual_numeros").disabled=true;
			document.getElementById("cual_numeros").style.display="none";	
		}
	}
	

	if(seri_nombres || seri_numeros){
		actualizaTablaNombres();
	}
	else{
		ocultaTallas();
		actualizaStockEstampaciones();
	}
}

function especifiqueCual(target,queValor){
	if(queValor==1){
		document.getElementById(target).value="Especifique en cual";
		document.getElementById(target).disabled=false;
		document.getElementById(target).style.display="";	
	}else{
		document.getElementById(target).value="";
		document.getElementById(target).disabled=true;
		document.getElementById(target).style.display="none";	
	}
	calculaSubtotal();
}

function actualizaStockTallas(){
	totalTallas = 	document.getElementById("total_tallas").value;

	datos="totalTallas="+totalTallas+"&articulo="+idArticulo+"&color="+idColor;
	for(i=1;i<=totalTallas;i++){
		datos += "&talla"+i+"="+document.getElementById("talla-"+i).value;
		datos += "&cantidad"+i+"="+document.getElementById("cantidadtalla-"+i).value;
	}
	FAjax ("get-stocktallas.php","txtStock",datos,"POST");
	FAjax ("get-stocktallas.php","txtStock2",datos,"POST");

	calculaSubtotal();

}


function actualizaStockEstampaciones(){
	totalTallas = 	document.getElementById("total_tallas").value;
	totalEstampaciones = 	document.getElementById("cantidadserigrafia").value;
	
	datos="totalTallas="+totalTallas+"&totalEstampaciones="+totalEstampaciones+"&articulo="+idArticulo+"&color="+idColor;
	for(i=1;i<=totalTallas;i++){
		datos += "&talla"+i+"="+document.getElementById("talla-"+i).value;
		datos += "&cantidad"+i+"="+document.getElementById("cantidadtalla-"+i).value;
	}
	for(j=1;j<=totalEstampaciones;j++){
		datos += "&estampacion"+j+"="+document.getElementById("estampacion_tipo_"+j).value;
	}
	if(document.getElementById("seri_nombres")!=null){
		if(document.getElementById("seri_nombres").checked){
			datos += "&seri_nombres=1";			   
		}
	}
	if(document.getElementById("seri_numeros")!=null){
		if(document.getElementById("seri_numeros").checked){
			datos += "&seri_numeros=1";
		}
	}
	
	FAjax ("get-stocktallas.php","txtStock",datos,"POST");
	FAjax ("get-stocktallas.php","txtStock2",datos,"POST");
	
	calculaSubtotal();

}


function actualizaTablaNombres(){
	totalTallas = 	document.getElementById("total_tallas").value;
	totalEstampaciones = 	document.getElementById("cantidadserigrafia").value;
	
	datos="totalTallas="+totalTallas+"&totalEstampaciones="+totalEstampaciones+"&articulo="+idArticulo+"&color="+idColor;
	for(i=1;i<=totalTallas;i++){
		datos += "&talla"+i+"="+document.getElementById("talla-"+i).value;
		datos += "&cantidad"+i+"="+document.getElementById("cantidadtalla-"+i).value;
	}
	for(j=1;j<=totalEstampaciones;j++){
		datos += "&estampacion"+j+"="+document.getElementById("estampacion_tipo_"+j).value;
	}
	if(document.getElementById("seri_nombres")!=null){
		if(document.getElementById("seri_nombres").checked){
			datos += "&seri_nombres=1";			   
		}
	}
	if(document.getElementById("seri_numeros")!=null){
		if(document.getElementById("seri_numeros").checked){
			datos += "&seri_numeros=1";
		}
	}
	
	FAjax ("get-stocktallas.php","txtStock",datos,"POST");
	FAjax ("get-stocktallas.php","txtStock2",datos,"POST");

	if((document.getElementById("seri_nombres")!=null) && (document.getElementById("seri_nombres")!=null)){
		if(document.getElementById("seri_nombres").checked && document.getElementById("seri_numeros").checked ){
			FAjax ("get-tablanumnombres.php","celdaNombres",datos,"POST",muestraConfig);
		}else{
			if(document.getElementById("seri_nombres").checked){
				FAjax ("get-tablanombres.php","celdaNombres",datos,"POST",muestraConfig);
			}else{
				FAjax ("get-tablanum.php","celdaNombres",datos,"POST",muestraConfig);
			}
		}
	}
	
	calculaSubtotal();	

}


function muestraConfig(txt){

	document.getElementById("tablaConfigNombresNumeros").style.display="";	
	var numnombres = new Array();
	if(numnombres){
		total_numnombres = document.getElementById("total_numnombres").value;
		
		for(i=1;i<=total_numnombres;i++){
			tmptalla = document.getElementById("numnombres_talla_"+i).value

			for(j=0;j<numnombres.length;j++){
				if(numnombres[j][0] == tmptalla){
					if(document.getElementById("seri_nombres").checked && document.getElementById("seri_numeros").checked ){
						document.getElementById("numnombres_numero_"+i).value = numnombres[j][1];
						document.getElementById("numnombres_nombre_"+i).value = numnombres[j][2];
					}else{
						if(document.getElementById("seri_nombres").checked){
							document.getElementById("numnombres_nombre_"+i).value = numnombres[j][1];
						}
						if(document.getElementById("seri_numeros").checked){
							document.getElementById("numnombres_numero_"+i).value = numnombres[j][1];
						}
					}
					numnombres[j][0]="";
					break;
				}
			}
		}
		numnombres=null;
	}
}

function muestraDondeSerigrafias(){
	valActual = Number(document.getElementById("cantidadserigrafia").value);
	if(valActual>0){
		if(document.getElementById("donde_serigrafias")){
			document.getElementById("tablaDondeSerigrafias").style.display="";	
			document.getElementById("donde_serigrafias").disabled=false;
			document.getElementById("donde_serigrafias").style.setProperty("color","#00afe7",null);
			document.getElementById("donde_serigrafias").style.display="";	
		}
	}
	else{
		if(document.getElementById("donde_serigrafias")){
			document.getElementById("tablaDondeSerigrafias").style.display="none";	
			document.getElementById("donde_serigrafias").selectedIndex=0;
			document.getElementById("donde_serigrafias").disabled=true;
			document.getElementById("donde_serigrafias").style.setProperty("color","#cccccc",null);
			document.getElementById("donde_serigrafias").style.display="none";	
			document.getElementById("cual_serigrafias").value="";
			document.getElementById("cual_serigrafias").disabled=true;
			document.getElementById("cual_serigrafias").style.display="none";	
		}
	}
}

function serigrafiaMas(){
	valActual = Number(document.getElementById("cantidadserigrafia").value);
	if(valActual<4){
		valActual++;
		document.getElementById("cantidadserigrafia").value = valActual;
		document.getElementById("cantidadserigrafia").style.color='#00b2e8';
	}
	muestraConfigEstampacion(valActual);
	muestraDondeSerigrafias();
	actualizaStockEstampaciones();
}
function serigrafiaMenos(){
	valActual = Number(document.getElementById("cantidadserigrafia").value);
	if(valActual>0){
		valActual--
		document.getElementById("cantidadserigrafia").value = valActual;
	}
	if(valActual>0){
		document.getElementById("cantidadserigrafia").style.color='#00b2e8';
	}else{
		document.getElementById("cantidadserigrafia").style.color='#505500';
	}
	muestraConfigEstampacion(valActual);
	muestraDondeSerigrafias();
	actualizaStockEstampaciones();
}
function pierdeFocoSerigrafia(obj){
	valActual = Number(obj.value);
	if(valActual>4){
		valActual=4;	
	}
	obj.value=valActual;
	if(valActual>0){
		obj.style.color='#00b2e8';
	}else{
		obj.style.color='#505500';
	}
	muestraConfigEstampacion(valActual);
}

function muestraConfigEstampacion(v){
	for(i=1;i<5;i++){
		document.getElementById("tablaEstampacion"+i).style.display="none";
	}
	for(i=1;i<=v;i++){
			document.getElementById("tablaEstampacion"+i).style.display="";
	}
	if(v>0){
		document.getElementById("tablaEstampacionComentarios").style.display="";
	}else{
		document.getElementById("tablaEstampacionComentarios").style.display="none";	
	}
	calculaSubtotal();
}

function cambiaTipoEstampacion(num,v){
	if(num==1){
		FAjax ("get-posicionesestampacion.php","debug","tipo="+v,"POST",updatePosiciones1);
		FAjax ("get-descripcionestampacion.php","descripcion_estampacion1","id="+v,"POST");
	}
	if(num==2){
		FAjax ("get-posicionesestampacion.php","debug","tipo="+v,"POST",updatePosiciones2);
		FAjax ("get-descripcionestampacion.php","descripcion_estampacion2","id="+v,"POST");
	}
	if(num==3){
		FAjax ("get-posicionesestampacion.php","debug","tipo="+v,"POST",updatePosiciones3);
		FAjax ("get-descripcionestampacion.php","descripcion_estampacion3","id="+v,"POST");
	}
	if(num==4){
		FAjax ("get-posicionesestampacion.php","debug","tipo="+v,"POST",updatePosiciones4);
		FAjax ("get-descripcionestampacion.php","descripcion_estampacion4","id="+v,"POST");
	}
}

function updatePosiciones1(txt){
	resultado = txt.split(";");
	while(document.getElementById("estampacion_posicion_1").options.length>1){
		document.getElementById("estampacion_posicion_1").options[document.getElementById("estampacion_posicion_1").options.length-1] = null	
	}
	//Empezamos el bucle en 6, porque los valores 0, 1 y 2 son los precios_unidad, minimo y extra
	//Y los valores 3, 4 y 5 son precios_unidad_doble, mínimo y extra, de la doble estampación
	for(i=6;i<resultado.length-1;i++){
		document.getElementById("estampacion_posicion_1").options.add(new Option(resultado[i],resultado[i]))	
	}
	document.getElementById("estampacion_preciounidad_1").value=resultado[0];
	document.getElementById("estampacion_precioextra_1").value=resultado[1];
	document.getElementById("estampacion_preciominimo_1").value=resultado[2];
	document.getElementById("estampacion_preciounidad_doble_1").value=resultado[3];
	document.getElementById("estampacion_precioextra_doble_1").value=resultado[4];
	document.getElementById("estampacion_preciominimo_doble_1").value=resultado[5];

	actualizaStockEstampaciones();
}
function updatePosiciones2(txt){
	resultado = txt.split(";");
	while(document.getElementById("estampacion_posicion_2").options.length>1){
		document.getElementById("estampacion_posicion_2").options[document.getElementById("estampacion_posicion_2").options.length-1] = null	
	}
	//Empezamos el bucle en 6, porque los valores 0, 1 y 2 son los precios_unidad, minimo y extra
	//Y los valores 3, 4 y 5 son precios_unidad_doble, mínimo y extra, de la doble estampación
	for(i=6;i<resultado.length-1;i++){
		document.getElementById("estampacion_posicion_2").options.add(new Option(resultado[i],resultado[i]))	
	}
	document.getElementById("estampacion_preciounidad_2").value=resultado[0];
	document.getElementById("estampacion_precioextra_2").value=resultado[1];
	document.getElementById("estampacion_preciominimo_2").value=resultado[2];
	document.getElementById("estampacion_preciounidad_doble_2").value=resultado[3];
	document.getElementById("estampacion_precioextra_doble_2").value=resultado[4];
	document.getElementById("estampacion_preciominimo_doble_2").value=resultado[5];

	actualizaStockEstampaciones();
}
function updatePosiciones3(txt){
	resultado = txt.split(";");
	while(document.getElementById("estampacion_posicion_3").options.length>1){
		document.getElementById("estampacion_posicion_3").options[document.getElementById("estampacion_posicion_3").options.length-1] = null	
	}
	//Empezamos el bucle en 6, porque los valores 0, 1 y 2 son los precios_unidad, minimo y extra
	//Y los valores 3, 4 y 5 son precios_unidad_doble, mínimo y extra, de la doble estampación
	for(i=6;i<resultado.length-1;i++){
		document.getElementById("estampacion_posicion_3").options.add(new Option(resultado[i],resultado[i]))	
	}
	document.getElementById("estampacion_preciounidad_3").value=resultado[0];
	document.getElementById("estampacion_precioextra_3").value=resultado[1];
	document.getElementById("estampacion_preciominimo_3").value=resultado[2];
	document.getElementById("estampacion_preciounidad_doble_3").value=resultado[3];
	document.getElementById("estampacion_precioextra_doble_3").value=resultado[4];
	document.getElementById("estampacion_preciominimo_doble_3").value=resultado[5];

	actualizaStockEstampaciones();
}
function updatePosiciones4(txt){
	resultado = txt.split(";");
	while(document.getElementById("estampacion_posicion_4").options.length>1){
		document.getElementById("estampacion_posicion_4").options[document.getElementById("estampacion_posicion_4").options.length-1] = null	
	}
	//Empezamos el bucle en 6, porque los valores 0, 1 y 2 son los precios_unidad, minimo y extra
	//Y los valores 3, 4 y 5 son precios_unidad_doble, mínimo y extra, de la doble estampación
	for(i=6;i<resultado.length-1;i++){
		document.getElementById("estampacion_posicion_4").options.add(new Option(resultado[i],resultado[i]))	
	}
	document.getElementById("estampacion_preciounidad_4").value=resultado[0];
	document.getElementById("estampacion_precioextra_4").value=resultado[1];
	document.getElementById("estampacion_preciominimo_4").value=resultado[2];
	document.getElementById("estampacion_preciounidad_doble_4").value=resultado[3];
	document.getElementById("estampacion_precioextra_doble_4").value=resultado[4];
	document.getElementById("estampacion_preciominimo_doble_4").value=resultado[5];

	actualizaStockEstampaciones();
}



function calculaSubtotal(){
	
	var seri_nombres;
	var seri_numeros;
	var precioBase = Number(document.getElementById("precio").value);
	var suplemento = 0;
	var extratotal = 0;
	var iva = 1.18;
	
	if(document.getElementById("seri_nombres")!=null) seri_nombres = document.getElementById("seri_nombres").checked;
	else seri_nombres = false;
	
	if(document.getElementById("seri_numeros")!=null) seri_numeros = document.getElementById("seri_numeros").checked;
	else seri_numeros = false;






	/*********************************************************\
	
	CALCULAMOS EL TOTAL DE UNIDADES
	
	\*********************************************************/
	var totalTallas = Number(document.getElementById("total_tallas").value);
	var totalUnidades = 0;
	for(i=1;i<=totalTallas;i++){
		totalUnidades += Number(document.getElementById("cantidadtalla-"+i).value);
	}



	/*********************************************************\
	
	CALCULAMOS EL TOTAL POR PONER NOMBRES
	
	\*********************************************************/
	var precio_nombres = 3;
	var veces_nombres = 0;
	
	if(seri_nombres){
		if(document.getElementById("donde_nombres")!=null){
			veces_nombres = Number(document.getElementById("donde_nombres").value);
		}
		else veces_nombres = 1;
	}

	precio_nombres = precio_nombres*totalUnidades*veces_nombres*iva;


	/*********************************************************\
	
	CALCULAMOS EL TOTAL POR PONER NÚMEROS
	Calculamos el coste de los números según la cantidad de cifras
	
	\*********************************************************/
	var precio_numeros = 0;
	
	if(document.getElementById("seri_tipo_regular")!=null)
		if(document.getElementById("seri_tipo_regular").checked)
			precio_numeros = 2;
	if(document.getElementById("seri_tipo_cincuenta")!=null)
		if(document.getElementById("seri_tipo_cincuenta").checked)
			precio_numeros = 1;

	if(document.getElementById("seri_tipo_gratis")!=null)
		if(document.getElementById("seri_tipo_gratis").checked)
			precio_numeros = 0;
	
	var veces_numeros = 0;
	var total_cifras = 0
	
	if(seri_numeros){
		if(document.getElementById("donde_numeros")!=null){
			veces_numeros = Number(document.getElementById("donde_numeros").value);
		}
		else veces_numeros = 1;
	}
	
	
	if(document.getElementById("numnombres_numero_1")){
		for(k=1;k<=totalUnidades;k++){
			total_cifras += eval("document.getElementById(\"numnombres_numero_"+k+"\").value.length");
		}
	}
	else{
		if(totalUnidades>9) total_cifras = 9 + (totalUnidades-9)*2;
		else total_cifras = totalUnidades;
	}
	
	precio_numeros = precio_numeros*total_cifras*veces_numeros*iva;

	
	
	
	
	
	
	/*********************************************************\
	
	CALCULAMOS EL TOTAL POR PONER ESTAMPACIONES
		
	\*********************************************************/
 	totalEstampaciones = Number(document.getElementById("cantidadserigrafia").value);
	var veces_estampaciones = 0;
	var precio_unidad = Array();
	var precio_extra = Array();
	var precio_minimo = Array();
	var precio_estampacion = Array();
	var precio_estampacion1 = 0;
	var precio_estampacion2 = 0;
	var precio_estampacion3 = 0;
	var precio_estampacion4 = 0;
	var precio_estampaciones = 0;
	
	if(document.getElementById("donde_serigrafias"))
		veces_estampaciones = Number(document.getElementById("donde_serigrafias").value);
	else veces_estampaciones = 1;

	if(totalEstampaciones > 0){
		for(i=1;i<=totalEstampaciones;i++){
			if(veces_estampaciones == 1){
				precio_unidad[i] = Number(document.getElementById("estampacion_preciounidad_"+i).value);
				precio_extra[i] = Number(document.getElementById("estampacion_precioextra_"+i).value);
				precio_minimo[i] = Number(document.getElementById("estampacion_preciominimo_"+i).value);
				precio_estampacion[i] = Math.max(precio_minimo[i],(precio_unidad[i]*totalUnidades))   + precio_extra[i]  ;
			}
			else{
				precio_unidad[i] = Number(document.getElementById("estampacion_preciounidad_doble_"+i).value);
				precio_extra[i] = Number(document.getElementById("estampacion_precioextra_doble_"+i).value);
				precio_minimo[i] = Number(document.getElementById("estampacion_preciominimo_doble_"+i).value);
				precio_estampacion[i] = Math.max(precio_minimo[i],(precio_unidad[i]*totalUnidades))   + precio_extra[i];
			}
			if(isNaN(precio_estampacion[i])) precio_estampacion[i] = 0;
			precio_estampaciones += precio_estampacion[i];
		}
	}
	
	/*
	Ya no lo multiplicamos por el numero de estampaciones, porque ahora las dobles estampaciones
	tienen su propio precio
	*/
	//precio_estampaciones = precio_estampaciones*veces_estampaciones*iva; 
	
	precio_estampaciones = precio_estampaciones*iva;
	

	/*********************************************************\
	
	CALCULAMOS EL PRECIO BASE
	
	\*********************************************************/
	//Lo primero es comprobar si el tipo de pedido es volumen de compra, para ello miramos la longitud de los arrays.
	var precioBase = Number(document.getElementById("precio").value);
	if(vc_desde!=null){
		if(vc_desde.length>0){
			//Se trata de un volumen de compra
			  for(i=0;i<vc_desde.length;i++){
				  if((totalUnidades>=Number(vc_desde[i]))&&(totalUnidades<=Number(vc_hasta[i]))){
					  var precioBase =vc_precio[i];
				  }
			  }
		}else{
			var precioBase = Number(document.getElementById("precio").value);
		}
	}else{
		var precioBase = Number(document.getElementById("precio").value);
	}
	
	precioBase = precioBase*totalUnidades

	
	
	
	/*********************************************************\
	
	SUMAMOS EL TOTAL DE TODO
	
	\*********************************************************/
	//subtotal = precioBase*totalUnidades + precio_numeros + precio_nombres + precio_estampacion1 + precio_estampacion2 + precio_estampacion3 + precio_estampacion4;
	subtotal = precioBase + precio_numeros + precio_nombres + precio_estampaciones;
	//alert("precioBase="+precioBase+"\ntotalUnidades="+totalUnidades+"\nprecio_nombres="+precio_nombres+"\nprecio_numeros="+precio_numeros+"\nprecio_estampacion1="+precio_estampacion1+"\nprecio_estampacion2="+precio_estampacion2+"\nprecio_estampacion3="+precio_estampacion3+"\nprecio_estampacion4="+precio_estampacion4);
	subtotal = formatAsMoney(subtotal);
	
	



	/*********************************************************\
	
	ANALIZAMOS SI PODEMOS AÑADIR AL CARRITO O NO EL PRODUCTO
	
	\*********************************************************/
	//Si se trata de un pedido minimo variable_total estará definido, en caso contrario simplemente pintamos el boton
	var podemos_comprar = false;
	
	if(variable_total!=""){
		variable_total=Number(variable_total);
		subtotal=Number(subtotal);
		
		//Si se trata de un pedido minimo comprobamos que el subtotal sea mayor que la variable total para mostrar el botón de finalizar
		if((variable_total-1)>=totalUnidades){
			podemos_comprar=false;
		}
		else{
			if(seri_numeros){
				podemos_comprar=false;
				if(document.getElementById("seri_tipo_regular")!=null && document.getElementById("seri_tipo_regular").checked) podemos_comprar=true;
				if(document.getElementById("seri_tipo_cincuenta")!=null && document.getElementById("seri_tipo_cincuenta").checked) podemos_comprar=true;
				if(document.getElementById("seri_tipo_gratis")!=null && document.getElementById("seri_tipo_gratis").checked) podemos_comprar=true;
			}
			else podemos_comprar=true;
		}
	}
	else{
		if(seri_numeros){
			if(seri_numeros){
				podemos_comprar=false;
				if(document.getElementById("seri_tipo_regular")!=null && document.getElementById("seri_tipo_regular").checked) podemos_comprar=true;
				if(document.getElementById("seri_tipo_cincuenta")!=null && document.getElementById("seri_tipo_cincuenta").checked) podemos_comprar=true;
				if(document.getElementById("seri_tipo_gratis")!=null && document.getElementById("seri_tipo_gratis").checked) podemos_comprar=true;
			}
			else podemos_comprar=true;
		}
		else podemos_comprar=true;
	}
	
	
	if(podemos_comprar==true){
		document.getElementById("botonFinalizar").innerHTML="<input type='image' src='images/addcesta.gif' style='float:right;margin-right:20px;margin-top:20px;' alt='añadir a la cesta' />";
	}
	else{
		document.getElementById("botonFinalizar").innerHTML="<img src='images/addcesta2.gif' style='float:right;margin-right:20px;margin-top:20px;' alt='Necesita completar el pedido mínimo' />";
	}
	
	document.getElementById("cantidadSubtotal").innerHTML = subtotal + "\u20AC";
	document.getElementById("cantidadSubtotal2").innerHTML = subtotal + "\u20AC";
	

}

function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function addCesta(){
	if(validarCompra()){
		document.form1.submit();	
	}
}
function validarCompra(){
	if(idColor==0){
		alert("Seleccione el color y las tallas que desea comprar");
		return false;
	}else{
		var totalTallas = Number(document.getElementById("total_tallas").value)
		var totalUnidades = 0;
		for(i=1;i<=totalTallas;i++){
			totalUnidades += Number(document.getElementById("cantidadtalla-"+i).value);
		}	
		if(totalUnidades==0){
			alert("Seleccione las tallas que desea comprar");
			return false;
		}
	}
	
	//comprobamos numeros y nombres 
	seri_nombres = document.getElementById("seri_nombres").checked;
	seri_numeros = document.getElementById("seri_numeros").checked;
	if(seri_nombres || seri_numeros){
		if(idColorNum==0){
			alert("Seleccione el color de los números y los nombres");	
			return false;
		}	
		total_numnombres = document.getElementById("total_numnombres").value		
		if(seri_numeros){
			for(i=1;i<=total_numnombres;i++){
				if(document.getElementById("numnombres_numero_"+i).value== ""){
					alert("Debe indicar el número de todas las equipaciones.");	
					return false;
				}
			}
		}
		if(seri_nombres){
			for(i=1;i<=total_numnombres;i++){
				if(document.getElementById("numnombres_nombre_"+i).value== "" || document.getElementById("numnombres_nombre_"+i).value== "Nombre del jugador"){
					alert("Debe indicar el nombre del jugador de todas las equipaciones.");	
					return false;
				}
			}
		}

	}
	
	
	//comprobamos doble estampacion
	if(seri_nombres || seri_numeros){
		if(seri_nombres){
			if (document.getElementById("donde_nombres").value == "1"){
				if (document.getElementById("cual_nombres").value == "" || document.getElementById("cual_nombres").value == "Especifique en cual"){ 
					alert("Ha decidido poner nombres sólo en una camiseta, pero no ha especificado en cuál de ellas.");
					document.getElementById("cual_nombres").style.setProperty('border','3px solid #f00',null);
					document.getElementById("cual_nombres").style.setProperty('background-color','#f7f0f0',null);
					document.getElementById("cual_nombres").style.setProperty('color','#660000',null);
					document.getElementById("cual_nombres").focus();
					return false;
				}
			}
		}
		if(seri_numeros){
			if (document.getElementById("donde_numeros").value == "1"){
				if (document.getElementById("cual_numeros").value == "" || document.getElementById("cual_numeros").value == "Especifique en cual"){ 
					alert("Ha decidido poner números sólo en una camiseta, pero no ha especificado en cuál de ellas.");
					document.getElementById("cual_numeros").style.setProperty('border','3px solid #f00',null);
					document.getElementById("cual_numeros").style.setProperty('background-color','#f7fafa',null);
					document.getElementById("cual_numeros").style.setProperty('color','#660000',null);
					document.getElementById("cual_numeros").focus();
					return false;
				}
			}
		}
	}
	
	
	//comprobamos serigrafias
	totalserigrafias =document.getElementById("cantidadserigrafia").value;
	
	if(totalserigrafias>0){
		if (document.getElementById("donde_serigrafias").value == "1"){
			if (document.getElementById("cual_serigrafias").value == "" || document.getElementById("cual_serigrafias").value == "Especifique en cual"){ 
				alert("Ha decidido serigrafiar sólo en una camiseta, pero no ha especificado en cuál de ellas.");
				document.getElementById("cual_serigrafias").style.setProperty('border','3px solid #f00',null);
				document.getElementById("cual_serigrafias").style.setProperty('background-color','#f7f0f0',null);
				document.getElementById("cual_serigrafias").style.setProperty('color','#660000',null);
				document.getElementById("cual_serigrafias").focus();
				return false;
			}
		}
	}	
	for(i=1;i<=totalserigrafias;i++){
		nombre = document.getElementById("estampacion_nombre_"+i).value;
		tipo = document.getElementById("estampacion_tipo_"+i).value;
		posicion = document.getElementById("estampacion_posicion_"+i).value;
		if(nombre=="" || nombre =="Escriba aquí un nombre de referencia para esta estampación -"){
			alert("Indique el nombre de la estampación "+i);
			return false;
		}
		if(tipo==""){
			alert("Indique el tipo de la estampación "+i);
			return false;
		}
		if(posicion==""){
			alert("Indique la posición de la estampación "+i);
			return false;
		}

	}
	return true;
}

function onFocus(obj,txt){
	if(obj.value==txt){
		obj.value="";	
	}
}
function onBlur(obj,txt){
	if(obj.value==""){
		obj.value=txt;	
	}
}

function cesta_masinfo(num){
	flecha=document.getElementById("flecha"+num);
	celda = document.getElementById("masinfo"+num);
	
	if(celda.style.display=="none"){
		celda.style.display=""
		flecha.src="images/flechita_abierto.gif";	
	}else{
		celda.style.display="none"
		flecha.src="images/flechita_cerrado.gif";
	}
}

function borrar_cesta(id){
	if(confirm("¿Seguro que quiere eliminar ese producto de la cesta de la compra?")){
		self.location = "borrar_cesta.php?id="+id
	}
}



function actualizaGastos(v){
	
	subtotal 		= Number(document.getElementById("celdaSubtotal").innerHTML.substr(0,document.getElementById("celdaSubtotal").innerHTML.length-1));
	baseimponible 	= Number(document.getElementById("celdaBase").innerHTML.substr(0,document.getElementById("celdaBase").innerHTML.length-1));
	iva 			= Number(document.getElementById("celdaIva").innerHTML.substr(0,document.getElementById("celdaIva").innerHTML.length-1));
	descuento		= Number(document.getElementById("celdaDescuento").innerHTML.substr(0,document.getElementById("celdaDescuento").innerHTML.length-1));
	total		= Number(document.getElementById("celdaTotal").innerHTML.substr(0,document.getElementById("celdaTotal").innerHTML.length-1));
	
	subtotal		= Number(subtotal);
	gastosEnvio 	= Number(v);
	baseimponible 	= Number(subtotal+gastosEnvio);
	iva			= Number(baseimponible*0.180);
	total 		= Math.round(parseFloat(baseimponible+iva+descuento)*1000)/1000;
	
	document.getElementById("celdaGastos").innerHTML = gastosEnvio.toFixed(3)+" €";
	document.getElementById("celdaBase").innerHTML = "<strong>"+baseimponible.toFixed(3)+" €</strong>";
	document.getElementById("celdaIva").innerHTML = iva.toFixed(3)+" €";
	document.getElementById("celdaTotal").innerHTML = total.toFixed(2)+" €";
	document.getElementById("textoCestaDcha").innerHTML = total.toFixed(2)+" €";
	
	//aquii
	FAjax ("set-gastos.php","debug","v="+v,"POST");
	
}
function cambiatipocliente(v){
	if(v=="Otro"){
		document.getElementById("tipocliente").value="";		
		document.getElementById("tipocliente_otro").value="";
		document.getElementById("celdaOtrotipo").style.display="";
	}else{
		document.getElementById("tipocliente_otro").value="";
		document.getElementById("tipocliente").value=v;
		document.getElementById("celdaOtrotipo").style.display="none";	
	}
}
function cambiatipocliente_otro(v){
	document.getElementById("tipocliente").value=v;
}

function validarPresupuesto(){
	nombres = Array("","tipocliente_select","nif","nombre","apellidos","organizacion","direccion","restodireccion","email","telefono","contacto","pais","provinciaList","cp","localidadList");
	
	gastos = document.getElementById("gastos_envio").value
	if(gastos=="" || gastos ==null){
			alert("Debe seleccionar el destino para calcular los gastos de envío.");
			return false;	
	}
	
	
	
	v1 = document.getElementById("tipocliente").value;
	v2 = document.getElementById("nif").value;
	v3 = document.getElementById("nombre").value;
	v4 = document.getElementById("apellidos").value;
	v5 = document.getElementById("organizacion").value;
	v6 = document.getElementById("direccion").value;
	v7 = document.getElementById("restodireccion").value;
	v8 = document.getElementById("email").value;
	v9 = document.getElementById("telefono").value;
	v10 = document.getElementById("contacto").value;
	v11 = document.getElementById("pais").value;
	v12 = document.getElementById("provincia").value;
	v13 = document.getElementById("cp").value;
	v14 = document.getElementById("municipio").value;
	error = false
	for(i=1;i<=14;i++){
		document.getElementById(nombres[i]).style.backgroundColor='#FFFFFF'
		if(eval("v"+i) == "" || eval("v"+i) == null){
			error = true;
			document.getElementById(nombres[i]).style.backgroundColor='#FFCC00'
		}
	}
	if(error){
		alert("Debe rellenar todos los campos marcados con asterisco");
		return false;
	}
	//nif
	if(v11=="España"){
		if(!cif(v2)){
			
			document.getElementById("nif").style.backgroundColor='#FFCC00'
			alert("El CIF / NIF no es válido");	
			return false;
		}
		if(isNaN(v13) || v13.length!=5){
			document.getElementById("cp").style.backgroundColor='#FFCC00'
			alert("El código postal no es válido");	
			return false;
		}
			//telefono
			if(isNaN(v9) || v9.length!=9 || (v9.substr(0,1)!="9" && v9.substr(0,1)!="6")){
				document.getElementById("telefono").style.backgroundColor='#FFCC00'
			alert("El teléfono de contacto no es válido");	
			return false;
		}
	}

	//email
	if(!IsMail(v8)){
		document.getElementById("email").style.backgroundColor='#FFCC00'
		alert("El email introducido no es válido");
		return false;
	}


	return true;	
}

function validarFactura(){
	nombres = Array("","tipocliente_select","nif","nombre","apellidos","organizacion","direccion","restodireccion","email","telefono","contacto","pais","provinciaList","cp","localidadList");
	v1 = document.getElementById("tipocliente").value;
	v2 = document.getElementById("nif").value;
	v3 = document.getElementById("nombre").value;
	v4 = document.getElementById("apellidos").value;
	v5 = document.getElementById("organizacion").value;
	v6 = document.getElementById("direccion").value;
	v7 = document.getElementById("restodireccion").value;
	v8 = document.getElementById("email").value;
	v9 = document.getElementById("telefono").value;
	v10 = document.getElementById("contacto").value;
	v11 = document.getElementById("pais").value;
	v12 = document.getElementById("provincia").value;
	v13 = document.getElementById("cp").value;
	v14 = document.getElementById("municipio").value;
		error = false
	for(i=1;i<=14;i++){
		document.getElementById(nombres[i]).style.backgroundColor='#FFFFFF'
		if(eval("v"+i) == "" || eval("v"+i) == null){
			error = true;
			document.getElementById(nombres[i]).style.backgroundColor='#FFCC00'
		}
	}
	if(error){
		alert("Debe rellenar todos los campos marcados con asterisco");
		return false;
	}
	//nif
	if(v11=="España"){
		if(!cif(v2)){
			
			document.getElementById("nif").style.backgroundColor='#FFCC00'
			alert("El CIF / NIF no es válido");	
			return false;
		}
		if(isNaN(v13) || v13.length!=5){
			document.getElementById("cp").style.backgroundColor='#FFCC00'
			alert("El código postal no es válido");	
			return false;
		}
			//telefono
			if(isNaN(v9) || v9.length!=9 || (v9.substr(0,1)!="9" && v9.substr(0,1)!="6")){
				document.getElementById("telefono").style.backgroundColor='#FFCC00'
			alert("El teléfono de contacto no es válido");	
			return false;
		}
	}

	//email
	if(!IsMail(v8)){
		document.getElementById("email").style.backgroundColor='#FFCC00'
		alert("El email introducido no es válido");
		return false;
	}

	
	return true;	
}



function validarEntrega(){
	nombres = Array("","nombre","apellidos","organizacion","direccion","restodireccion","email","telefono","pais","provinciaList","cp","localidadList");
	
	v1 = document.getElementById("nombre").value;
	v2 = document.getElementById("apellidos").value;
	v3 = document.getElementById("organizacion").value;
	v4 = document.getElementById("direccion").value;
	v5 = document.getElementById("restodireccion").value;
	v6 = document.getElementById("email").value;
	v7 = document.getElementById("telefono").value;
	v8 = document.getElementById("pais").value;
	v9 = document.getElementById("provincia").value;
	v10 = document.getElementById("cp").value;
	v11 = document.getElementById("municipio").value;
		error = false
	for(i=1;i<=11;i++){
		document.getElementById(nombres[i]).style.backgroundColor='#FFFFFF'
		if(eval("v"+i) == "" || eval("v"+i) == null){
			error = true;
			document.getElementById(nombres[i]).style.backgroundColor='#FFCC00'
		}
	}
	if(error){
		alert("Debe rellenar todos los campos marcados con asterisco");
		return false;
	}
	//nif
	if(v8=="España"){
		//cp		
		if(isNaN(v10) || v10.length!=5){
			document.getElementById("cp").style.backgroundColor='#FFCC00'
			alert("El código postal no es válido");	
			return false;
		}
			//telefono
		if(isNaN(v7) || v7.length!=9 || (v7.substr(0,1)!="9" && v7.substr(0,1)!="6")){
			document.getElementById("telefono").style.backgroundColor='#FFCC00'
			alert("El teléfono de contacto no es válido");	
			return false;
		}
	}

	//email
	if(!IsMail(v6)){
		document.getElementById("email").style.backgroundColor='#FFCC00'
		alert("El email introducido no es válido");
		return false;
	}

	
	return true;	
}





//la funcion "IsMail(YourMail)" chequea si "YourMail" es una direccion de correo electronico valida
//La variable "YourMail" es una cadena de caracteres
function IsMail(YourMail)
{
var Template = /^[a-z][a-z-_0-9.]+@[a-z-_=>0-9.]+.[a-z]{2,3}$/i //Formato de direccion de correo electronico
return (Template.test(YourMail)) ? 1 : 0 //Compara "YourMail" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
}
//la funcion "IsNIF(YourNIF)" chequea si "YourNIF" es un DNI valido
//La variable "YourNIF" es una cadena de caracteres
function cif(cif){
	par = 0
	non = 0
	letras="ABCDEFGHKLMNPQS"
	let=cif.charAt(0)
	
	if (!isNaN(let)){
	  nif=cif
	  return validar(nif)
	}
	
	if (cif.length!=9){
	//  alert('El Cif debe tener 9 dígitos')
	//  document.formulario.nif.focus()
	  return false
	}
	
	if (letras.indexOf(let.toUpperCase())==-1){
	//  alert("El comienzo del Cif no es válido")
	 // document.formulario.nif.focus()
	  return false
	}
	
	for (zz=2;zz<8;zz+=2){
	  par = par+parseInt(cif.charAt(zz))
	}
	
	for (zz=1;zz<9;zz+=2){
	  nn = 2*parseInt(cif.charAt(zz))
	  if (nn > 9) nn = 1+(nn-10)
	  non = non+nn
	}
	
	parcial = par + non
	control = (10 - ( parcial % 10))
	if (control==10) control=0
	
	if (control!=cif.charAt(8)){
	//  alert("El Cif no es válido")
	//  document.formulario.nif.focus()
	  return false
	}
	// alert("El Cif es válido")
	return true
}

function validar(abc)
{
dni=abc.substring(0,abc.length-1)
let=abc.charAt(abc.length-1)
if (!isNaN(let))
 {
//  alert('Falta la letra')
//  document.formulario.nif.focus()
  return false
 }
else
 {
  cadena="TRWAGMYFPDXBNJZSQVHLCKET"
  posicion = dni % 23
  letra = cadena.substring(posicion,posicion+1)
  if (letra!=let.toUpperCase())
   {
//    alert("Nif no válido")
//    document.formulario.nif.focus()
    return false
   }
 }
//alert("Nif válido")
	return true
}


function realizarPedido(){
	gastos = document.getElementById("gastos_envio").value;
	if(gastos=="" || gastos ==null){
		alert("Debe seleccionar el destino para calcular los gastos de envío.");
		return;	
	}
	else{
	//if(confirm("¿Está seguro que desea finalizar el pedido? Las compras que realice a partir de ahora formarán parte de otro pedido.")){
		self.location = "compra1.php";	
	//}
	}
}

function registro_news(){
	v = document.getElementById("newsleter_email").value;	
	if(v=="" || v==null){
		alert("Indicanos tu dirección de e-mail.");	
	}else{
		if(IsMail(v)){
			FAjax ("graba-newsreg.php","debug","email="+v,"POST",registro_news_response);		
		}else{
			alert("Indicanos una dirección de e-mail correcta.");	
		}
	}
}
function registro_news_response(){
	document.getElementById("newsleter_email").value=""
	alert("Hemos registrado tu email con éxito. Pronto recibiras nuestras ofertas.");	
}


function contacte_ahora(){
	v1 = document.getElementById("contacte_ahora_nombre").value;	
	v2 = document.getElementById("contacte_ahora_email").value;	
	v3 = document.getElementById("contacte_ahora_comentario").value;	
	
	if(v2=="" || v2==null){
		alert("Indica tu email para poder contactarte mas tarde");	
		return;
	}else{
		if(!IsMail(v2)){
			alert("Indicanos una dirección de e-mail correcta.");	
			return;
		}
	}
	if(v3=="" || v3==null){
		alert("Escribe el comentario que nos quieres hacer.");	
		return;
	}
	FAjax ("graba-contacta.php","debug","nombre="+v1+"&email="+v2+"&comentario="+v3,"POST",conctacte_ahora_response);	
	
}

function conctacte_ahora_response(){
	document.getElementById("contacte_ahora_nombre").value="";	
	document.getElementById("contacte_ahora_email").value="";	
	document.getElementById("contacte_ahora_comentario").value="";
	
	alert("Hemos recibido su mensaje. En breve nos pondremos en contacto con usted.");
	
}



function validarColectivo(){
	nombres = Array("","nombre","apellidos","nombre_colectivo","email","telefono","cantidad","necesidad");
	
	v1 = document.getElementById("nombre").value;
	v2 = document.getElementById("apellidos").value;
	v3 = document.getElementById("nombre_colectivo").value;
	v4 = document.getElementById("email").value;
	v5 = document.getElementById("telefono").value;
	v6 = document.getElementById("cantidad").value;
	v7 = document.getElementById("necesidad").value;
	error = false
	for(i=1;i<=7;i++){
		document.getElementById(nombres[i]).style.backgroundColor='#FFFFFF'
		if(eval("v"+i) == "" || eval("v"+i) == null){
			error = true;
			document.getElementById(nombres[i]).style.backgroundColor='#FFCC00'
		}
	}
	if(error){
		alert("Debe rellenar todos los campos marcados con asterisco");
		return false;
	}
	//telefono
	if(isNaN(v5) || v5.length!=9 || (v5.substr(0,1)!="9" && v5.substr(0,1)!="6")){
		document.getElementById("telefono").style.backgroundColor='#FFCC00'
		alert("El teléfono de contacto no es válido");	
		return false;
	}
		
	//email
	if(!IsMail(v4)){
		document.getElementById("email").style.backgroundColor='#FFCC00'
		alert("El email introducido no es válido");
		return false;
	}

	
	return true;	
}
