// JavaScript Document
function cargaPagina(url,div,parametros)
{
	new Request(
	{
		method: 'post',
		url: url,
		onSuccess: function(texto){
		$(div).innerHTML = texto;}
	}).send(parametros);
}
function escribeflash(url,anchoswf,altoswf){
document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="https://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+anchoswf+'" height="'+altoswf+'"  align="middle">');
document.write('<param name="allowScriptAccess" value="sameDomain" />');
document.write('<param name="movie" value="'+url+'" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><embed wmode="transparent" src="'+url+'" quality="high" width="'+anchoswf+'" height="'+altoswf+'"  align="middle"  type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer" />');
document.write('</object>');}

var tempX=0;
var tempY=0;
var IE=document.all?true:false;
if(IE)
{
	var AltoPantalla = screen.Height / 2;
	var AnchoPantalla = screen.Width / 2;
}
else
{
	var AltoPantalla=screen.height / 2;	
	var AnchoPantalla=screen.width / 2;
}

function getMouseXY(e)
{
	if(IE)
	{
		tempX=event.clientX - 530;
		tempY=event.clientY;
		altura=document.body.clientHeight
	}
	else
	{
		tempX=parseInt(e.pageX-530)+"px";
		tempY=parseInt(e.pageY+16)+"px";
		altura=window.innerHeight
	}
	
	if(tempX<0)
		tempX=0;
		
	if(tempY<0)
		tempY=0;
	
	if(document.getElementById('cuadro').offsetHeight+parseInt(tempY)>altura)
	{
		document.getElementById('cuadro').style.top=(parseInt(parseInt(tempY)-document.getElementById('cuadro').offsetHeight)-18)+"px";
		
		if(parseInt(document.getElementById('cuadro').style.top)<0)
		{
			document.getElementById('cuadro').style.top=10+"px"
		}
	}
	else
	{
		document.getElementById('cuadro').style.top=tempY
	}
	
	document.getElementById('cuadro').style.left=tempX;
	return true;
}

function mueve()
{
	//if(document.direccion.forma_entrega[0].checked)
		var reparto = 0;
	//else
		//var reparto = 1;
	var cp = 0;//$('direcciones-habituales').value
	cargaPagina('/desglose-compra.php', 'cuadro', 'reparto_tienda=' + reparto + "&cp=" + cp);
	
	if(!IE) document.captureEvents(Event.MOUSEMOVE);
	
	document.onmousemove=getMouseXY;
	//document.getElementById('cuadro').innerHTML="<img src='"+a+"' align='top'/><div style='padding:5px;'>"+b+"</div>";
	document.getElementById('cuadro').style.display="block";
	document.getElementById('cuadro').style.visibility="visible";
}

function oculta(){document.onmousemove="";document.getElementById('cuadro').style.display="none";document.getElementById('cuadro').style.visibility="hidden";document.getElementById('cuadro').style.left=-400+"px";document.getElementById('cuadro').style.top=-400+"px"}

function cambia(elemento, tipo, cual)
{
	if(tipo == 1)
	{
		elemento.style.background = "URL(/imagenes/px-boton-on.gif) repeat-x";
		if(cual != 0)
			$('submenu' + cual).style.display = 'block';
	}
	else
	{
		elemento.style.background = "URL(/imagenes/px-boton-off.gif) repeat-x";
		if(cual != 0)
			$('submenu' + cual).style.display = 'none';
	}
}
function guardarRegistro()
{
	var error = "";
		
	if($('nombre-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar el nombre de registro.");
		error = "nombre-registro";
	}
	if($('apellidos-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar los apellidos de registro.");
		error = "apellidos-registro";
	}
	if($('direccion-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar la direcciÃ³n de registro.");
		error = "direccion-registro";
	}
	if($('cp-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar el cÃ³digo postal de registro.");
		error = "cp-registro";
	}
	if(!validaCodigoPostal($('cp-registro').value) && error == "")
	{
		alert("Por favor, el cÃ³digo postal de registro de ser un nÃºmero de 5 dÃ­gitos.");
		error = "cp-registro";
	}
	if($('cp-registro').value != "" && error == "")
	{
		if($('cp-registro').value.length == 4)
			var pro = $('cp-registro').value.substr(0,1);
		else
			var pro = $('cp-registro').value.substr(0,2);
			
		if(pro == "7" || pro == "07" || pro == "35" || pro == "38" || pro == "51" || pro == "52")
		{
			alert("Por cuestiones de reparto tan solo se permite el\nregistro a provincias de EspaÃ±a peninsular.");
			error = "cp-registro";
		}
	}
	if($('poblacion-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar la poblaciÃ³n de registro.");
		error = "poblacion-registro";
	}
	if($('tlf-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar el telÃ©fono de registro.");
		error = "tlf-registro";
	}
	if(!telefono_valido($('tlf-registro').value) && error == "")
	{
		alert("Por favor, el telÃ©fono de registro de ser un nÃºmero de 9 dÃ­gitos .");
		error = "tlf-registro";
	}
	if($('nif-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar el NIF/CIF de registro.");
		error = "nif-registro";
	}
	if(!validaCIF($('nif-registro').value) && !isValidNif($('nif-registro').value) && error == "")
	{
		alert("Por favor, debe rellenar la correctamente el NIF/CIF de la factura.\n\nFormtato NIF: 00000001X\nFormtato NIF: X00000001X\nFormtato CIF: A00000001");
		error = "nif-registro";
	}
	if(!comprueba_fecha($('dia-registro').value,$('mes-registro').value,$('anio-registro').value) && error == "")
	{
		alert("La fecha de nacimiento no es correcta, hay que ser mayor\nde edad para completar el registro.");
		error = "dia-registro";
	}
	if($('email-registro').value == "" && error == "")
	{
		alert("Por favor, debe rellenar el email de registro.");
		error = "email-registro";
	}
	if(!validarMail($('email-registro').value) && error == "")
	{
		alert("Por favor, el email de registro no es correcto.");
		error = "email-registro";
	}
	if(!$('accion'))
	{
		if($('pass-registro').value == "" && error == "")
		{
			alert("Por favor, debe rellenar la contraseÃ±a de registro.");
			error = "pass-registro";
		}
		if($('pass-registro').value != $('pass-registro2').value && error == "")
		{
			alert("Las contraseÃ±as de registro no coinciden.");
			error = "pass-registro";
		}
	}
	else
	{
		if($('pass-registro').value != "" && $('pass-registro').value != $('pass-registro2').value && error == "")
		{
			alert("Las contraseÃ±as de registro no coinciden.");
			error = "pass-registro";
		}
	}
	if(!$('condiciones-compra').checked && error == "")
	{
		alert("Por favor, para completar el registro debe aceptar las condiciones de compra.");
		error = "condiciones-compra";
	}		
	
	if(!$('accion'))
	{
		validaRegistro();
		if(estadoRegistro == "KO" && error == "")
		{
			alert("Ya existe un usuario registrado que tiene el mismo NIF o el mismo E-mail.")
			error = "nif-registro";
			llamadaAjax = false;
			estadoRegistro = "";
		}
		if(estadoRegistro == "" && error == "")
		{
			setTimeout("guardarRegistro();", 250);
			return false;
		}/**/
	}
	
	if(error != "")
		$(error).focus();
	else if(confirm("¿Son correctos todos los datos?"))
	{
		document.registro.action = "guardar-registro.php";
		document.registro.submit();
	}
	else
	{
		llamadaAjax = false;
		estadoRegistro = "";
	}
}
var llamadaAjax = false;
var estadoRegistro = "";
function validaRegistro()
{
	if(!llamadaAjax)
	{
		cargaPagina("comprueba-registro.php", "valida_registro", "nif-registro="+$('nif-registro').value+"&email-registro=" + $('email-registro').value);
		llamadaAjax = true;
	}
	else
	{
		if($('valida_registro').innerHTML == 'KO')
			estadoRegistro = "KO";
		else if($('valida_registro').innerHTML == 'OK')
			estadoRegistro = "OK";
	}
}

function validarMail(sEmail) {
  	var emailFilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
	if (sEmail != '' && emailFilter.test(sEmail)) {return true;}
	return false;
}

function validaCIF(CIF)
{
	var pares = 0;
	var impares = 0;
	var suma, ultima, numero;
	var letra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
	var cad;
	
	CIF = CIF.toUpperCase();
	
	var regular = new RegExp(/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g);
	if (!regular.exec(CIF)) return false;
		 
	ultima = CIF.substr(8,1);
	
	for (var cont = 1 ; cont < 7 ; cont ++){
		cad = (2 * parseInt(CIF.substr(cont++,1))).toString() + "0";
		impares += parseInt(cad.substr(0,1)) + parseInt(cad.substr(1,1));
		pares += parseInt(CIF.substr(cont,1));
	}
	cad = (2 * parseInt(CIF.substr(cont,1))).toString() + "0";
	impares += parseInt(cad.substr(0,1)) + parseInt(cad.substr(1,1));
	
	suma = (pares + impares).toString();
	numero = parseInt(suma.substr(suma.length - 1, 1));
	numero = (10 - numero).toString();
	if(numero == 10) numero = 0;
	
	if ((ultima == numero) || (ultima == letra[numero]))
		return true;
	return false; 
}

function isValidNif(abc)
{
	var letra_nuevo = new Array("K", "L", "M", "X", "Y", "Z");
	var letraInicial = abc.substring(0,1);
	if(isNaN(letraInicial))
	{
		dni=abc.substring(1,abc.length-1);
		esta = false;
		for(z=0; z <= letra_nuevo.length-1; z++)
		{
			if(letra_nuevo[z] == letraInicial.toUpperCase())
			{
				//alert(letraInicial);
				esta = true;
				break;
			}
		}
		if(!esta) return false;
	}
	else
	{
		dni=abc.substring(0,abc.length-1);	
	}
	
	let=abc.charAt(abc.length-1);
	if (!isNaN(let)) {
		return false;
	}else{
		cadena = "TRWAGMYFPDXBNJZSQVHLCKET";
		posicion = dni % 23;
		letra = cadena.substring(posicion,posicion+1);
		if (letra!=let.toUpperCase()){
			return false;
		}
	}
	return true;
}

function telefono_valido(numero)
{
	var tfno= parseInt(numero);
	var error = "";
	if ( isNaN(tfno) )
		return false;
	else
	{
		if ( !( (tfno >= 900000000) && (tfno < 1000000000) || (tfno >= 600000000) && (tfno < 700000000) ) )  
			return false;
	}
	return true;
}
function validaCodigoPostal(CP)
{
	if(CP == "" || isNaN(CP) || CP < 1000 || CP > 52999)
		return false;
	return true;
}
function comprueba_fecha(dia,mes,anio)
{
	var elMes = parseInt(mes);		
	if(elMes == 2)
	{
		if(esBisiesto(anio))
		{
			if(parseInt(dia) > 29)
				return false;
			else
				return true;
		}
		else
		{
			if(parseInt(dia) > 28)
				return false;
			else
				return true;
		}
	}

	if(elMes== 4 || elMes==6 || elMes==9 || elMes==11)
	{
		if(parseInt(dia) > 30)
			return false;
	
	}
	
	var hoy = new Date();
	
	edad=hoy.getFullYear()- anio;			
	
    if (hoy.getMonth() + 1 - elMes > 0)
       edad = edad + 1;
    else if(hoy.getMonth() + 1 - elMes == 0) 
	{	
		if (hoy.getUTCDate() - dia >= 0)
		   edad = edad +1;
	}

	if(edad < 18)
	    return false;
		
	return true;
}
function cambiaFormaPago()
{
	if($('cambio-pago').style.display == 'none')
	{
		$('cambio-pago').style.display = 'inline';
		$('titulo-pago').innerHTML = '&nbsp;';
		$('forma-pago').style.display = 'none';
	}
	else
	{
		$('cambio-pago').style.display = 'none';
		$('titulo-pago').innerHTML = 'Forma de pago';
		$('forma-pago').style.display = 'inline';
	}
}

function anadeDireccion(codigo)
{
	$('direcciones-habituales').options[$('direcciones-habituales').length ]=new Option($('direccion-nueva').value + " ("  + $('cp-nueva').value + ")",codigo,"defaultSelected");
	$('direccion-nueva').value = "";
	$('cp-nueva').value = "";
}

function recargaCompra(cod, unidades, precio)
{
	$('precioBase' + cod).innerHTML = formatCurrency(precio) + " &euro;";
	$('totalProducto' + cod). innerHTML = formatCurrency(precio * unidades) + " &euro;";
	
	/*if($('direcciones-habituales'))
	{
		if(document.direccion.forma_entrega[0].checked)
			setTimeout("actualizaPortes($('direcciones-habituales').value,1);", 1000);
	}*/
	cargaPagina('/calcula_carro.php', 'prev_carro_on', '');
}
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (num + ',' + cents);
}

function eliminaProducto (codigo)
{
	var myFx = new Fx.Tween('producto'+codigo);
	myFx.start('height', 0);
	setTimeout("$('producto"+codigo+"').destroy();", 500);
	cargaPagina('/calcula_carro.php', 'prev_carro_on', '');
}

window.addEvent('load', function() {
 
	ReMooz.assign('#demo-photos a', {
		'origin': 'img',
		'shadow': 'onOpenEnd', // fx is faster because shadow appears after resize animation
		'resizeFactor': 0.8, // resize to maximum 80% of screen size
		'cutOut': false, // don't hide the original
		'opacityResize': 0.4, // opaque resize
		'dragging': false, // disable dragging
		'centered': true // resize to center of the screen, not relative to the source element
	});
});

function borraCarroCompra()
{
	var myFx = new Fx.Tween('contenido_pedido');
	//var myFx2 = new Fx.Tween('contenido_pedido');
	myFx.start('opacity', 1, 0);
	setTimeout("$('contenido_pedido').innerHTML= '<div style=\"float:left; display:inline; width:862px; margin: 30px 0 20px 0; font-size: 15px; text-align: center; font-weight: 700;\">No hay productos en el carro de la compra.</div>';", 500);
	//myFx.start('opacity', 0, 1);
	setTimeout("$('contenido_pedido').erase('style');", 1000);
}

function compruebaFormaPago(total)
{
	/*if(document.form_pago.forma_pago[2].checked && total < 180)
		alert("Para poder financiar una compra debe superar los 180 euros en compra.")
	else*/
		document.form_pago.submit();
}
function compruebaFormaPago2(total)
{
	/*if(document.direccion.forma_entrega[0].checked)
	{*/
		$('tipo_envio').value = 1;
		$('cod_entrega').value = $('direcciones-habituales').value;
	/*}
	else
	{
		$('tipo_envio').value = 2;
		$('cod_entrega').value = $('tiendas').value;;
	}
	if(document.form_pago.forma_pago_sel.checked)
	{
		if(document.form_pago.forma_pago_sel.value == 3 && total < 180)
			alert("Para poder financiar una compra debe superar los 180 euros en compra.\n\n Por favor modifique su forma de pago.")
		else
			document.form_pago.submit();
	}
	else
	{
		if($('cod_entrega').value == -1 && $('tipo_envio').value == 2)
		{
			alert("Indique la tienda en la desea recoger su pedido.")
			return false;
		}*/
		/*if(document.form_pago.forma_pago[2].checked && total < 180)
		{
			alert("Para poder financiar una compra debe superar los 180 euros en compra.")
			return false;
		}*/
		if(!$('condiciones_compra').checked)
		{
			alert("Para poder continuar debe aceptar las condiciones de compra.")
			return false;
		}
		else
		{
			if(confirm("La direcciÃ³n de entrega es: " + $('direcciones-habituales').options[$('direcciones-habituales').selectedIndex].text + "\n\nSi ha aÃ±adido una nueva direcciÃ³n y no es la correcta, debe pulsar en el icono de 'aÃ±adir a direcciones habituales'"))
				document.form_pago.submit();
		}
	//}		
}

function revisaCurriculum()
{
		var error = "";
		
		if($('nombre').value == "" && error == "")
		{
			alert("Debe rellenar el nombre.")
			error = "nombre";
		}
		
		if($('apellidos').value == "" && error == "")
		{
			alert("Debe rellenar los apellidos.")
			error = "apellidos";
		}
		
		if($('direccion').value == "" && error == "")
		{
			alert("Debe rellenar la direcciÃ³n.")
			error = "direccion";
		}
		
		if($('cp').value == "" && error == "")
		{
			alert("Debe rellenar el cÃ³digo postal.")
			error = "cp";
		}
		
		if(!validaCodigoPostal($('cp').value) && error == "")
		{
			alert("El cÃ³digo postal no es correcto.")
			error = "cp";
		}
		
		if($('email').value == "" && error == "")
		{
			alert("Debe rellenar el e-mail.")
			error = "email";
		}
		
		if(!validarMail($('email').value) && error == "")
		{
			alert("El e-mail no es correcto.");
			error = "email";
		}
		
		if($('tlf').value == "" && error == "")
		{
			alert("Debe rellenar el telÃ©fono.")
			error = "tlf";
		}
		
		if(isNaN($('tlf').value) && error == "")
		{
			alert("El telÃ©fono debe ser un numero.")
			error = "tlf";
		}
		
		if($('curriculum').value != "" && error == "")
		{
			corte = $('curriculum').value.split(".");
			extension = corte[corte.length - 1];
			
			if(extension.toUpperCase() != "DOC" && extension.toUpperCase() != "DOCX" && extension.toUpperCase() != "PDF")
			{
				alert("El formato del curriculum debe ser DOC, DOCX o PDF.")
				error = "tlf";
			}
		}
		
		if($('horario').value == "-1" && error == "")
		{
			alert("Debe seleccionar un horario.")
			error = "horario";
		}
		
		if(!$('politica_privacidad').checked && error == "")
		{
			alert("Debe aceptar la polÃtica de privacidad.")
			error = "politica_privacidad";
		}
		
		if(error != "")
			$(error).focus();
		else if(confirm("EstÃ¡ todo correcto?"))
			document.curriculums.submit();
}

function recargaTiendas (cp)
{
	if(!validaCodigoPostal(cp))
		alert("El codigo postal no es válido");
	else
		cargaPagina('/saca-tiendas-carro.php', 'div_tiendas', 'cp='+cp);
}
function miraTiendas(valor, e)
{
	alert(e)
	/*if(document.all)
		if(e.keyCode == 13) recargaTiendas(valor);
	else
	{
		alert(e.which)
		if(e.which == 13) recargaTiendas(valor);
	}*/
}
function actualizaPortes(cod, tipo)
{
	cargaPagina('/saca-portes.php', 'div_portes', 'cod='+cod+'&tipo='+tipo);
	setTimeout("cargaPagina('/calcula_carro.php', 'prev_carro', '');", 500);
}

function validaNuevaDireccion()
{
	if($('direccion-nueva').value != '' && validaCodigoPostal($('cp-nueva').value))
	{
		if($('cp-nueva').value.length == 4)
			var pro = $('cp-nueva').value.substr(0,1);
		else
			var pro = $('cp-nueva').value.substr(0,2);
			
		if(pro == "7" || pro == "07" || pro == "35" || pro == "38" || pro == "51" || pro == "52")
			alert("Por cuestiones de reparto tan solo se permite el\nregistro a provincias de EspaÃ±a peninsular.");
		else
			document.direccion.submit();
	}
	else
		alert('Debe rellenar correctamente todos los datos.');
}

function validaNuevaDireccion2()
{
	if($('direccion-nueva').value != '' && validaCodigoPostal($('cp-nueva').value) && $('poblacion-nueva').value != '')
	{
		if($('cp-nueva').value.length == 4)
			var pro = $('cp-nueva').value.substr(0,1);
		else
			var pro = $('cp-nueva').value.substr(0,2);
			
		if(pro == "7" || pro == "07" || pro == "35" || pro == "38" || pro == "51" || pro == "52")
			alert("Por cuestiones de reparto tan solo se permite el\nregistro a provincias de EspaÃ±a peninsular.");
		else
			document.direccion.submit();
	}
	else
		alert('Debe rellenar correctamente todos los datos.');
}
function cargaMapa()
{
		var map = new google.maps.Map2(document.getElementById("map"));
		var geocoder = new GClientGeocoder();
		var address = $('direccion').value;				
		if($('lat').value != "" && $('lon').value != "")
		{
			var LatLng = new GLatLng($('lat').value, $('lon').value);
			map.setCenter(LatLng, 16);
			marker = new GMarker(LatLng);
			map.addOverlay(marker);			
		}
		else
		{
			var LatLng = new GLatLng(geocoder.getLatLng(address, function(point) {
					map.setCenter(point, 16);
					var marker = new GMarker(point);
					map.addOverlay(marker);
				}
				)
			);
		}
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setMapType(G_HYBRID_MAP)
}
function validaCP()
{
	var cp = parseFloat($('cp').value);
	if(!validaCodigoPostal(cp))
	{
		alert("Por favor, el cÃ³digo postal de registro de ser un nÃºmero de 5 dÃ­gitos.");
		$('cp').focus();
		return false;
	}
	if(cp < 10000)
		cp = "0" + cp.toString();
	$('cp').value = cp;	
	cargaPagina('resultados-busqueda-tiendas.php', 'resultados_busqueda', 'cp=' + cp);
}
function cambiaFoto()
{
	var rango_superior = total;  
		var rango_inferior = 1; 
	var aleatorio=actual;
	do
	{
		aleatorio = Math.floor(Math.random()*(rango_superior-(rango_inferior-1))) + rango_inferior;  
	}
	while(aleatorio == actual)
	
	eval("myFx" + actual + ".start('opacity', [1,0]);");
	eval("myFx" + aleatorio + ".start('opacity', [0,1]);");
	
	actual = aleatorio;
			
	setTimeout("cambiaFoto();", 5000);
}
function esBisiesto(anio)
{
	if(parseInt(anio)%4==0)
	{
		if(parseInt(anio)%100==0)
		{
			if(parseInt(anio)%400==0)		
				return true;
			else
				return false;
		}
		else
			return true;
	}
	else
		return false;
} 

