
function checkemail(email)
 {
	var str = email;
	var filter=/^.+@.+\..{2,4}$/;

	if(filter.test(str))
		testresults = true;
	else
		testresults = false;
	return testresults;
}


$(document).ready(function() {


	var alts = document.getElementsByTagName('img');
	for(var al=0; al<alts.length; ++al)
	 	alts[al].alt = '';


	//Convierte todos los 'a' con 'rel=external' a 'target=_blank'
	$('a[rel="external"]').attr('target', '_blank');
	
	//comprueba los datos cuando se va a hacer login
	$("#btnAutentificarse").click(function(){
	
		var msg = '';		
		var campos = '';
		
		campos += "#txtUsuarioLogin, ";
		campos += "#txtPassLogin, ";
		
		jQuery.trim($(campos).val());
		
		if ($("#txtUsuarioLogin").val().length == 0 || $("#txtUsuarioLogin").val() == 'Usuario')
			msg += 'Debes rellenar el campo \"usuario\".\n';

		if ($("#txtPassLogin").val().length == 0 || $("#txtPassLogin").val() == 'Clave')
			msg += 'Debes rellenar el campo \"clave\".\n';
	
		
		if(msg)
			alert(msg);
		else
			$("#formuLogin").submit();
	
	});
	
	//Elimina el contenido del input del campo "usuario" (en el login)
	$("#txtUsuarioLogin").focus(function(){
	
		$("#txtUsuarioLogin").css("background-image", "none");
		
	});
	
	//Elimina el contenido del input del campo "pass" y lo convierte de tipo password (en el login)
	$("#txtPassLogin").focus(function(){
		
		$("#txtPassLogin").css("background-image", "none");
	
	});
	
	//vuelve a la pÃ¡gina "autentificacion/paso1" enviando de vuelta los datos introducidos.
	$("#btnVolver").click(function(){
	
		$("#formuDatosPersonales").submit();
	
	});
	
	//si el pais no es españa, no se le deja seleccionar provincia. AHORA MISMO EL COMBO DE PAISES ESTA COMENTADO, HAY QUE DESCOMENTARLO DE
	//LAS PÁGINAS RESPECTIVAS PARA QUE EL SIGUIENTE CONTROL TENGA SENTIDO.
		$("#cmbPaises").change(function(){
				
			if($(this).val() != "ES")
			{
				$("#cmbProvincias").val(0);
				$("#cmbProvincias").attr("disabled", "disabled");
			}
			else
				$("#cmbProvincias").attr("disabled", "");
		});
		
		$("#cmbPaisesEnvio").change(function(){
				
			if($(this).val() != "ES")
			{
				$("#cmbProvinciasEnvio").val(0);
				$("#cmbProvinciasEnvio").attr("disabled", "disabled");
			}
			else
				$("#cmbProvinciasEnvio").attr("disabled", "");
		});


	//comprueba los campos
		$("#btnContinuar").click(function() {

			var msg = '';

			if(document.getElementById('cmbProvincias'))
			 {
				var prov = document.getElementById('cmbProvincias').value;
				prov = (prov < 10) ? "0"+prov : prov;
				var pcp = $("#txtCp").val();
				pcp = pcp.substring(0,2);

				if(pcp != prov)
					msg += 'El código postal que ha ingresado no coincide con la provincia elegida.\n';
			 }
			 
			if(document.getElementById('cmbProvinciasEnvio'))
			 {
				var prov = document.getElementById('cmbProvinciasEnvio').value;
				prov = (prov < 10) ? "0"+prov : prov;
				var pcp = $("#txtCpEnvio").val();
				pcp = pcp.substring(0,2);

				if(pcp != prov)
					msg += 'El código postal que ha ingresado no coincide con la provincia elegida.\n';
			 }

			if($("#txtConfirmoPolitica").val() == '0')
				msg += 'Debe leer y aceptar la \"Política de privacidad\" y las \"Condiciones de compra\".\n';
			
						
						
			//informacion del cliente
				if($("#txtNombre").length > 0)
				{			
					$("#txtNombre").val($.trim($("#txtNombre").val()));
					
					if ($("#txtNombre").val().length == 0)
						msg += 'Debes rellenar el campo \"Nombre\".\n';
				}//fin if
				
				if($("#txtDireccion").length > 0)
				{
					$("#txtDireccion").val($.trim($("#txtDireccion").val()));
					
					if ($("#txtDireccion").val().length == 0)
						msg += 'Debes rellenar el campo \"Dirección\".\n';
				}//fin if
				
				/*COMBO DE PAISES DESACTIVADO.
				if($("#cmbPaises").length > 0)
				{
					if ($("#cmbPaises").val() == 0)
						msg += 'Debes seleccionar una opción en el campo \"paí­s\".\n';
	
				}//fin if
				*/
					
				if($("#cmbProvincias").length > 0)
				{
					/*COMBO DE PAISES DESACTIVADO
					if($("#cmbProvincias").val() == 0 && $("#cmbPaises").val() == 'ES')*/
					if($("#cmbProvincias").val() == 0)
						msg += 'Debes seleccionar una opción en el campo \"Provincia\".\n';	
				}//fin if
				
				if($("#txtLocalidad").length > 0)
				{			
					$("#txtLocalidad").val($.trim($("#txtLocalidad").val()));
					
					if ($("#txtLocalidad").val().length == 0)
						msg += 'Debes rellenar el campo \"Localidad\".\n';
				}//fin if
				
				if($("#txtCp").length > 0)
				{						
					$("#txtCp").val($.trim($("#txtCp").val()));
					
					if ($("#txtCp").val().length == 0)
						msg += 'Debes rellenar el campo \"Código postal\".\n';
					else if( $("#txtCp").val().match("\\D", "g") )
						msg += 'Solo se permiten números en el campo \"Código postal\".\n';
				}//fin if
				
				
				if($("#txtTelefono").length > 0)
				{						
					$("#txtTelefono").val($.trim($("#txtTelefono").val()));
					
					if ($("#txtTelefono").val().length == 0)
						msg += 'Debes rellenar el campo \"Teléfono\".\n';
					else if(parseInt($("#txtTelefono").val()) != $("#txtTelefono").val())
						msg += 'Solo se permiten números en el campo \"Teléfono\".\n';
				}//fin if
 
						
				if($("#txtEmail").length > 0)
				{											
					$("#txtEmail").val($.trim($("#txtEmail").val()));
					
					if($("#txtEmail").val().length == 0)
						msg += 'Debes rellenar el campo \"e-mail\".\n';
					else if(!checkemail(($("#txtEmail").val())))
						msg += 'La dirección de e-mail que has ingresado no es válida.\n';
				}//fin if		
	
	
	
			//informacion de envio			
				if($("#txtNombreEnvio").length > 0)
				{
					$("#txtNombreEnvio").val($.trim($("#txtNombreEnvio").val()));
				
					if($("#txtNombreEnvio").val().length == 0)
						msg += 'Debes rellenar el campo \"Nombre de envío\".\n';
				}//fin if
				
				if($("#txtDireccionEnvio").length > 0)
				{
					$("#txtDireccionEnvio").val($.trim($("#txtDireccionEnvio").val()));
					
					if($("#txtDireccionEnvio").val().length == 0)
						msg += 'Debes rellenar el campo \"Dirección de envío\".\n';
				}//fin if
				
				/*COMBO DE PAISES DESACTIVADO
				if($("#cmbPaisesEnvio").length > 0)
				{
					if ($("#cmbPaisesEnvio").val() == 0)
						msg += 'Debes seleccionar una opciÃ³n en el campo \"país de envÃ­o\".\n';					
				}//fin if
				*/
				
				//if($("#cmbProvinciasEnvio").length > 0 && $("#cmbPaisesEnvio").val() == 'ES')
				if($("#cmbProvinciasEnvio").length > 0)
				{
					if ($("#cmbProvinciasEnvio").val() == 0)
						msg += 'Debes seleccionar una opción en el campo \"Provincia de envío\".\n';				
				}//fin if
							
				if($("#txtLocalidadEnvio").length > 0)
				{
					$("#txtLocalidadEnvio").val($.trim($("#txtLocalidadEnvio").val()));
					
					if($("#txtLocalidadEnvio").val().length == 0)
						msg += 'Debes rellenar el campo \"Localidad de envío\".\n';
				}//fin if	
				
				if($("#txtCpEnvio").length > 0)
				{
					$("#txtCpEnvio").val($.trim($("#txtCpEnvio").val()));
					
					if($("#txtCpEnvio").val().length == 0)
						msg += 'Debes rellenar el campo \"Código postal de envío\".\n';
					else if( $("#txtCpEnvio").val().match("\\D", "g") )
						msg += 'Solo se permiten números en el campo \"Código postal de envío\".\n';
				}//fin if			
				
				if($("#txtTelefonoEnvio").length > 0)
				{
					$("#txtTelefonoEnvio").val($.trim($("#txtTelefonoEnvio").val()));
					
					if($("#txtTelefonoEnvio").val().length == 0)
						msg += 'Debes rellenar el campo \"Teléfono de envío\".\n';
					else if(parseInt($("#txtTelefonoEnvio").val()) != $("#txtTelefonoEnvio").val())
						msg += 'Solo se permiten números en el campo \"Teléfono de envió\".\n';
				}//fin if				
				
				if($("#txtEmailEnvio").length > 0)
				{
					$("#txtEmailEnvio").val($.trim($("#txtEmailEnvio").val()));
					
					if($("#txtEmailEnvio").val().length == 0)
						msg += 'Debes rellenar el campo \"E-mail de envío\".\n';
					else if(!checkemail(($("#txtEmailEnvio").val())))
						msg += 'La dirección de e-mail que has ingresado no es válida.\n';
				}//fin if		
			
			if (msg)
				alert (msg);
			else
				$("#formuDatosPersonales").submit();
		});
	
	//cambia el estado del radio button de recibir el boletí­n
	$("#btnRecibirInfo").toggle (
	
		function ()
		{
			$(this).css("backgroundPosition", "top");//posicionamos la imagen de fondo del button arriba para que parezca activo
			$("#txtRecibirInfo").val(1);
		},
		function ()
		{
			$(this).css("backgroundPosition", "bottom");//posicionamos la imagen de fondo del button abajo para que parezca activo
			$("#txtRecibirInfo").val(0);			
		}
	);
	
	$("#btnConfirmoPolitica").toggle (
	
		function ()
		{
			$(this).css("backgroundPosition", "top");//posicionamos la imagen de fondo del button arriba para que parezca activo
			$("#txtConfirmoPolitica").val(1);
		},
		function ()
		{
			$(this).css("backgroundPosition", "bottom");//posicionamos la imagen de fondo del button abajo para que parezca activo
			$("#txtConfirmoPolitica").val(0);			
		}
	);
	
	//cambia el estado del radio button de datos de envÃ­o
	$("#btnMismosDatos").toggle (
		
		function ()
		{	
			$(this).css("backgroundPosition", "top");//posicionamos la imagen de fondo del button arriba para que parezca activo

			$("#txtNombreEnvio").val($("#txtNombre").val());			
			$("#txtDireccionEnvio").val($("#txtDireccion").val());		
			
			$("#cmbProvinciasEnvio").val($("#txtProvincia").val());
			
			/*PAISES DESACTIVADO
			if($("#txtPais").val() != 'ES')
			{
				$("#cmbProvinciasEnvio").val(0);
				$("#cmbProvinciasEnvio").attr("disabled", "disabled");
			}//fin if
			else			
				$("#cmbProvinciasEnvio").val($("#txtProvincia").val());
			*/
			
			
			
			$("#txtLocalidadEnvio").val($("#txtLocalidad").val());
			$("#txtCpEnvio").val($("#txtCp").val());			
			//$("#cmbPaisesEnvio").val($("#txtPais").val());PAISES DESACTIVADO
			$("#txtTelefonoEnvio").val($("#txtTelefono").val());
			$("#txtEmailEnvio").val($("#txtEmail").val());		
					
			//$("#txtNombreEnvio, #txtDireccionEnvio, #txtProvinciaEnvio, #txtLocalidadEnvio, #txtCpEnvio, #txtPaisEnvio, #txtTelefonoEnvio, #txtEmailEnvio").attr("readonly", "readonly");
		},
		function()
		{
			$(this).css("backgroundPosition", "bottom");//posicionamos la imagen de fondo del button abajo para que parezca activo
			
			$("#txtNombreEnvio").val("");			
			$("#txtDireccionEnvio").val("");
			$("#cmbProvinciasEnvio").attr("disabled", "");
			$("#cmbProvinciasEnvio").val(0);
			$("#txtLocalidadEnvio").val("");
			$("#txtCpEnvio").val("");
			//$("#cmbPaisesEnvio").val(0); PAISES DESACTIVADO
			$("#txtTelefonoEnvio").val("");
			$("#txtEmailEnvio").val("");		
					
			//$("#txtNombreEnvio, #txtDireccionEnvio, #txtProvinciaEnvio, #txtLocalidadEnvio,, #txtCpEnvio, #txtPaisEnvio, #txtTelefonoEnvio, #txtEmailEnvio").attr("readonly", "");
		}
	);
	
	//imprime la factura
	$("#btnImprimir").click(function(){	
		window.print();	
	});
	
	
	//manejo de los radio buttons para los acabados: marcamos el primero.
	$("ul.acabados li button:first").css("backgroundPosition", "top");
	
	//interruptor para evitar que el AJAX se ejecute varias veces al hacer click repetidas veces el radio button de un acabado
	var swAjax = true;
	
	//manejo de los radio buttons para los acabados: al pulsar uno, el que esta activado se desactiva.
	$("ul.acabados li button").click(function(){
			
		var valorRadio = $(this).val().replace(/SPAN|\<|\>|\//g, "");
		
		//En caso de pulsar sobre el acabado en el que ya se esta, no se hace nada
		if(valorRadio == $("#hdnAcabado").val())
			return false;
		
		if(swAjax)//si es true, dejamos que ejecute todo lo siguiente
		{			
			$("ul.acabados li button").css("backgroundPosition", "bottom");
			$(this).css("backgroundPosition", "top");
			$("#hdnAcabado").val(valorRadio);
			
			$.ajax({
				type: "GET",
				url: "http://www.becaratiendaonline.com/includes/imagenesAcabados.proc.php",
				data: "producto=" + $("#hdnCodigo").val() + "&acabado=" + $("#hdnAcabado").val(),
				beforeSend: function(){
							
					swAjax = false; //hasta que no haya pasado todo el ajax, bloqueamos la ejecucion de codigo al clickar los radios
					$(".contenedorImagen").html("");
					$(".carruselImagenes").html("");
				},
				success: function(datos){

					if(datos != "null")
					{
						imagenes = eval(datos);				
						
						
						$(".contenedorImagen").html('<img id="fotoDetalles" src="http://www.becaratiendaonline.com/imagenes/productos/detalles_/' + imagenes[0] + '" alt="imagen grande" />');								
												
						var thumbs = '';
						
						for(i = 0; i < imagenes.length; ++i)
							thumbs += '<img class="producto-thumb" id="f' + imagenes[i] + '" src="http://www.becaratiendaonline.com/imagenes/productos/thumbs_/' + imagenes[i] + '" target="_blank" />';

						
						$(".carruselImagenes").html(thumbs);
						
						$(".producto-thumb").bind("click", function(){
							
							$("#fotoDetalles").hide();
							
							var foto = $(this).attr("id").substring(1, $(this).attr("id").length); //quitamos la 'f' del identificador de la imagen
							
							$("#fotoDetalles").attr("src", "http://www.becaratiendaonline.com/imagenes/productos/detalles_/" + foto);
							
							$("#fotoDetalles").load(function(){
							
								$("#fotoDetalles").show();
							
							});					
						
						});
						
						//Sacar datos del webservice es lento. Para agilizar el proceso, cargamos primero la galería
						//y, una vez cargada, sacamos el precio.
						$.ajax({
							type: "GET",
							url: "http://www.becaratiendaonline.com/includes/precioAcabados.proc.php",
							data: "producto=&acabado=" + $("#hdnAcabado").val(),
							beforeSend: function(){
								$("#precio").html('Cargando precio...');
							},
							success: function(datos){
								//alert(datos);								
								$("#precio").html(datos + "&euro;");								
							}
						});//fin ajax					
						
						swAjax = true;//una vez finalizado todo, dejamos que se pueda clickar sobre los radios
					}//fin if	
					else
					{
						swAjax = true;//una vez finalizado todo, dejamos que se pueda clickar sobre los radios
						$(".contenedorImagen").html('<img id="fotoDetalles" src="http://www.becaratiendaonline.com/imagenes/productos/noImagen.gif" alt="imagen grande" />');				
					}//fin else
				}//fin success
			});//fin ajax
		}//fin if	
	});
	

	
	//cierra el velo blanco y negro
	$("#btnCerrarCapaBlanca").click(function(){
	
		if(jQuery.browser.msie && jQuery.browser.version == "6.0")
		{
			$("html, body").css("height", "1000px");			
			$("html, body").css("overflow", "auto");
		}//fin if

		$("#veloNegro").css("display", "none");
		$("#contenidoBlanco").css("display", "none");
	
	});	
	
	
	
	//manejo de imagenes thumb en los detalles del producto
	$(".producto-thumb").click(function(){
	
		//$("#fotoDetalles").hide();

		var foto = $(this).attr("id").substring(1, $(this).attr("id").length); //quitamos la 'f' del identificador de la imagen
		
		$("#fotoDetalles").attr("src", "http://www.becaratiendaonline.com/imagenes/productos/detalles_/" + foto);
		$("a#alargarImagen").attr("href", "http://www.becaratiendaonline.com/imagenes/productos/grandes_/" +  foto);		
		
		$("#fotoDetalles").load(function(){
		
			$("#fotoDetalles").show();
		
		});
	
	});



	//boton para refrescar el carrito (verCesta.php)
	$("#btnRefresca").click(function(){

		var msg;

		for(i = 0; i < $("input").length; ++i)
		{		
			$("#txtCantidad" + i).val(jQuery.trim($("#txtCantidad" + i).val()));
			valor = parseInt($("#txtCantidad" + i).val());
			
			if($("#txtCantidad" + i).val() == 0 || $("#txtCantidad" + i).val() == "" || isNaN(valor))
				msg = "Alguna de las cantidades son incorrectas.";	
		}//fin for

		if(msg)
			alert(msg);

		else
		{
			$("#formuVerCesta").attr('action', 'cesta');
			$("#formuVerCesta").submit();
		}//fin else
	});	


	//boton para comenzar la compra (verCesta.php)
	$("#btnFinalizarCompra").click(function(){
		
		var msg;
		var no_disponible = '';
		
		if(no_disponible == '1')
			alert('Lo siento, pero no podemos procesar su compra.\nExisten items no disponibles en su carrito de la compra.');
		else
		 {
			for(i = 0; i < $("input").length; ++i)
			 {		
				$("#txtCantidad" + i).val(jQuery.trim($("#txtCantidad" + i).val()));
				valor = parseInt($("#txtCantidad" + i).val());
			
				if($("#txtCantidad" + i).val() == 0 || $("#txtCantidad" + i).val() == "" || isNaN(valor))
					msg = "Alguna de las cantidades son incorrectas.";		
			 }//fin for
		
			if(msg)
				alert(msg);
			else
				$("#formuVerCesta").submit();		 
		 }

	});
	
	
	
	//Evitar que se introduzcan caracteres alfanumericos en la cantidad
	$(".entero").keypress(function(e) {

		var key;
		var keychar;
		
		if (window.event)
			key = window.event.keyCode;
		else if (e)
			key = e.which;
		else
			return true;
		
		keychar = String.fromCharCode(key);

		// control keys
		if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
			return true;

		// numbers
		else if((("0123456789").indexOf(keychar) > -1))
			return true;
		else
			return false;
	});

	//Similar al anterior pero para telas
	$(".pdecimales").keypress(function(e) {

		var key;
		var keychar;
		var alltext = document.getElementById('txtCantidad').value;

		if (window.event)
			key = window.event.keyCode;
		else if (e)
			key = e.which;
		else
			return true;
		
		keychar = String.fromCharCode(key);

		// control keys


		if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
			return true;
		// Only one decimal sign
		else if (((".").indexOf(keychar) > -1) &&  (alltext.indexOf(".") > -1))
			return false;
		//only 2 decimals
		else if ((alltext.indexOf(".") >= 1 && alltext.indexOf(".") <= alltext.length-3))
			return false;
		// numbers
		else if(((".0123456789").indexOf(keychar) > -1))
			return true;
		else
			return false;
	});	
	
	//boton de agregar a la cesta
	$("#btnAnadirCesta").click(function(){
		
		$("#txtCantidad").val(jQuery.trim($("#txtCantidad").val()));
		
		var swEntero = true;
		var valor = parseInt($("#txtCantidad").val());
		
		if($("#txtCantidad").length == 0 || $("#txtCantidad").val() == 0 || isNaN(valor))
			alert("Debes indicar una cantidad correcta.");
		else			
			$("#formuAgregar").submit();	
	});	
		
		
	//Manda el formulario al TPV automaticamente al cargar la página
	if($('#formuDatosTpv').length > 0)
		$('#formuDatosTpv').submit();

	
	
	/**
	*	Enviar el formulario de contacto
	*/
	$('#btnEnviar').click(function(){
	
		var msg = '';
		
		$('#txtNombre').val($.trim($('#txtNombre').val()));
		
		if($('#txtNombre').val() == '')
			msg += 'Debes rellenar el campo \"Nombre\"\n';
		if($('#txtApellidos').val() == '')
			msg += 'Debes rellenar el campo \"Apellidos\"\n';
		if($('#txtEmail').val() == '')
			msg += 'Debes rellenar el campo \"E-mail\"\n';
		if($('#txtComentario').val() == '')
			msg += 'Debes rellenar el campo \"Comentario\"\n';
			
		if(msg)
			alert(msg)
		else
			$('#formuContacto').submit();			
	});	
});
