// JavaScript Document

window.addEvent('domready', function() {
	applyRollOvers();
	initForms();
	hideDetails();
});

function initForms(){
	applyInputOverText("infolettreEmail");
	applyInputOverText("stf_from_name");
	applyInputOverText("stf_to");
	applyInputOverText("stf_from_email");
	applyInputOverText("stf_message");
}

function applyInputOverText(elId){
	var tE = $(elId);
	if(tE){
		tE.store('defaultValue', tE.get('value'));
		tE.addEvent('focus', function(e){
			e.stop();
			var tV = this.get('value');
			if(tV == this.retrieve('defaultValue')) this.set('value', '');
		});
		tE.addEvent('blur', function(e){
			e.stop();
			var tV = this.get('value');
			if(tV == '') this.set('value', this.retrieve('defaultValue'));
		});
	}
}


function applyRollOvers(){
	//preload images
	var aPreLoad = new Array();
	var aPreLoadi = 0;
 
	//ROLL OVER D'IMAGES SUR LES MENUS
	$$('.mnuRoll').each(function(el){
		//let's preload
		aPreLoad[aPreLoadi] = new Image();
		aPreLoad[aPreLoadi].src = el.src.replace(el.src.replace('_1', '_2'));
		aPreLoadi++;
 
		el.addEvent('mouseover',function(){
			this.setAttribute('src',this.src.replace('_1', '_2'));
		});
 
		el.addEvent('mouseout',function(){
			this.setAttribute('src',this.src.replace('_2','_1'));
		});
	});
	
	//set le menu sélectionné
	$$('.mnuSelected').each(function(el){
		el.setAttribute('src',el.src.replace('_1', '_3'));
	});
	
	
	///pour la liste en accueil
	$$('.itemAccueil').each(function(el){
	
		el.addEvent('mouseover',function(){
			this.setStyle('background-color', '#eeedda');
			var title = this.getElement('.listTitre');
			title.setStyle('color', '#d30a0a');
		});
 
		el.addEvent('mouseout',function(){
			this.setStyle('background-color', '#f7f6ec');
			var title = this.getElement('.listTitre');
			title.setStyle('color', '#000');
		});
	});
	
	//POUR LES SOUS MENUS!
	$$('.itemSousMenu').each(function(el){
	
		el.addEvent('mouseover',function(){
			this.setStyle('background-color', '#e4e2c4');
			this.setStyle('color', '#d30a0a');
		});
 
		el.addEvent('mouseout',function(){
			this.setStyle('background-color', 'transparent');
			this.setStyle('color', '#000');
		});
	});
	
	$$('.itemSousMenuSelected').each(function(el){
		el.setStyle('background-color', '#e4e2c4');
		el.setStyle('color', '#d30a0a');
	});
}

/******* POUR L'OUVERTURE DES DÉTAILS DANS LES LISTES *******/
/******************************
/* toggleDetails(id, show)
/* ouvre le paneau de détail, appelé sur le click du lien
/******************************/
function toggleDetails(id, show){
	var progItem = $('progItem_'+id);
	var detailPane = progItem.getElement(".progItemDetails");
	var plusInfoBt = progItem.getElement(".plusInfo");
	
	var myFx = new Fx.Slide(detailPane,{
     duration: 1000,
   	 transition: Fx.Transitions.Pow.easeOut
	});
	
	var myTween = new Fx.Tween(progItem, {
     duration: 1000,
   	 transition: Fx.Transitions.Pow.easeOut
	});
	
	elementUpdate = (detailPane)
	var myFx = new Fx.Slide(detailPane,{
		duration: 1000,
		transition: Fx.Transitions.Pow.easeOut,
		onComplete: function(){initResize()}
	});
	
	if (show){
		myFx.slideIn();
		myTween.start("background-color","#FFF");
		plusInfoBt.fade("out");
		detailPane.fade("in");
		var gotoPane = function(){
		 var myFxScroll = new Fx.Scroll(window).toElement('progItem_'+id);
		}.delay(200);
	}else{
		myFx.slideOut();
		myTween.start("background-color","#f7f6ec");
		plusInfoBt.fade("in");
		detailPane.fade("out");
	}
}

function toggleDetailsNvl(id, show){
	var nvlItem = $('nvlItem_'+id);
	var previewPane = nvlItem.getElement(".nvl_preview");
	var detailPane = nvlItem.getElement(".nvl_complete");
	
	var previewFx = new Fx.Slide(previewPane,{
     duration: 1000,
   	 transition: Fx.Transitions.Pow.easeOut
	});
	
	var detailFx = new Fx.Slide(detailPane,{
     duration: 1000,
   	 transition: Fx.Transitions.Pow.easeOut
	});
	
	
	elementUpdate = (detailPane) // Déclaration de l'élément en cour de transformation
	var detailFx = new Fx.Slide(detailPane,{
	  duration: 1000,
	  transition: Fx.Transitions.Pow.easeOut,
	  onComplete: function(){initResize()} // Initialisation du resize du background
	});
	
	if (show){
		previewFx.slideOut();
		detailFx.slideIn();
		previewPane.fade('out');
		detailPane.fade('in');
	}else{
		previewFx.slideIn();
		detailFx.slideOut();
		previewPane.fade('in');
		detailPane.fade('out');
	}
}

function hideDetails(){
	$$('.progItemDetails', '.nvl_complete').each(function(el){
		var myFx = new Fx.Slide(el);
		myFx.hide();
	});
}

/******* INSCRIPTION À L'INFOLETTRE *************/
function subscribeInfolettre(){
	var email = $("infolettreEmail").value;
	if (!validateEmail(email)){
		//invalide
		alert("Votre courriel est invalide");
	}else{
		//valide
		var subscribeRequest = new Request.JSON({url: "phpScripts/infolettreSubscribe.php", onComplete: function(obj){
		if(obj.status == "1"){ //success
			$("blockInfolettre").set("html",(
				"<div>Merci, vous recevrez un courriel de confirmation sous peu.</div>"
			));
		}
		}}).get({'email': email});
	}
}

/******* POUR L'IMPRESSION D'UN ÉVÉNEMENT ******/
function printEvent(eventId){
	if(Browser.Engine.trident){
		var pwin = window.open('eventPrint.php?id='+eventId, "printwin", "width=620, height=400");
	}else{
		$("printIframe").src = 'eventPrint.php?id='+eventId;
	}
	//$("printIframe").location.href='eventPrint.php?id='+eventId;
	//$("printIframe").setProperty('src', 'eventPrint.php?id='+eventId);
}

/****** AFFICHE LE BACKDROP NOIR **********/
function showBlackOverlay(){
	$("blackOverlay").setStyle('display','block');
	$("blackOverlay").addEvent("click", function(){
			this.setStyle('display','none');
	});
}

/****** AFFICHE LE DÉTAIL DE L'OBJET DANS BOUTIQUE ****/
function openBoutiqueDetails(divItem){
	Shadowbox.open({
        content:    $(divItem).get("html"),
        player:     "html",
       /* title:      $(divItem).getElementById("titre").get("text"),*/
        height:    540,
        width:  	700   
    });
}

/***** ADD 2 CART ********************************/
function add2cart(nom, prix){
	$("item_name").value = nom;
	$("amount").value = prix;
	$("paypall").submit();
}

/****** AFFICHE LA FENÊTRE SEND TO A FRIEND ******/
function stf(eventId){
	showModal("#000", {
		events: {
			click: function() {
				fadeHideModal();
			}
		}
	});
	$("sendToFriendForm").getElementById('STFnomArticle').set("text", getNomArticle(eventId));
	$("sendToFriendForm").getElementById('stf_event_id').value = eventId;
	$("modalContent").adopt($("sendToFriendForm"));
	$("sendToFriendForm").setStyle("display", "block");
	reinitForm();
					 
}
function reinitForm(){
	//efface les anciennes notices
	$$(".validationNotice").dispose();
	$$("#loadIco").dispose();
	
	$("STF_form").setStyle("visibility", "visible");
	$$(".STF_input").each( function(item){
			item.set("value", item.retrieve('defaultValue'));
	});
	
}
function getNomArticle(eventId){
	//alert($('progItem_'+eventId).getElement(".progItemDescription").getElement("SPAN").get("text"));
	return $('progItem_'+eventId).getElement(".progItemDescription").getElement("SPAN").get("text");
}
function validate_and_send_STF(){
	var invalid_email = "Courriel invalide";
	var invalid_empty = "Ce champs est requis";
	var valid = true;
	
	var allFields = $$(".STF_input");
	var requiredFields = $$(".STF_required");
	var allEmailFields = $$(".STF_email");
	
	//efface les anciennes notices
	$$(".validationNotice").dispose();
	
	var isEmpty = new InputValidator('required', {
		errorMsg: 'This field is required.',
		test: function(field){
			return ((field.value == null) || 
					(field.value.length == 0) ||
					 field.value == field.retrieve('defaultValue'));
		}
	});
	
	//check if empty
	requiredFields.each(function(item){
		if(isEmpty.test(item) && valid){
			valid = false;
			showFormMessage(item, invalid_empty);
		}
	});
	
	//check les adresses email
	if(valid){
		allEmailFields.each(function(item){
			if (!validateEmail(item.value)){
				valid = false;
				showFormMessage(item, invalid_email);
			}
		});
	}
	
	if (valid){
		//met le message personnel à vide si la valeur n'a pas changée
		if (isEmpty.test($('stf_message'))){
			$('stf_message').set("value","");
		}
		send_STF();
	}
	

}

function send_STF(){
	$("STF_form").setStyle("visibility", "hidden");
	//cré l'icone loader
	var loadIcoDiv = new Element("DIV", {"id": "loadIco"}).inject($('sendToFriendForm'));
	
	var stfRequest = new Request.JSON({url: "phpScripts/sendToFriend.php", onComplete: function(obj){
		if(obj.status == "1"){ //success
			//$("loadIco").set("text", "Merci!");
			$("loadIco").dispose();
			fadeHideModal();
		}
	}}).get({'to': $('stf_to').value, 'fromName': $('stf_from_name').value, 'fromEmail': $('stf_from_email').value, 'message': $('stf_message').value, 'eventId':$('stf_event_id').value});
}

function validateEmail(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(address) == false) {
      return false;
   }else{
	   return true;
   }
}

function showFormMessage(item, message){
	var parentDiv = item.getParent();
	//alert("parent Div : " + parentDiv);
	var notice = new Element('div', {
				'class' : 'validationNotice',
				'text' : message,
				'styles' : {
					'opacity':0
				}
				}).inject(parentDiv);
	notice.fade(1);
	
}