var popin = null;

Event.add(document, "domready", initialize);

function initialize(e){
	popin = new Popin();
	Element.setOpacity("ajaxLoader", 0);
	Event.add("searchInput", "focus", onFocusSearch);
	Event.add("searchInput", "blur", onBlurSearch);
	Event.add("searchSubmit", "click", onSubmitSearch);
	$$("a.userlogout").each(function(link){
		Event.add(link, "click", onUserLogout);
	});
	if($("submitcomment")) initCommentForm();
	if($("largeSearchForm")) initLargeSearchForm();
}

function showAjaxLoader(){
	Element.show("ajaxLoader");
	Element.show("locker");
	new Animation("ajaxLoader", {
		"opacity": {from: 0, to: 1}
	}, {
		duration: 500
	});
}

function hideAjaxLoader(callback){
	if(typeof callback === "undefined")
		callback = function(){};
	var handle = function(){
		Element.hide("locker");
		new Animation("ajaxLoader", {
			"opacity": {from: 1, to: 0}
		}, {
			duration: 500,
			onComplete: function(){
				Element.hide("ajaxLoader");
				callback.call(null);
			}
		});
	}
	handle.delay(500);
}

function initLargeSearchForm(){
	Event.add("largeSearchInput", "focus", onFocusSearch);
	Event.add("largeSearchInput", "blur", onBlurSearch);
	Event.add("largeSearchSubmit", "click", onSubmitLargeSearch);
}

function onFocusSearch(e){
	var input = Event.getElement(e);
	if(input.value.isEmpty() || input.value == "Rechercher")
		Element.update(input, "");
}

function onBlurSearch(e){
	var input = Event.getElement(e);
	if(input.value.isEmpty())
		Element.update(input, "Rechercher");
}

function onSubmitSearch(e){
	Event.cancel(e);
	if($("searchInput").value.isEmpty() || $("searchInput").value == "Rechercher"){
		popin.show({title: "Attention", message: "Veuillez saisir votre recherche."});
		return;
	}else $("searchForm").submit();
}

function onSubmitLargeSearch(e){
	Event.cancel(e);
	if($("largeSearchInput").value.isEmpty() || $("largeSearchInput").value == "Rechercher"){
		popin.show({title: "Attention", message: "Veuillez saisir votre recherche."});
		return;
	}else $("largeSearchForm").submit();
}

function initCommentForm(){
	Event.add("submitcomment", "click", onSendCommentForm);
}

function onSendCommentForm(e){
	Event.cancel(e);
	var form = Form.getHash("commentform");
	if(!$("login")){
		if(form.author.isEmpty()){
			popin.show({title: "Attention", message: "Veuillez saisir votre nom."});
			return;
		}
		if(form.email.isEmpty()){
			popin.show({title: "Attention", message: "Veuillez saisir votre adresse email."});
			return;
		}
	}
	if(form.comment.isEmpty()){
		popin.show({title: "Attention", message: "Veuillez saisir votre commentaire."});
		return;
	}
	$("commentform").submit();
}

function onUserLogout(e){
	Event.cancel(e);
	popin.show({
		type: "QUESTION",
		title: "Déconnexion",
		message: "Voulez-vous vraiment vous déconnecter ?",
		onYes: function(){
			document.location.href = Event.getElement(e).getAttribute("href");
		}
	});
}
