// Funciones para disminuir el acoplamiento entre el XHTML y Javascript.
//TODO: Reemplazar los puntos decimales por comas.	(Parece que solo se puede hacer a base de replaces puntuales).

function setEnlaceComprar() {
	if ($('numero_productos')) {
		quantity = parseInt($('numero_productos').innerHTML);
		var elem = $('comprar_productos');
		if (elem)
		elem.style.display = (quantity > 0) ? "block" : "none";
	}
}

function addEventHandlerToClassName (idClass, eventName, eventHandler) {
	if (idClass && eventName && eventHandler) {
		var adds = document.getElementsByClassName(idClass);	// $$('.idClass')? //con element.select('.class') irķa +rapido
		for (var i = 0; i < adds.length; i++) {
			if (adds[i].id) {
				element = $(adds[i].id);
				if (element)
					Event.observe(element, eventName, eventHandler);
			}
		}
	}
}

function init() {
	addEventHandlerToClassName('add', 'click', function() { 
		if (this.form.serigrafia && this.form.serigrafia.value == 1) 
			calculaPrecio(true); // Esto hace luego addProduct(this.form) con el nuevo precio.
		else addProduct(this.form);										 // addProduct *sin* calculaPrecio() previo. 
	});
	addEventHandlerToClassName('vermas','click',	function() { document.location.href=this.form.url.value; });
	Event.observe('searchForm','submit',function() { encontrar(this); return false; });
	Event.observe(	'busqueda',	'click',	function() { encontrar(this.form); });
	Event.observe(	'buscar'	,	'keyup',	function() { autocompletar('sugerencias', this.value); });
	setEnlaceComprar();

	if ($('variante')) {			// Solo disponible en ficha.php
		Event.observe('variante', 'change', 
			function() {

				this.form.key.value   = keys[this.value]; 
				this.form.name.value  = names[this.value];
				this.form.price.value = prices[this.value];
 
				if ($('nombre_producto'))	$('nombre_producto').update(names[this.value]);
				if ($('add'))					$('add').title = names[this.value];
				if ($('importe'))				$('importe').update(prices[this.value] + ' &euro;');
			}
		);
	}

	if ($('pago_por_transferencia')) {
		Event.observe('pago_por_transferencia', 'click', 
			function() { 
				if ($('notas_transferencia')) 
					$('notas_transferencia').style.display = "block";
			}
		);
	}

	if ($('pago_por_tarjeta')) {
		Event.observe('pago_por_tarjeta', 'click', 
			function() { 
				if ($('notas_transferencia')) 
					$('notas_transferencia').style.display = "none";
			}
		);
	}
}

Event.observe(window, 'load', function() { init(); });
