//Mostar seccion al presionar boton ----------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
function Bon(NombreSeccion){
	Boff();
	document.getElementById(NombreSeccion).scrollTop = 0;
	document.getElementById(NombreSeccion).style.display = 'block';
}
function Boff(){
	document.getElementById("joyeria").style.display = 'none';
	document.getElementById("repujados").style.display = 'none';
	document.getElementById("cajas").style.display = 'none';
	document.getElementById("vidrieras").style.display = 'none';
	document.getElementById("otros").style.display = 'none';
	document.getElementById("bazar").style.display = 'none';
	
	document.getElementById("principal").style.display = 'none';
	document.getElementById("enlaces").style.display = 'none';
	document.getElementById("carrito").style.display = 'none';
	document.getElementById("contacto").style.display = 'none';
}

//Mostrar foto -------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
function fotoon(direccionfoto){
	document.getElementById("marcofoto").style.display = 'block';
	document.getElementById("imagenfoto").src = " ";
	document.getElementById("imagenfoto").src = direccionfoto;
	document.getElementById("marcofotofondo").style.display = 'block';
}
function fotooff(){
	document.getElementById("imagenfoto").src = " ";
	document.getElementById("marcofoto").style.display = 'none';
	document.getElementById("marcofotofondo").style.display = 'none';
}

//Formularios de ariculo ---------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
function mostrarFormulario(evento){
	
	var producto=evento.parentNode.parentNode;
	producto.className='bloque2';
	formulario = evento.parentNode.parentNode.getElementsByTagName('form');
	a = formulario[0].clientHeight;
	formulario[0].style.height = 0 + 'px';
	setTimeout(function(){efectoDesplegar(formulario[0],0,a);},40);
}
function efectoDesplegar(objeto,fin,a){
	
	if (fin<=4)
	{
		objeto.style.height = ((a/5)*fin) + 'px';
		fin=++fin;
		setTimeout(function(){efectoDesplegar(objeto,fin,a);},40);
	}else{
		objeto.style.height = 'auto';
	}
}
function cancelarMandarCarrito(evento){
	var producto=evento.parentNode.parentNode;
	producto.className='bloque1';
	formulario = producto.getElementsByTagName("form");
	formulario[0].reset();
	actualizarPrecio(formulario[0].Cantidad);
}
//Formularios de ariculo - Carrito -----------------------------------------------------------------
function mandarCarrito(evento){
	var producto = evento.parentNode.parentNode;
	var productoCopiado = producto.cloneNode(true);
	productoCopiado.className='bloque3';
	producto.className='bloque1';
	productoDestino=document.getElementById("carritoPedidos");
	productoDestino = productoDestino.appendChild(productoCopiado);
	copiarDatos(producto,productoDestino);
	anyadidoAlCarrito(1);
	sumarPrecio();
	setTimeout(function(){mensajes("mensajeEnvioCarrito",1000,11);},1);
	formulario = producto.getElementsByTagName("form");
	formulario[0].reset();
	actualizarPrecio(formulario[0].Cantidad);
}
function copiarDatos(original,copia){
	originalCajas = original.getElementsByTagName('input');
	copiaCajas = copia.getElementsByTagName('input');
		for(i=0;i<originalCajas.length;i++){
			copiaCajas[i].value = originalCajas[i].value;
		}
		originalSelectores = original.getElementsByTagName('select');
		copiaSelectores = copia.getElementsByTagName('select');
		for(i=0;i<originalSelectores.length;i++){
			copiaSelectores[i].value = originalSelectores[i].value;
		}
}
function borrarCarrito(evento){
	var producto = evento.parentNode.parentNode;
	producto.parentNode.removeChild(producto);
	mensajes("mensajeBorradoCarrito",1000,11);
	anyadidoAlCarrito(-1);
	sumarPrecio();
}

//Efecto parapadeo botones -------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
var contadorB = new Array(10);
function botonParpadeo(i,opacidadBoton,botonObjetivo,contadorI){
	opacidadBoton = opacidadBoton + i;
	botonObjetivo.style.opacity = opacidadBoton/10;
	botonObjetivo.style.filter = 'alpha(opacity='+ (opacidadBoton*10) +')';
	botonObjetivo.childNodes[0].style.filter = 'alpha(opacity='+ (opacidadBoton*10) +')';
	if (opacidadBoton == 0)
	{
		i = 1;
	}else if (opacidadBoton == 10){
		i = -1;
	}
	contadorB[contadorI] = setTimeout(function(){botonParpadeo(i,opacidadBoton,botonObjetivo,contadorI);},100);
}
//Efecto parapadeo botones - Carrito ---------------------------------------------------------------
var botonCarrito = document.getElementById("bcarrito");
botonCarrito.style.opacity = 1.0;
botonCarrito.style.filter = 'alpha(opacity='+ 100 +')';
botonCarrito.childNodes[0].style.filter = 'alpha(opacity='+ 100 +')';
var numeroArticulos = 0;
function anyadidoAlCarrito(anyadido){
	contadorI = 0;
	numeroArticulos = numeroArticulos + anyadido;
	if (numeroArticulos == 1 && anyadido == 1)
	{
		contadorB[contadorI] = setTimeout(function(){botonParpadeo(-1,10,botonCarrito,contadorI);},100);
	}
	else if (numeroArticulos == 0)
	{
		clearTimeout(contadorB[contadorI]);
		botonCarrito.style.opacity = 1.0;
		botonCarrito.style.filter = 'alpha(opacity='+ 100 +')';
		botonCarrito.childNodes[0].style.filter = 'alpha(opacity='+ 100 +')';
	}
}

//Desplegar preguntas frecuentes -------------------------------------------------------------------
function mostrarFAQ(tituloFAQ){
textoFAQ = tituloFAQ.parentNode.getElementsByTagName('div');
textoFAQ = textoFAQ[0];
	if (textoFAQ.style.display != "block")
		{
			textoFAQ.style.display = "block";
			a = textoFAQ.clientHeight;
			textoFAQ.style.height = 0 + 'px';
			setTimeout(function(){efectoDesplegar(textoFAQ,0,a);},40)
		}else{
			textoFAQ.style.display = "none";
		}
}

//Mensajes sistema ---------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
var contadorM;
function mensajes(mensaje,tiempo,opacidadMensaje){
	mensajeElegido = document.getElementById(mensaje);	
	if (opacidadMensaje == 11)
	{
		mensajeElegido.style.opacity = 0.5;
		mensajeElegido.style.filter = 'alpha(opacity='+ 50 +')';
		mensajeElegido.style.display = 'block';
		opacidadMensaje = opacidadMensaje - 1;
		setTimeout(function(){mensajes(mensaje,tiempo,opacidadMensaje);},50);
		altura = mensajeElegido.clientHeight;
		mensajeElegido.style.marginTop = Math.round(-altura /2) + "px";
	}
	else if (opacidadMensaje == 10)
	{
		mensajeElegido.style.opacity = 1.0;
		mensajeElegido.style.filter = 'alpha(opacity='+ 100 +')';
		opacidadMensaje = opacidadMensaje - 1;
		setTimeout(function(){mensajes(mensaje,tiempo,opacidadMensaje);},tiempo);
	}
	else if (opacidadMensaje > 0)
	{
		mensajeElegido.style.opacity = opacidadMensaje/10;
		mensajeElegido.style.filter = 'alpha(opacity='+ (opacidadMensaje*10) +')';
		setTimeout(function(){mensajes(mensaje,tiempo,opacidadMensaje);},50);
		opacidadMensaje = opacidadMensaje - 1;
	}
	else
	{
		opacidadMensaje = 11;
		mensajeElegido.style.display = 'none';
	}
	
}

//Mensajes ayuda -----------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
var mensajeAyudaActual = 0;
var contadorMA;
function mensajesAyuda(mensaje,a){
	mensajeElegido = document.getElementById(mensaje);
	switch (a)
	{
		case 4:
			clearTimeout(contadorMA);
			if (mensajeAyudaActual == mensajeElegido)
			{
				a = 3;
				contadorMA = setTimeout(function(){mensajesAyuda(mensaje,a);},50);
			}
			else
			{
			if(mensajeAyudaActual!=0){mensajeAyudaActual.style.display = 'none';}
			mensajeAyudaActual = mensajeElegido;
			mensajeElegido.style.opacity = 0.5;
			mensajeElegido.style.display = 'block';
			a = 3;
			contadorMA = setTimeout(function(){mensajesAyuda(mensaje,a);},50);
			}
			break;
		case 3:
			mensajeElegido.style.opacity = 1.0;
			break;
		case 2:
			a = 1;
			contadorMA = setTimeout(function(){mensajesAyuda(mensaje,a);},2000);
			break;
		case 1:
			mensajeElegido.style.opacity = 0.5;
			a = 0;
			setTimeout(function(){mensajesAyuda(mensaje,a);},50);
			break;
		case 0:
			mensajeElegido.style.display = 'none';
			mensajeAyudaActual = 0;
			break;
	}	
}

//Comprovaciones de formularios --------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
function permite(elEvento, permitidos) {
	var numeros = "0123456789";
	var caracteres = " abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
	var numeros_caracteres = numeros + caracteres;
	var teclas_especiales = [8, 37, 39, 46];
	switch(permitidos)
	{
		case 'num':
			permitidos = numeros;
			break;
		case 'car':
			permitidos = caracteres;
			break;
		case 'num_car':
			permitidos = numeros_caracteres;
			break;
	}
	var evento = elEvento || window.event;
	var codigoCaracter = evento.charCode || evento.keyCode;
	var caracter = String.fromCharCode(codigoCaracter);
	var tecla_especial = false;
	for(var i in teclas_especiales)
	{
		if(codigoCaracter == teclas_especiales[i])
		{
			tecla_especial = true;
			break;
		}
	}
	return permitidos.indexOf(caracter) != -1 || tecla_especial;
}
function validarFormulario() {
	c = 1;
	d = 2;
	e = 4;
	color = "#aaaaff";
	var campos = [nombre,apellidos,dni,email,telefono,direccion,ciudad,provincia,cpostal];
	for (i=0;i<campos.length;i++)
	{
		if(campos[i].value=="")
		{
			campos[i].parentNode.style.backgroundColor  = color;
			c = 0;
		}else{
			campos[i].parentNode.style.backgroundColor  = "";
		}
	}
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email.value))
	{
		email.parentNode.style.backgroundColor  = "";
	} else {
		email.parentNode.style.backgroundColor  = color;
		d = 0;
	}
	if	(numeroArticulos == 0)
	{
		e = 0;
	}
	return c + d + e;
}
var nombre = document.forms["formularioenvio"].nombre;
var apellidos = document.forms["formularioenvio"].apellidos;
var dni = document.forms["formularioenvio"].dni;
var email = document.forms["formularioenvio"].email;
var telefono = document.forms["formularioenvio"].telefono;
var pais = document.forms["formularioenvio"].pais;
var direccion = document.forms["formularioenvio"].direccion;
var ciudad = document.forms["formularioenvio"].ciudad;
var provincia = document.forms["formularioenvio"].provincia;
var cpostal = document.forms["formularioenvio"].cpostal;
var pago = document.forms["formularioenvio"].pago;
//var envio = document.forms["formularioenvio"].envio;
var comentario = document.forms["formularioenvio"].comentario;
var listapedido = document.forms["formularioenvio"].articulos;
//Ajax formulario de envio -------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
function enviodeFormulario(){
	var mensajeError = ["El formulario está incompleto.\nCumplimenta llas casillas marcadas en azul.\n\n","La dirección de email " + email.value + " es incorrecta.\nComprueba que esta bien escrita (persona@servidor.dominio).\n\n","El carrito esta vacio.\nComprueba que has seleccionado al menos un articulo del catálogo.\n\n"];
	switch(validarFormulario())
	{
		case 7:
			prepararlistaarticulos();
			http = getXMLHTTPRequest();
			var url = '../phpmailer/envio.php';
			http.open("POST", url,true);
			http.onreadystatechange = respuesta;
			http.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			http.send("&Nombre="+nombre.value+"&Apellidos="+apellidos.value+"&Dni="+dni.value+"&Email="+email.value+"&Telefono="+telefono.value+"&Pais="+pais.value+"&Direccion="+direccion.value+"&Ciudad="+ciudad.value+"&Provincia="+provincia.value+"&Cpostal="+cpostal.value+"&Pago="+pago.value+"&Comentario="+comentario.value+"&Listapedido="+listapedido.value);
			listapedido.value = "";
			break;
		case 6:
			alert(mensajeError[0]);
			break;
		case 5:
			alert(mensajeError[1]);
			break;
		case 4:
			alert(mensajeError[0] + mensajeError[1]);
			break;
		case 3:
			alert(mensajeError[2]);
			break;
		case 2:
			alert(mensajeError[0] + mensajeError[2]);
			break;
		case 1:
			alert(mensajeError[1] + mensajeError[2]);
			break;
		case 0:
			alert(mensajeError[0] + mensajeError[1] + mensajeError[2]);
			break;
	}
}
//Ajax formulario de envio - HTTPReques ------------------------------------------------------------
var http;
function getXMLHTTPRequest() {
	try
	{
		req = new XMLHttpRequest();
	}catch(err1){
		try
		{
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}catch (err2){
			try
			{
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}catch (err3){
				req = false;
			}
		}
	}
  return req;
}
//Ajax formulario de envio - lista Articulos -------------------------------------------------------
function prepararlistaarticulos(){
	lista = document.getElementById("listaarticulos").getElementsByTagName('form');
	for(i=0;i<lista.length;i++)
	{
		titulo = lista[i].parentNode.getElementsByTagName('h2');
		listapedido.value = listapedido.value + "<h3>" + titulo[0].childNodes[0].nodeValue + "</h3>";
		listapedido.value = listapedido.value + "<ul>";
		var cajas = lista[i].getElementsByTagName("input");
		for(j=0;j<cajas.length;j++){
			listapedido.value = listapedido.value + "<li>" + cajas[j].getAttribute('name') + ": " + cajas[j].value + "</li>";
		}
		selectores = lista[i].getElementsByTagName("select");
		for(j=0;j<selectores.length;j++){
			listapedido.value = listapedido.value + "<li>" + selectores[j].getAttribute('name') + ": " + selectores[j].value + "</li>";
		}
		listapedido.value = listapedido.value + "</ul>";
	}
	listapedido.value = listapedido.value + "<hr><h3>Gastos de envio: " + gastosEnvio.nodeValue + "</h3><h2>Total: " + precioTotal.nodeValue + "</h2>";
}
//Ajax formulario de envio - respuesta -------------------------------------------------------
function respuesta() {
	if (http.readyState == 4)
	{
		if(http.status == 200)
		{
			switch (http.responseText)
			{
				case "1":
					mensajes("mensajeEnvioFormulario",5000,11);
					break;
				case "0":
					alert("Error garrafal. Pongase en contacto con admin@palaciodeloscuervos.com");
					break;
			}
		}else{
			alert(http.status);
		}
	}
}

//suma de precios ----------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
var carritoPedidosTotal = document.getElementById("carritoPedidosTotal");
var avisoCarritoLleno = document.getElementById("avisocarritolleno").getElementsByTagName("p");
var precioTotal = document.getElementById("precioTotal").childNodes[0];
var gastosEnvio = document.getElementById("gastosEnvio").childNodes[0];
function sumarPrecio(){
b = 0;
sumaArticulos = 0;
sumaEnvios = 3;
pesoArticulos = 0;
sumaNumeroArticulos = 0;
	if  (numeroArticulos == 0)
	{
		carritoPedidosTotal.style.display = "none";
	}else if (numeroArticulos == 1){
		carritoPedidosTotal.style.display = "block";
	}
	objetivo = document.getElementById("carritoPedidos").getElementsByTagName("form");
	for (i=0;i<objetivo.length;i++)
	{
		
		sumaArticulos = sumaArticulos + (parseFloat(objetivo[i].Precio.value) * parseFloat(objetivo[i].Cantidad.value));
		switch (objetivo[i].Tipo.value)
		{
			case "joya":
				pesoArticulos = pesoArticulos + parseFloat(objetivo[i].Cantidad.value);
				break;
		}
		sumaNumeroArticulos = sumaNumeroArticulos + parseFloat(objetivo[i].Cantidad.value);
	}
	if (sumaNumeroArticulos == 1)
	{
		avisoCarritoLleno[0].childNodes[0].nodeValue = sumaNumeroArticulos + " articulo";
	}else{
		avisoCarritoLleno[0].childNodes[0].nodeValue = sumaNumeroArticulos + " articulos";
	}
	sumaEnvios = sumaEnvios + (2 * Math.round(pesoArticulos/2));
	gastosEnvio.nodeValue = "+" + sumaEnvios.toFixed(2) + "€";
	b = sumaArticulos + sumaEnvios;
	precioTotal.nodeValue = b.toFixed(2) + "€";
	
}
marcarPrecios();
function marcarPrecios(){

	precio = document.getElementsByName("Precio");
	for (i=0;i<precio.length;i++)
	{
		marcarPrecio(precio[i].parentNode.parentNode.parentNode.getElementsByTagName("p"),precio[i]);
	}
}
function actualizarPrecio(objeto){
marcarPrecio(objeto.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("p"),objeto.parentNode.parentNode.parentNode.Precio);
sumarPrecio();

}
function marcarPrecio(textoPrecio, precio){	
	b = parseFloat(precio.value) * parseFloat(precio.parentNode.parentNode.Cantidad.value);
	textoPrecio[textoPrecio.length - 5].childNodes[0].nodeValue = b.toFixed(2) + "€";
}
