var ProductHover = {};
ProductHover.productId;
ProductHover.positionTop;
ProductHover.positionLeft;

ProductHover.getProduct = function(elem)
{
	// Locate the product ID
	var mainElem, productId;
	mainElem = (elem.up(1).tagName.toUpperCase() != 'LI') ? elem.up(2) : elem.up(1);
	if (Object.isUndefined(mainElem.id) || mainElem.id.empty()) {
		return false;
	} else {
		productId = mainElem.id;
		productId = productId.gsub('p-', '');
	}

	// Define the left and top position
	var elemOffset = mainElem.cumulativeOffset();
	this.positionTop = elemOffset[1] + 'px';
	this.positionLeft = (mainElem.offsetLeft + 50) + 'px';

	if (this.productId == productId && $('product-hover-container')) {
		return true;
	}

	this.productId = productId;
	var url = PbLib.getNewURI('l/webshop2/product/' + productId + '/hover');
	new Ajax.Request(url, {
			'onSuccess': ProductHover.showProduct.bindAsEventListener(this),
			'onFailure': ProductHover.notFound.bindAsEventListener(this)
		});
}

ProductHover.notFound = function(transport)
{
	dialogElem = window.top.PbLib.createDialog(false, 400, 75);
	dialogElem.update("<div style='text-align: center;'>" +
		"<div>" + PbLib.g('Product could not be found.') + "</div>" +
		"<div><a href='" + window.top.document.location + "' onclick='Event.stop(event); window.top.PbLib.destroyDialog();'>" + PbLib.g('Close') + "</a></div>" +
		"</div>");

	this.productId = null;

	return false;
}

ProductHover.showProduct = function(transport)
{
	// Remove the current container if it exists
	if ($('product-hover-container')) {
		$('product-hover-container').remove();
	}

	var hoverElem = new Element('div', { 'id': 'product-hover-container', 'class': 'product-information-dialog' });
	hoverElem.setStyle({ 'position': 'absolute', 'top': this.positionTop, 'left': this.positionLeft });
	hoverElem.innerHTML = transport.responseText;

	hoverElem.observe('mouseover', function(event) {
		if (!Object.isUndefined(window.removeHoverTimeout)) {
			window.clearTimeout(removeHoverTimeout);
		}
	});
	hoverElem.observe('mouseout', function(event) {
		removeHoverTimeout = window.setTimeout(function() { $('product-hover-container').remove(); }, 400);
	});

	if ($('container')) {
		$('container').insert({'top': hoverElem});
	}

	return true;
}

document.observe('dom:loaded', function (event) {
	$$('img.product-image').each( function(elem) {

		// Remove the onclick action
		elem.observe('click', function(event) {
			Event.stop(event);
		});

		elem.observe('mouseover', function(event) {
			hoverTimeout = window.setTimeout(function() { ProductHover.getProduct(elem); }, 400);
		});

		elem.observe('mouseout', function(event) {
			if (!Object.isUndefined(window.hoverTimeout)) {
				window.clearTimeout(hoverTimeout);
			}
			if ($('product-hover-container')) {
				removeHoverTimeout = window.setTimeout(function() { $('product-hover-container').remove(); }, 400);
			}
		});

	});
});
