document.observe('dom:loaded', function() {
	SimplyButtons.init();

	new Ajax.Autocompleter('product', 'autocomplete_choices', './autocomplete.php', {frequency: 0.2, minChars: 2, noEnter: true, afterUpdateElement: submitLookFor});

	$('product').observe('focus', selectElement);
	$('lookfor').observe('submit', validLookFor);
	$('simpleSearchLink').observe('click', toggleSearchPanels);
	$('complexSearchLink').observe('click', toggleSearchPanels);
	$('next').observe('click', changeNews);

	bindLinkToMenu('itemLink', 'itemMenu');

	changeNews();

	reloadBasket(false);
});

function toggleSearchPanels(event) {
	Event.stop(event);

	$('simpleSearch').toggle();
	$('complexSearch').toggle();
}

function bindLinkToMenu(link, menu) {
	$(link).observe('click', showMenu.curry(menu));
	$(menu).observe('click', Effect.SlideUp.curry(menu, {duration: 0.5}));
}

function showMenu (menu, event) {
	var element = event.element();
	var pos1 = element.cumulativeOffset();
	var pos2 = element.cumulativeScrollOffset();
	var dim = element.getDimensions();
	var menuElem = $(menu);

	var pos = {x: pos1.left + pos2.left, y: pos1.top + dim.height + 5};

	event.stop();

	menuElem.setStyle({left: pos.x+'px', top: pos.y+'px'});

	$$('ul.menu').without(menuElem).each(function(m) {
		new Effect.BlindUp (m, {duration: 0.25});
	});

	new Effect.toggle(menuElem, 'blind', {duration: 0.5});
}

function changeNews() {
	var news = $('newsContent');

	if (changeNews.timeoutId) {
		clearTimeout(changeNews.timeoutId);
	}

	new Effect.Opacity(news, {queue: {position: 'end', scope: 'newsScope'}, from: 1, to: 0.25, duration: 0.5});

	new Ajax.Request('./news.php', {onComplete: function(response) {
		var json = response.responseJSON;

		if (json.code == 1) {
			new Effect.Opacity(news, {queue: {position: 'end', scope: 'newsScope'}, from: 0.25, to: 1, duration: 0.5, afterSetup: function() {
				$(news).update(json.content);
			}});
			changeNews.timeoutId = changeNews.delay(json.duration);
		}
	}});
}

function linkToLookFor(event) {
	Event.stop(event);

	$('product').value = event.findElement().innerHTML;

	submitLookFor();
}

function submitLookFor() {
	$('lookfor').submit();
}

function validLookFor(event) {
	if ($('product').value.length < 2) {
		Event.stop(event);

		alert('Le nom du produit doit comporter 2 caractères minimum');
	}
}