
/* Fonction qui ajoute dynamiquement un
   Target blank au a qui on on
	 l'attribut rel="external"
************************************************/


(function($){

	$(function(){
		var $body = $('body');

		$.fn.hauteurEgale = function() {
			var maxH = 0;
			$(this)
			.css( 'height', 'auto' )
			.each(function() {
				if ( $(this).height() > maxH ) {
					maxH = $(this).height();
				}
			})
			.height( maxH );
			return $(this);
		}

		$.fn.bindHauteurEgale = function() {
			var $this = $(this).hauteurEgale();
			$(document).bind("fontresize", function (event, data) {
				$this.hauteurEgale();
			});
		}

		/*
		 * @Cache les sous-menu de navigation lorsque que le JS est activé
		******************************************************************************/
		$('ul.sub-nav li:not(.active) .menu').hide();

		/*
		 * @Animation de la navigation
		******************************************************************************/
		$('ul.sub-nav > li > a').click(function() {
			if ( $(this).parent().find('.menu').length ) {
				var self = $(this);
				var $menu = self.parent().find('.menu');
				if ( !self.parent().find('.menu').is(':visible') ) {
					afficherMenu( self, $menu );

					// $menu.parent().siblings().not('.originale').each(function() {
					$menu.parent().siblings().each(function() {
						cacherMenu( $(this).children('a'), $(this).find('.menu'), true );
					});

				} else {
					cacherMenu( self, $menu );
				}
				return false;
			}
		});

		/*
		 * @section Auto-complete
		******************************************************************************/
		if($body.is('.template-fiche-livre') || $body.is('.template-listes') || $body.is('.template-catalogue')){
			$('#auteur-recherche,#catalogue-recherche').autocomplete( 'ajax.html', {
				delay: 400,
				minChars : 2,
				scroll : false,
				autoFill : false,
				highlight : false,
				width: 215,
				selectFirst: false
			});
		}

		function afficherMenu( self, $menu ) {
			$menu.hide();
			self.parent().addClass('active');
			$menu.animate({
				height: 'show'
			},{
				duration: 200,
				easing : 'easeOutCubic'
			});
		}


		function cacherMenu( self, $menu, alt ) {
			if ( alt ) {
				self.parent().removeClass('active');
			}
			$menu.animate({
				height: 'hide'
			},{
				duration: 200,
				complete: function() {

					self.parent().removeClass('active');
				},
				easing : 'easeOutCubic'
			});
		}

		if($body.is('.template-accueil')){
			/*
			 * @section Nouveauté sur la page d'accueil
			******************************************************************************/
			$('.listing-livres').each(function() {
				var compteur = 0;
				var livres = [];
				$(this).find('.liste .livre').each(function() {
					compteur++;
					livres.push(this);
					if (compteur == 5) {
						$( livres ).find('h2').bindHauteurEgale();
						compteur = 0;
						livres = [];
					}
				});
				if (compteur%5!=0) {
					$( livres ).find('h2').bindHauteurEgale();
				}
			});


			$('.listing-livres .pagination ul').show();

			jQuery.fn.pagination = function() {

				$(this).each(function() {

					var $self = $(this);
					var $numeros = $self.find('li').not('.next, .prev');
					var $fleches = $self.find('li').filter('.next, .prev');
					var $liste = $self.parent().prev().find('.liste');
					var page_actuelle = 0;
					var width = 900;
					var duration = 500;
					var $next = $fleches.filter('.next');
					var $prev = $fleches.filter('.prev');

					function update_nav() {
						if ( page_actuelle == 0 ) { $prev.addClass('prev-inactive'); }
						else { $prev.removeClass('prev-inactive'); }
						if ( page_actuelle == $numeros.length - 1 ) { $next.addClass('next-inactive'); }
						else { $next.removeClass('next-inactive'); }
					}
					update_nav();

					function aller(i) {
						page_actuelle = i;
						$numeros.eq(page_actuelle).addClass('active').siblings().removeClass('active');
						$liste.stop().animate({
							'marginLeft' : (page_actuelle * width * -1)+'px'
						},{
							duration: duration
						});
						update_nav();
					}

					function update_height( animate ) {
						var $page = $liste;

						var $groupe = $liste.find('.groupe-livre');

						var maxGroupHeight = 0;
						$groupe.each(function(){
							if($(this).height() > maxGroupHeight){
								maxGroupHeight = $(this).height();
							}
						});

						$liste.parent().height( maxGroupHeight );
						$groupe.height( maxGroupHeight );
					}
					update_height();

					$liste.bind('activate', function() {
						update_height();
					});

					$(document).bind("fontresize", function (event, data) {
						if ( $liste.is(':visible') ) {
							update_height();
						}
					});

					$numeros.find('a').click(function() {
						var index = $numeros.index( this.parentNode );
						aller( index );
						return false;
					});

					$fleches.find('a').click(function() {
						if ( $(this).parent().is('.next-inactive') || $(this).parent().is('.prev-inactive') ) { return false; }
						if ( $(this).parent().is('.next') ) { aller( page_actuelle + 1 ); }
						else { aller( page_actuelle - 1 ); }
					});

				});

				return $(this);

			}


		/*
		 * @section Tooltip des Nouveautés de l'accueil et du catalogue
		******************************************************************************/
			xOffset = 10;
			yOffset = 20;
			$("#nouveautes .livre a").hover(function(e){
				this.t = this.title;
				this.title = "";
				$("body").append("<p id='tooltip'>"+ this.t +"</p>");
				$("#tooltip")
					.css("top",(e.pageY - xOffset) + "px")
					.css("left",(e.pageX + yOffset) + "px")
					.fadeIn("fast");
		    },
				function(){
					this.title = this.t;
					$("#tooltip").remove();
		  	}
			);

			$("#nouveautes .livre a").mousemove(function(e){
				$("#tooltip")
					.css("top",(e.pageY - xOffset) + "px")
					.css("left",(e.pageX + yOffset) + "px");
			});

		}

		if($body.is('.template-catalogue') || $body.is('.template-listes') || $body.is('.template-fiche-livre')){
		/*
		 * @section Liste de sélection personnalisée
		******************************************************************************/
			$('div.select .label a').each(function(){
				if($(this).html().length > 32){
					$(this).html($.trim($(this).html().substr(0,30)) + '...');
				}
			});

			$('div.select ul').hide();
			$('div.select .label a').click(function(e) {
				$(this).parent().next().slideToggle(100);
				e.stopPropagation();
				e.preventDefault();
				return false;
			});

			$(document).click(function() {
				var $ul = $('div.select ul');
				if ( $ul.is(':visible') ) {
					$ul.slideUp(100);
				}
			});

		}
		
	/*	if($body.is('.template-fiche-livre')){
	//		console.log($(".ebook-link-not-found"));
								if($("li.feuilleteur div.ebook-link-not-found").length>0){
									$(".feuilleteur").hide();
								}
			}*/
			
			if($body.is('.template-fiche-livre')){
				// pour chaque liste, on affiche 3 liens, le reste est caché
				$(".revendeurs").each(function(){
						if($(this).children("li").length>4){
							var i = 0;
							$(this).children("li").each(function(){
													i++;
											if(i>4){
												$(this).hide();
											}
								});
							// afficher
							$(".lien-plus").show();
							$(".lien-plus").click(function(){
												$(this).parent().children("li:hidden").fadeIn();																									
												$(this).hide();																					
							});
						}
				});
					
			}
			
			
		
		
		if($body.is('.template-fiche-livre') || $body.is('.template-fiche-auteur')){

			$('.couverture a').click(function() {
				var couverture = new Image;
				var $this = $(this);
				var $contenu = $(this).parents('#fiche-livre');
				var largeur = $(this).find('img').width();
				var hauteur = $(this).find('img').height();
				couverture.onload = function() {
					couverture.onload = false;
					var l_largeur = couverture.width; var l_hauteur = couverture.height;
					$contenu.find('.couverture-large').remove();
					$contenu.append('<div style="display: none;" class="couverture-large"><img src="'+$this.attr('href')+'" alt="" /></div>').find('.couverture-large img').click(function() {
						$(this).stop().animate({
							width: largeur,
							height: hauteur
						},{
							duration: 300,
							easing: 'easeOutCirc',
							complete : function() {
								$(this).parent().remove();
							}
						});
					});
					$contenu.find('.couverture-large img').css('width', largeur+'px').css('height', hauteur+'px').parent().show().find('img').stop().animate({
						width: l_largeur,
						height: l_hauteur
					},{
						duration: 300,
						easing: 'easeOutCirc'
					});


				};
				couverture.src = $this.attr('href');
				return false;
			});


			$('.nav-resultat a').each(function() {
				var meta = $.metadata.get(this);
				if (meta && meta.vignette) {
					$(this).attr('title', '<img src="'+meta.vignette+'" />');
				}
			}).tooltip({
				delay : 0,
				track: true,
				showURL : false
			});


			$('body.template-fiche-livre a.envoyer').click(function(e) {
				ixbox.toggle('envoyer');
			});

			$('#fiche-livre a.collaborateur').click(function(e) {
				ixbox.toggle('collaborateur');
			});

			var ixbox = {
				init : function() {
					$('.form-overlay .fermer').click(function() {
						ixbox.toggle($(this).parent().parent().attr('id'));
					})
					$('#overlay').css('opacity', 0.8);
					$('.form-overlay').find('.loading, .confirmation, .form-erreur').hide();
					$('#envoyer form').submit(function() {

						$(this).find('input, textarea').removeClass('erreur');
						var valide = true;

						var auteur_nom 				= $('#auteur-nom').val();
						var auteur_courriel 		= $('#auteur-courriel').val();
						var destinataire_nom 		= $('#destinataire-nom').val();
						var destinataire_courriel 	= $('#destinataire-courriel').val();
						var commentaires 			= $('#commentaires').val();
						var idProduit 				= $('#idProduit').val();

						if (auteur_nom == "") {
							$('#auteur-nom').addClass('erreur');
							valide = false;
						}

						if (!auteur_courriel.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
							$('#auteur-courriel').addClass('erreur');
							valide = false;
						}

						if (destinataire_nom == "") {
							$('#destinataire-nom').addClass('erreur');
							valide = false;
						}

						if (!destinataire_courriel.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
							$('#destinataire-courriel').addClass('erreur');
							valide = false;
						}

						if (valide === true) {
							$(this).find('.champs, .confirmation').hide().parent().find('.loading').show();

							// Envoi du courriel!
							$.ajax({
								type: 'POST',
								url : $('#envoyer form').attr('action'),
								data : {
									'auteur-nom' : auteur_nom,
									'auteur-courriel' : auteur_courriel,
									'destinataire-nom' : destinataire_nom,
									'destinataire-courriel' : destinataire_courriel,
									'commentaires' : commentaires,
									'idProduit' : idProduit
								},
								success : function(data) {
									// Affichage de confirmation
									if (parseInt(data) == 1) {
										$('#envoyer form').find('.confirmation').show().parent().find('.loading, .champs').hide();
									} else {
										$('#envoyer form').find('.form-erreur').show().parent().find('.loading, .champs').hide();
									}
								}
							})
						}
						return false;
					})

				},
				toggle : function(id, callback) {
					$overlay = $('#overlay');
					$overlay.bgiframe();
					$form = $('#'+id);
					if ($overlay.is(':animated')) {
						$overlay.stop();
					}
					if ($overlay.is(':visible')) {
						$overlay.fadeOut(400, function() {
							if (callback) {
								callback();
							}
						});
						$form.slideUp();
						$form.find('input[name=c]').val('');
						$form.find('input, textarea').val("").removeClass('erreur');
						$form.find('.loading, .confirmation, .form-erreur').hide().parent().find('.champs').show();
					} else {

						if ($.browser.msie && $.browser.version <= 6) {
							window.scrollTo(0,1);
						}
						$form.css('top', (100+$(window).scrollTop())+'px');
						$form.slideDown(600, function() {
							if (callback) {
								callback()
							}
						});

						$overlay.fadeIn();
					}
				}

			};
			ixbox.init();

		}

		/*
		 * @section Fiche d'un auteur
		******************************************************************************/
		if($body.is('.template-catalogue') && $('#details .photo').length > 0){
			$('#details .content').css({'width':'540px'})
		}

		/*
		 * @section Champs de recherche
		******************************************************************************/
		$('.champ-recherche input').not('.plein').focus(function() {
			var meta = $.metadata.get(this);
			if (meta && meta.libele) {
				if ( $(this).val() == meta.libele ) {
					$(this).val( '' );
				}
			}

		}).blur( function() {
			var meta = $.metadata.get(this);
			if (meta && meta.libele) {
				if ( $(this).val() == '' ) {
					$(this).val( meta.libele );
				}
			}
		});

		// Liens externes
		$('a[href^=http://]').not('a[href*='+window.location.host+']').not('a[href*='+PUQ_URL+']').addClass('externe').attr('target','_blank');

		/*
		 * @section Fiche d'un auteur
		******************************************************************************/
		if($('#recherche-avancer #choix-lettre').length < 1){
			$('#recherche-avancer').css({'height':'46px','border-bottom':'solid 1px #DEDFE0'});
		}

	});

	$(window).load(function() {
		var $body = $('body');
		if($body.is('.template-accueil')){
			var $self = $('.listing-livres .pagination ul');
			var $liste = $self.parent().prev().find('.liste');
			var $page = $liste.find('.groupe-livre').eq( 0 );
			$liste.parent().height( $page.height() );

			$('.listing-livres .pagination ul').pagination();
			$('.listing-livres').eq(1).siblings().hide();
		}

		if($body.is('.template-catalogue')){
			$('.groupe-livre').each(function(i){
				livres = $('.groupe-livre:eq(' + i + ') .wrap');
				var plusGrand = 0;
				livres.each(function() {
					var thisHeight = $(this).height();
					if(thisHeight > plusGrand) {
						plusGrand = thisHeight;
					}
				});
				livres.height(plusGrand);
			});
		}
		/* Abonnement à l'infolettre */ 
			var nomsChamps = new Array("Votre nom","Votre courriel");
			$("#abonnement-infolettre").click(function(){
							if($("#abonnement-infolettre-form:visible").length>0){
								$("#abonnement-infolettre-form").fadeOut();
									$(this).removeClass("actif");		
							}
							else{
									$(this).addClass("actif");		
									$("#abonnement-infolettre-form").fadeIn();
							}
			});

			$("#nom-infolettre").focus(function(){
						if($(this).val()==nomsChamps[0]){
							$(this).val("");
						}
			});
			$("#nom-infolettre").focusout(function(){
						if($(this).val()==""){
							$(this).val(nomsChamps[0]);
						}
			});
			$("#courriel-infolettre").focus(function(){
					if($(this).val()==nomsChamps[1]){
							$(this).val("");
						}																																		
			});
			$("#courriel-infolettre").focusout(function(){
						if($(this).val()==""){
							$(this).val(nomsChamps[1]);
						}
			});
	});

})(jQuery);

