

$(document).ready(function(){
	
	texteBoutonFavoris = {
		FR : {
			ajout : 'Ajouter à mes favoris',
			suppression : 'Supprimer ce favori'
		},
		EN : {
			ajout : 'Add to my favorites ',
			suppression : 'Delete from favorites'
		}
	};
	
	$('.boutonAjouterFavoris').live('click',function(e){
		e.preventDefault();
		var $boutonTmp = $(this);
		noMembre = $(this).attr('href').replace(window.location.href,'').replace('#','');
		favoriteMemberToggle(noMembre, $(this));
	});
	
	var nbFav = 0;
	if(typeof($.cookie('noMembreFavoris')) == 'string'){
		var favstr = $.cookie('noMembreFavoris').toString();
		var favArray = favstr.split(',');
		favArray = unique(favArray);
		
		if(favArray.length == 1 && $.trim(favArray[0]).length > 0){
			nbFav = 1; 
		}else if(favArray.length > 1){
			nbFav = favArray.length;
		}
		
		$('.boutonAjouterFavoris').each(function(){
			noMembre = $(this).attr('href').replace(window.location.href,'').replace('#','');	
			var texteStr = "";
			if($.inArray(noMembre.toString(),favArray) > -1){
				texteStr = texteBoutonFavoris[langue].suppression;
			}else{
				texteStr = texteBoutonFavoris[langue].ajout;
			}
			$(this).find('.toggleText').text(texteStr);
		});
	}
	
	$('#btnVoirFavoris .nbFavoris').text(nbFav);
	
	$.nyroModalSettings({
        processHandler: function(settings) {
            var scaleRatio = 1;
            var from = settings.from;
            if (from && from.href && from.href.indexOf('http://www.youtube.com/watch?v=') == 0) {
                $.nyroModalSettings({
                    type: 'swf',
                    width: (640 * scaleRatio),
                    height: (370 * scaleRatio),
                    url: from.href.replace(new RegExp("watch\\?v=", "i"), 'v/')
                });
            }
            else if (from && from.href && from.href.indexOf('repertoireDetailsChambres') > 0) {
                var tmpBoxmodel = $.support.boxModel;
                $.support.boxModel = 0;
                $.nyroModalSettings({
                    type : 'iframe',
                    width: (720),
                    height: (600),
                    url: from.href
                });
            }
			else if (from && from.href && from.href.indexOf('banqueDImagesFlashSlimbox') > 0) {
                var tmpBoxmodel = $.support.boxModel;
				$.support.boxModel = 0;
                $.nyroModalSettings({
                    type : 'iframe',
					width:  667,
					height: 542,
					padding: 0,
                    url: from.href
                });
            }else if (from && from.href && from.href.indexOf('demandeDeDisponibiliteafficherCalendrier') > 0) {
                var tmpBoxmodel = $.support.boxModel;
                $.support.boxModel = 0;
                $.nyroModalSettings({
                    type : 'iframe',
                    width: (600),
                    minHeight: (450),
                    url: (from.href)
                });
			}else if (from && from.href && from.href.indexOf('demandeDeDisponibilitePolitiqueDeReservation') > 0) {
                var tmpBoxmodel = $.support.boxModel;
                $.support.boxModel = 0;
                $.nyroModalSettings({
                    type : 'iframe',
                    width: (500),
                    height: (500),
                    url: (from.href)
                });
            }else if (from && from.href && from.href.indexOf('gestionFavoris') > 0) {
                var tmpBoxmodel = $.support.boxModel;
                $.support.boxModel = 0;
				var baseUrl = window.location.href; 
					// IE7,IE8 mets en cache les fenetres modales, les coquins !
					var dt = new Date().getMilliseconds();
					url = from.href + '?r=' + dt;
					$.nyroModalSettings({
						endRemove : function(){
							if(typeof($.cookie('noMembreFavoris')) == 'string'){
								var splittedArray = $.cookie('noMembreFavoris').toString();
								var splittedArray = splittedArray.split(',');
								var nbFav = 0;
								if(typeof(splittedArray) == 'object' && splittedArray.length > 1){
									nbFav = splittedArray.length;
								}else if(splittedArray.length == 1 && $.trim(splittedArray[0]).length){
									nbFav = 1;
								}
							}else{
								splittedArray = new Array();
								var nbFav = 0;
							}
							$('.nbFavoris').text(nbFav);
							$('.boutonAjouterFavoris').each(function(){
								var noMembre = $(this).attr('href').replace(baseUrl,'').replace('#','');

								if($.inArray(noMembre,splittedArray) == -1){
									$(this).find('.toggleText').text(texteBoutonFavoris[langue].ajout);
								}else{
									$(this).find('.toggleText').text(texteBoutonFavoris[langue].suppression);
								}
							});
						},
						type : 'iframe',
						width: (520),
						height: (500),
						url: (url)
					});
				
			}
            else {
                var tmpBoxmodel = $.support.boxModel;
                $.support.boxModel = false;
                $.nyroModalSettings({
                    //width: (680),
                    //height: (600),
                    //url: from.href
                });
            }
        }
    });
	
	if($('#offresEmploi').length > 0){
		$('.groupeEmplois').css('display','none');
		$('#offresEmploi h2 a').click(function(){
			var elementEnCours=$(this).parent().next()
			$('.groupeEmplois').not(elementEnCours).each(function(){
				if($(this) != elementEnCours){
					$(this).slideUp(500);
					$(this).prev().find('a').attr('class','flecheBas');
				}
			})
			$(this).toggleClass('flecheBas flecheHaut')
			$(this).parent().next().stop(true,true).slideToggle(500);
			return false
		})
	}
	
	if($('#calendrierEvenementsAccordeon').length > 0){
		$('.groupeEvenements').css('display','none');
		$('#calendrierEvenementsAccordeon h2 a').click(function(){
			var elementEnCours=$(this).parent().next()
			$('.groupeEvenements').not(elementEnCours).each(function(){
				if($(this) != elementEnCours){
					$(this).slideUp(500);
					$(this).prev().find('a').attr('class','flecheBas');
				}
			})
			$(this).toggleClass('flecheBas flecheHaut')
			$(this).parent().next().stop(true,true).slideToggle(500);
			return false
		})
	}
	
	
	
	var paramChangementLangue = $('#lienChangementLangue').attr('href');
	paramChangementLangue = paramChangementLangue + (window.location.search.replace(/(\?)(.+)/ig, "&$2"));
	paramChangementLangue = paramChangementLangue.replace(/microsite=[0-9]{1,}&/g, "");

	paramChangementLangue = paramChangementLangue.replace('.cfm&','.cfm?');
	$('#lienChangementLangue').attr('href', paramChangementLangue);
	
	$('a.smoothAnchor[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
				var $target = $(this.hash);
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 1000);
					return false;
				}
			}
		});

	
	
	
	/* slideshow accueil */

//slideshow

	if($('div#slideshow').length > 0){
		var largeurMaxTitreSlideshow=0
		$('div#slideshow div.titreImage').each(function(){
			if($(this).width() > largeurMaxTitreSlideshow){
				largeurMaxTitreSlideshow=$(this).width()
			}
		})
		$('div#slideshow div.titreImage').css('width',largeurMaxTitreSlideshow+'px');
		
		var largeurMaxPagerSlideshow=0
		$('div#slideshow div.boiteNombreImages').each(function(){
			if($(this).width() > largeurMaxPagerSlideshow){
				largeurMaxPagerSlideshow=$(this).width()
			}
		})
		$('div#slideshow div.boiteNombreImages').css('width',largeurMaxPagerSlideshow+'px');
		
		
		
		var calculPositionFlecheGauche=($('#slideshowSuiv').outerWidth()+10)+($('div#slideshow div.boiteInfos:eq(0) div.titreImage').outerWidth()+5)+($('div#slideshow div.boiteInfos:eq(0) div.boiteNombreImages').outerWidth()+5)+(5)
		
		$('a#slideshowPrec').css('right',calculPositionFlecheGauche+'px');
		
		$('div#slideshow').cycle({
			type: 'fade',
			prev:   '#slideshowPrec', 
			next:   '#slideshowSuiv'
		});
		
		$('a#slideshowPrec').css('display','block');
		$('a#slideshowSuiv').css('display','block');
		
/*
		$('a#slideshowPrec').click(function(){
			$('div#slideshow').cycle('prev');return false;
		});
		$('a#slideshowSuiv').click(function(){
			$('div#slideshow').cycle('next');return false;
		});
		*/
	}
	
	/*if($('#formRechercheCarte').length>0){
		var hauteurFieldsets=0;
		$('#formRechercheCarte fieldset').each(function(){
			if($(this).height()>hauteurFieldsets){
				hauteurFieldsets=$(this).height();
			}
		})
		$('#formRechercheCarte fieldset').css('height',hauteurFieldsets+'px');
	}*/
	
});

function OuvrirBanqueDimage(categorie, panier){
	if(typeof(panier) == 'undefined'){
		panier = false; 
	}
	if(typeof(microsite) == 'undefined'){
		microsite = 4; 
	}
	var href= "banqueDImagesFlashSlimbox.cfm?categorie=" + categorie + "&panier=" + panier + "&microsite=" + microsite + "&langue=" + langue;
	$.fn.nyroModalManual({
		forceType : 'iframe',
		type : 'iframe',
		width:  667,
		height: 542,
		padding: 0,
		url: href
	});
}

function repositionnerCalendrier(input,calendar){
	var hauteurChampsTexte = (input.outerHeight());
	positionInput = $(input).position();
	calendar.css('top',(positionInput.top + hauteurChampsTexte) +'px');
	calendar.css('left',positionInput.left + 'px');
}


function compterClique(emplacement,langue){
	donnees = {
		localisation : window.location.href,
		emplacement  : emplacement,
		langue		 : langue
	};
	$.param(donnees);
	$.ajax({
			type: "post",
			async: false,
			cache: false,
			timeout: 30000,
			url : '_compterCliques.cfm',
			data : donnees
	});
	return true;
}


function unique(arrayName){
  var newArray=new Array();
  label:for(var i=0; i<arrayName.length;i++ ){
	for(var j=0; j<newArray.length;j++ ){
		if(newArray[j]==arrayName[i])
		continue label;
	}
  newArray[newArray.length] = arrayName[i];
  }
return newArray;
}



function favoriteMemberToggle(noMembre,$jQueryObject){
	var listeFavoris = $.cookie('noMembreFavoris'),
		messageBox = {};
		var obj = "";
		if(typeof(infoMarkers) != 'undefined'){
			$.each(infoMarkers, function(k,v){
				if(v.noMembre == noMembre){
					obj = v;
					return false;
				}
			});
		}
		if(listeFavoris == null){
			listeFavoris = "";
		}
		
		if(listeFavoris.length > 0){
		var splittedArray = listeFavoris.toString().split(',');
			splittedArray = unique(splittedArray);
		}else{
			splittedArray = new Array();
		}
		var $textBox = "";
		if(typeof($jQueryObject) != 'undefined'){
			var tmpHref = $jQueryObject.attr('href');
			$textBox = $('a.boutonAjouterFavoris[href=' + tmpHref + ']').find('.toggleText');
		}
		
		var texteBouton = "";
		if($.inArray(noMembre.toString(),splittedArray) == -1){
			// Ajouté
			splittedArray.push(noMembre);
			texteBouton = texteBoutonFavoris[langue].suppression;
			if(typeof(obj) == 'object'){
				messageBox = {
					title : obj.titreCategorie + ' ajouté avec succès aux favoris',
					text : obj.nomMembre + ' ajouté avec succès aux favoris'
				}
			}else{
				messageBox = {
					title : 'Ajouté avec succès aux favoris',
					text : 'Le membre sélectionné a été ajouté avec succès'
				}
			}
		}else{
			// Supprimé
			var position = $.inArray(noMembre.toString(),splittedArray);
			texteBouton = texteBoutonFavoris[langue].ajout;
			if(position > -1){
				removeByIndex(splittedArray,position);
			}
			messageBox = {
				title : 'Suppression du favoris',
				text : 'Le membre sélectionné a été supprimé avec succès'
			}
		}
		if($textBox.length > 0){
			$textBox.text(texteBouton);
		}
		
		//$.gritter.add(messageBox);
		// Cleanup
		splittedArray = unique(splittedArray);
		while($.inArray("",splittedArray) > -1){
			removeByIndex(splittedArray,$.inArray("",splittedArray));
		}
		$('.nbFavoris').text(splittedArray.length);
		// On ramasse tout ça dans un tas.
		listeFavoris = splittedArray.join(',');
		// Set le cookie.
		$.cookie('noMembreFavoris', listeFavoris);
	return false;
}


function removeByIndex(arrayName,arrayIndex){
    arrayName.splice(arrayIndex,1);
}

function isInList(value,list,delimiter){
	if(typeof(delimiter) == 'undefined'){
		delimiter = ',';
	}
	var found = false;
	if(list !== null && list.length > 0){
		list = list.toString().split(delimiter);
		$.each(list,function(k,v){
			if(value==v){
				found = true;
				return false;
			}
		});
	}
	return found;
}
