/*
 Interfaçage javascript global
 conception Agence Cosmic Communication 2009 (www.agencecosmic.com)
 Dernière mise �  jour : 9 avril 2009
 Version 1.15
*/
var isIE = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 8);

/* Detect if navigator supports min-height */
(function($) {
	$.extend($.support, {
		minHeight : function() {
			var id = "minheightsupport" + (new Date).getTime();
			$("<div></div>").attr("id",id)
			.css({
				height : "1px",
				minHeight : "2px",
				overflow : "hidden",
				border : "none",
				padding : "0",
				margin : "0"
			})
			.appendTo("body");
			var iscorrectheight = document.getElementById(id).offsetHeight==2;
			$("#"+id).remove();
			return iscorrectheight;
		}
	});
})(jQuery);

/*
	Plugin clearHighlight par Olivier Gorzalka
	Plugin permettant de mettre en valeur un terme
	Dernière mise �  jour : 6 mai 2009
	Mise-� -jour de Sunny Ripert : 26 mai 2009 (ajout de $(this).each)
	@param {searchTerm} terme �  rechercher
	@param {insensitive} sensible �  la casse ou non
	@param {classHighlight} classe de l'élément �  mettre en valeur
	@param {tagHighlight} balise �  utiliser pour l'élement �  mettre en valeur
*/

(function($) {
	$.fn.extend({
		clearHighlight: function(opts){
			$(this).each(function() {
				opts = $.extend({
					searchTerm:null,
					insensitive:true,
					classHighlight:'highlight',
					tagHighlight:'strong'
				},opts||{});

				function r(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
				var patternSearch = new RegExp("(<[^>]*>)|(\\b"+ opts.searchTerm.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", opts.insensitive ? "ig" : "g");
					return this.html(this.html().replace(patternSearch, function(a, b, c){
						return (a.charAt(0) == "<") ? a : "<"+opts.tagHighlight+" class=\""+ r(opts.classHighlight) +"\">" + c + "</"+opts.tagHighlight+">";
					}
				));
			})
		}
	});
})(jQuery);

/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
(function($) {
jQuery.fn.pagination = function(maxentries, opts){
	opts = jQuery.extend({
		items_per_page:10,
		num_display_entries:10,
		current_page:0,
		num_edge_entries:0,
		link_to:"#",
		prev_text:"Prev",
		next_text:"Next",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		callback:function(){return false;}
	},opts||{});

	return this.each(function() {
		/**
		 * Calculate the maximum number of pages
		 */
		function numPages() {
			return Math.ceil(maxentries/opts.items_per_page);
		}

		/**
		 * Calculate start and end point of pagination links depending on
		 * current_page and num_display_entries.
		 * @return {Array}
		 */
		function getInterval()  {
			var ne_half = Math.ceil(opts.num_display_entries/2);
			var np = numPages();
			var upper_limit = np-opts.num_display_entries;
			var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
			var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
			return [start,end];
		}

		/**
		 * This is the event handling function for the pagination links.
		 * @param {int} page_id The new page number
		 */
		function pageSelected(page_id, evt){
			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}

		/**
		 * This function inserts the pagination links into the container element
		 */
		function drawLinks() {
			panel.empty();
			var interval = getInterval();
			var np = numPages();
			// This helper function returns a handler function that calls pageSelected with the right page_id
			var getClickHandler = function(page_id) {
				return function(evt){ return pageSelected(page_id,evt); }
			}
			// Helper function for generating a single link (or a span tag if it's the current page)
			var appendItem = function(page_id, appendopts){
				page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
				appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
				if(page_id == current_page){
					var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
				}
				else
				{
					var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
						.bind("click", getClickHandler(page_id))
						.attr('href', opts.link_to.replace(/__id__/,page_id));


				}
				if(appendopts.classes){lnk.addClass(appendopts.classes);}
				panel.append(lnk);
			}
			// Generate "Previous"-Link
			if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
				appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
			}
			// Generate starting points
			if (interval[0] > 0 && opts.num_edge_entries > 0)
			{
				var end = Math.min(opts.num_edge_entries, interval[0]);
				for(var i=0; i<end; i++) {
					appendItem(i);
				}
				if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
			}
			// Generate interval links
			for(var i=interval[0]; i<interval[1]; i++) {
				appendItem(i);
			}
			// Generate ending points
			if (interval[1] < np && opts.num_edge_entries > 0)
			{
				if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
				var begin = Math.max(np-opts.num_edge_entries, interval[1]);
				for(var i=begin; i<np; i++) {
					appendItem(i);
				}

			}
			// Generate "Next"-Link
			if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
				appendItem(current_page+1,{text:opts.next_text, classes:"next"});
			}
		}

		// Extract current_page from options
		var current_page = opts.current_page;
		// Create a sane value for maxentries and items_per_page
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
		// Store DOM element for easy access from all inner functions
		var panel = jQuery(this);
		// Attach control functions to the DOM element
		this.selectPage = function(page_id){ pageSelected(page_id);}
		this.prevPage = function(){
			if (current_page > 0) {
				pageSelected(current_page - 1);
				return true;
			}
			else {
				return false;
			}
		}
		this.nextPage = function(){
			if(current_page < numPages()-1) {
				pageSelected(current_page+1);
				return true;
			}
			else {
				return false;
			}
		}
		// When all initialisation is done, draw the links
		drawLinks();
        // call callback function
        opts.callback(current_page, this);
	});
}
})(jQuery);

/**
 * Equal Heights Plugin
 * Equalize the heights of elements. Great for columns or any elements
 * that need to be the same size (floats, etc).
 *
 * Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
 * Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
 * Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
 * than 300 pixels tall. Elements with too much content will gain a scrollbar.
 *
 */

(function($) {
  $.fn.equalHeights = function(minHeight, maxHeight) {
    var tallest = (minHeight) ? minHeight : 0;

    function addSize(elem,baseHeight,operation) {
      var border_top = parseInt(elem.css('border-top-width'));
      var border_bottom = parseInt(elem.css('border-bottom-width'));
      var padding_top = parseInt(elem.css('padding-top'));
      var padding_bottom = parseInt(elem.css('padding-bottom'));
      if (operation == 'subtract') {
        if (!isNaN(padding_top)) baseHeight -= padding_top;
        if (!isNaN(padding_bottom)) baseHeight -= padding_bottom;
        if (!isNaN(border_top)) baseHeight -= border_top;
        if (!isNaN(border_bottom)) baseHeight -= border_bottom;
      } else {
        if (!isNaN(padding_top)) baseHeight += padding_top;
        if (!isNaN(padding_bottom)) baseHeight += padding_bottom;
        if (!isNaN(border_top)) baseHeight += border_top;
        if (!isNaN(border_bottom)) baseHeight += border_bottom;
      }
      return baseHeight;
    }

    var cpt = 0;
    var lastParentId;
    var tallestList = new Array();
    // add id to parent of elements to equalize
    this.each(function() {
      cpt++;
      $(this).parents('.largeblock').attr('id','productdetails_bloc'+cpt);
    });
    cpt = 0;
    this.each(function() {
      var parentId = $(this).parents('.largeblock').attr('id'); // get id of parent
      if(parentId != lastParentId) tallest = 0; // init tallest var if parent has changed (= elements are in another block)
      var height = $(this).height();
      height = addSize($(this),height);
      tallest = (height > tallest) ? height : tallest;
      tallestList[parentId] = tallest; // get all tallest heights into tallestList for each set of elements
      cpt++;
      lastParentId = parentId; // saving parent id for use in next iteration
    });
    if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
    return this.each(function() {
      var parentId = $(this).parents('.largeblock').attr('id');
      if(maxHeight)
        tallest2 = addSize($(this),tallest,'subtract');
      else
        tallest2 = addSize($(this),tallestList[parentId],'subtract');
      $(this).height(tallest2);
    });
  }
})(jQuery);


/*
	Plugin gérant le menu accordéon
	Dernière mise �  jour : 9 avril 2009
*/

var newPos = 0;
(function($) {
	$.fn.extend({
		accordionMenu: function (options) {
			// Default options
			var settings = {
				hideOnLoad:true, // cacher tout les items au chargement de la page?
				classActiveMenu:'.active', // classe des menus actifs
				showActiveMenu:true, // ouvrir le sous menu actif
				alwaysShowActive:false, // laisser l'item actif toujours ouvert
				allowToggleOpened:true // permet de refermer un item qui vient d'être ouvert
			};
			if(options) $.extend(settings, options);
			var $this = $(this);
			if (settings.hideOnLoad == true || (settings.hideOnLoad == 'trueIfNoActive')) { $this.find('li ul li:not('+settings.classActiveMenu+')').parent('ul').hide(); }
			if (settings.showActiveMenu == true) { $this.find('li ul:has('+settings.classActiveMenu+')').show().parent('li').addClass('opened'); }

			var heightMenuBefore,positionFocus; // variable uniquement pour le cas particulier Thermor

			$this.find('li:has(ul) > strong').addClass('toggleElem').click(function(i,item){
				heightMenuBefore = $('#menu').height();  // variable uniquement pour le cas particulier Thermor

				 // variable uniquement pour le cas particulier Thermor
				if (newPos) { positionFocus = newPos; }
				else { positionFocus = parseInt($('#sidebar .focus').css('top')); }


				if (settings.alwaysShowActive= true) {
					$this.find('li:has(ul) strong').not($(this)).parent('li').not(':has('+settings.classActiveMenu+')').removeClass('opened').find('ul').slideUp();
				} else {
					$this.find('li:has(ul) strong').not($(this)).parent('li').removeClass('opened').find('ul').slideUp();
				}
				if ($(this).parent('li').hasClass('opened') && settings.allowToggleOpened) {
					$(this).parent('li').removeClass('opened').find('ul').slideUp(function() {
						newPos = positionFocus+(heightMenuBefore-$('#menu').height());  // variable uniquement pour le cas particulier Thermor
					});
				} else {
					$(this).parent('li').addClass('opened').find('ul').slideDown(function() {
						newPos = positionFocus+(heightMenuBefore-$('#menu').height());  // variable uniquement pour le cas particulier Thermor
					});
				}
			})

		}
	});
})(jQuery);

/*
	clearScroll plugin for jQuery
	parameters: @speed:500 > vitesse de l'animation
					@offset > offset par défaut
					@container > id du parent
					@delay > delai avant de lancer l'animation
*/

(function($) {
	$.fn.extend({
		clearScroll: function (options) {
			var settings = {
				speed:500, // vitesse de l'animation
				offset:0, // offset par défaut
				container: this.parent().attr( 'id' ), // id du parent
				delay:0 // delai avant de lancer l'animation
			};
			if(options) $.extend(settings, options);

			var $this = $(this); // l'élement �  bouger

			$this.css('position','relative'); // on lui applique une position relative
			function animateBlock() {
				$this.queue( [ ] ); // afin d'éviter les animations superflues (scroll multiple)

				// Calcul de position sur les différents élements �  prendre en compte (hauteur de la fenêtre, le blocn etc...)
				var windowHeight = parseInt( $(window).height() ); // dimension de la page
				var scrollPage =  parseInt( $(document).scrollTop() ); // position de la page lors du scroll
				var parentOffsetTop =  parseInt( $containerBlock.offset().top ); // position du bloc par rapport au haut de la page
				var parentHeight = parseInt( $containerBlock.height() ); // on récupère l'offset du parent conteneur du bloc
				var blockHeight = parseInt( $this.height() + ( parseInt( $this.css('marginTop') ) || 0 ) + ( parseInt( $this.css('marginBottom') ) || 0 ) );
				var movementTop;

				// seulement si l'animation doit être lancée
				if ( isAnimated ) {
					// On anime pas tant que le haut de la fenêtre n'est pas proche du haut du bloc
					if ( $this.defaultOffsetTop >= ( scrollPage + settings.offset ) ) {
						movementTop = $this.defaultPosTop;
					} else {
						movementTop = Math.min((Math.max((-parentOffsetTop),(scrollPage-$this.defaultOffsetTop+$this.defaultPosTop))+settings.offset),(parentHeight-blockHeight-$this.paddingAdjustment));
					}

					// On vérifie que le scroll �  effectuer est bien le dernier. -20 permet de signifier que le timeout n'est pas correct
					// top: movementTop+newPos > variable uniquement pour le cas particulier Thermor (sinon, pour un plugin générique, utiliser top: movementTop)
					if ( ( new Date().getTime() - $this.lastAnimation ) >= ( settings.delay - 20 ) ) {
						if (movementTop+newPos < 0) { tempMovementTop = 0; }
						else { tempMovementTop = movementTop+newPos; }
						$this.animate({ top: tempMovementTop }, settings.speed);
					}
				}
			};

			// initialise le processus d'animation �  "vrai"
			var isAnimated = true;

			// Si aucun parent n'a été spécifié et si le parent du bloc n'a pas d'id, un id doit être défini
			if ( settings.container == '') {
				$containerBlock = $this.parent();
			} else {
				$containerBlock = $('#'+settings.container);
			}

			// Récupère le positionnement par défaut du bloc
			$this.defaultOffsetTop =  parseInt( $this.offset().top ); // valeur de l'offset du bloc initiale
			$this.defaultPosTop = parseInt( $this.css( 'top' ) ) || 0; // valeur relative du positionnement du bloc initiale

			// On ajuste le positionnement en fonction des padding
			$this.paddingAdjustment = parseInt( $containerBlock.css('paddingTop') ) + parseInt( $containerBlock.css('paddingBottom') );

			// Anime le bloc lorsque la page est redimensionnée ou scrollée
			$(window).bind("resize scroll", function() {
				// On lance l'animation
				$.fn.clearScroll.interval = setTimeout( function(){ animateBlock(); } , settings.delay );

				// Met �  jour le moment ou le dernier scroll a été effectué
				$this.lastAnimation = new Date().getTime();
			});

			// Lance l'animation au premier chargement de la page
			$this.lastAnimation = 0;
			animateBlock();

		}
	});
})(jQuery);


/*
	tabGenerator plugin for jQuery
	created by Cosmic Communication
	parameters: @separator : element which define the différent panels of content
					             a header tag (h2,h3,hr) can be choosen as delimiter > a div wraps each section beginning by this tag
	            @navigation : element which contains the tabs
*/

(function($) {
	$.fn.tabGenerator = function(options) {
		// Default options
		var settings = {
			separator : 'h4', // separator
			navigation: '.nav', // tab links class or id
			tabClassName: '.tabApplied',
			desactivateHash: false
		};
		if(options) $.extend(settings, options);
		function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
		// Element to exclude from the creation of wrapper div
		var arr = [ 'div' , 'dl' , 'ul' , 'li' ];

		$(this).addClass(c(settings.tabClassName));
		return $(this).each(function(i, elem) {
			// if object exists
			if ($(elem).length) {
				// initialize variables
				var div = false;
				var linkNavigTab = new Array();
				var idConteneur = null;
				var createWrappers = null;
				if (jQuery.inArray(options.separator, arr) < 0) {
					createWrappers = true
				}

				var wrapperElement = options.separator;
				/* Each elements delimited by the
				 separator is wrapped by a div */

				// if element is not in the exclusion list to wrap with a div
				if (createWrappers) {
					$(elem).children().each(function(){
						if( $(this).is(options.separator) ){
							div = document.createElement("div");
							$(div).insertBefore(this);
							$(div).append(this);
							return;
						}
						if( div != false ){ $(div).append(this); }
					});
					wrapperElement = 'div';
				}

				/* Id attribute of each created div */
				var parentElement = $(elem).find(wrapperElement).not(options.navigation);
				if (wrapperElement == 'li' && $(elem).find('ul').length == 2) {
					parentElement = $(elem).find('ul:eq(1)').find(wrapperElement+':parent').not(options.navigation);
				}

				parentElement.each(function(i,item) {
					var idConteneur;
					if (createWrappers) {
						idConteneur = $(this).find(options.separator).attr('id');
						if (idConteneur != undefined) {
							$(this).attr('id',idConteneur+'_wrapper').addClass('panel').hide();
							idConteneur = $(this).find(options.separator).attr('id',idConteneur+'_title');
						}
					} else {
						idConteneur = $(this).attr('id');
						if (idConteneur != undefined) { $(this).eq(0).attr('id',idConteneur+'_wrapper').addClass('panel').hide(); }
					}
				})
				var optionHeight;
				var thisHeight = 0;
				var baseHeight = 0;
				$(this).find('.panel').each(function() {
					thisHeight = $(this).height();
					if (thisHeight >= baseHeight) { baseHeight = thisHeight; }
				});
        heightContainer = 0;
				//heightContainer = baseHeight+$(settings.navigation).height();

				if ($.support.minHeight()) { optionHeight = {minHeight:heightContainer} }
				else { optionHeight = {height:heightContainer} }
				$(this).css(optionHeight)

				/* If a url hash is present in the URL */

				if (window.location.hash) {
					var offsetElem = $(settings.tabClassName).offset().top
					var navigTabHash = window.location.hash; // hash variable
					if ($(elem).find(navigTabHash+'_wrapper').length) {
						$(elem).find(navigTabHash+'_wrapper').show(); // show !!!
						$(elem).find("a[href$='"+navigTabHash+"']").parent('li').addClass('active'); // give the 'active' class to the active tab
					}
					// else we show the first element
					else {
						$(elem).find('.panel:first').show(); // show !!!
						$(elem).find(options.navigation).find('li:first').addClass('active'); // give the 'active' class to the first tab
					}
				} else {
					$(elem).find('.panel:first')
						.css('position','absolute') // to fix some IE Bug (background-image not shown)
						.css('position','static')
					.show();
					$(elem).find(settings.navigation).find('li:first').addClass('active');
				}

				// when the user click on a tab
				$(options.navigation).bind('click', function(e) {
					var $target;
					if($(e.target).is(options.navigation+' li')) {
						$target = $(e.target).find('a');
					} else {
						$target = $(e.target).parent().find('a');
					}

					if ($target.is("a[href*='#']")) {
						if ($target.parent('li').hasClass('active')) { return; }
						$(options.navigation).find("a").parent('li.active').removeClass('active'); // remove the 'active' class
						$target.parent('li').addClass('active'); // give the 'active' class to the active tab
						var hashValue = $target.attr("href"); // 'href' attribute of the clicked tab
						var lengthHref = $target.attr("href").length; // size of the url
						var checkhashValue = hashValue.lastIndexOf('#'); // search for the last # in the url
						if (checkhashValue > -1) {
							var targetHash = hashValue.substr(checkhashValue,lengthHref); // give the real hash value
							if ($(elem).find(targetHash)) {
								$(elem).find('.panel:visible').hide(); // hide the previous panel
								$(elem).find(targetHash+'_wrapper').fadeIn()
								.css('position','absolute') // to fix some IE Bug (background-image not shown)
								.css('position','static'); // show the called panel by the tab link
								if (settings.desactivateHash) {
									return false;
								}
							}
						}
					}
				});
			}
		});
	}
})(jQuery);

/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
*
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);



/*
	Plugin clearAccordion par Olivier Gorzalka
	Permet d'ins�rer un accord�on horizontal
	Derni�re mise � jour : 6 avril 2009
*/
(function($) {
	$.fn.extend({
		clearAccordion: function (options) {
			// Default options
			var settings = {
				panelTag:'div', // balise des panneaux d�filants
				clickZone:'a', // zone cliquable pour d�filer les panneaux
				panelWidth:null, // taille du panneau d�filant
				clickWidth:null, // taille de la zone cliquable
				correctLengthSlide:0, // correction eventuelle de la longueur du chemin � parcourir
				timing:500 // vitesse de l'animation
			};
			if(options) $.extend(settings, options);
			var actualpos,newpos,newposPrev,id,actualid,idNext,idPrev;
			var pos = new Array();

			var $this = $(this);
			var containerWidth = $this.width();
			var posFirstElem = parseInt($this.find(settings.panelTag).eq(0).css('left'));

			if (!settings.clickWidth) { settings.clickWidth = $(this).find(settings.clickZone).eq(0).width(); }
			if (!settings.panelWidth) {
				settings.panelWidth = (containerWidth)-(($(this).find(settings.clickZone).length-1)*((settings.clickWidth)-settings.correctLengthSlide)-settings.correctLengthSlide);
				$this.find(settings.panelTag).width(settings.panelWidth);
			}


			$this.find(settings.panelTag).each(function(i,item) {
				if (i == 0) {
					$(item).css({'left':settings.correctLengthSlide, zIndex:i});
				} else if (i == 1) {
					$(item).css({'left':settings.panelWidth, zIndex:i});
				} else {
					$(item).css({'left':parseInt($(this).prev(settings.panelTag).css('left'))+(settings.clickWidth)-settings.correctLengthSlide, zIndex:i});
				}
			});
			var lengthSlide = parseInt(settings.panelWidth)-parseInt(settings.clickWidth);
			var widthImgZone = lengthSlide-parseInt(settings.correctLengthSlide);

			$this.find(settings.panelTag+' :not('+settings.clickZone+')').wrap('<div style="width:'+widthImgZone+'; overflow:hidden" class="insidepanel"/>');
       	$this.find(settings.panelTag).eq(0).addClass('movedPanel').nextAll(settings.panelTag).addClass('movedRight');

			// �v�nement onclick
			$this.addClass('clearAccordion').find(settings.clickZone).click(function() {

				$this.find('.movedPanel').removeClass('movedPanel');
				$(this).parent(settings.panelTag).addClass('movedPanel');
				thisPosLeft = parseInt($(this).parent(settings.panelTag).css('left'))-lengthSlide;
				actualpos = parseInt($(this).parent(settings.panelTag).css('left'));

				if (actualpos != posFirstElem && thisPosLeft >= settings.clickWidth) {
					$(this).parent(settings.panelTag).animate({
						left:thisPosLeft
					},settings.timing);
				}

				$(this).parent(settings.panelTag).prevAll(settings.panelTag).addClass('movedLeft').removeClass('movedRight').each(function() {
					newposPrev = parseInt($(this).css('left'))-lengthSlide;
					if (newposPrev > 0) {
						idPrev = $(this).attr('id');
						$(this).animate({
							left:newposPrev
						},settings.timing);
					}
				});

				$(this).parent(settings.panelTag).nextAll(settings.panelTag).addClass('movedRight').removeClass('movedLeft').each(function() {
					testWidth = containerWidth+parseInt(settings.clickWidth);
					var leftPosition = parseInt($(this).css('left'))+lengthSlide;
					if ( testWidth > leftPosition) {
						$(this).animate({
						left:leftPosition
						},settings.timing);
					}
				});
			});
		}
	});
})(jQuery);


/*
	Plugin ClearCarousel par Olivier Gorzalka
	permet de créer un caroussel
	Dernière mise �  jour : 6 avril 2009
*/
(function($) {
	$.fn.extend({
		clearCarousel: function (options) {
			// Default options
			var settings = {
				insideContainer:'ul', // conteneur de la liste des panneaux �  défiler
				panelTag:'li', // balise des différents panneaux
				nextBtn:'.nextitem', // selecteur suivant
				prevBtn:'.previousitem', // selecteur précédent
				classInsideWrapper:'.wrappernavigation', // classe du conteneur ajouté en javascript
				nbrToShow:5, // nbre de diapo �  afficher par défaut
				timing:500, // vitesse de l'animation
				activeBtnCss: {
					'cursor':'pointer',
					opacity:1
				},
				inactiveBtnCss: {
					'cursor':'default',
					opacity:0.5
				}
			};
			if(options) $.extend(settings, options);

			var widthElem;
			var page = 0;
			var baseWidth = 0;

			function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector

			var $this = $(this);
			$this.addClass('clearCarousel');
			var $container =  $this.find(settings.insideContainer);
			var $screens = $container.find(settings.panelTag);
			var totalScreen = $screens.length;
			if (totalScreen <= settings.nbrToShow) { $(settings.nextBtn+','+settings.prevBtn).css('display','none'); } else {
				$(settings.prevBtn).css(settings.inactiveBtnCss);
			}

			function nextPrevSlide(sense) {
				if(sense=='next') {
					$(settings.prevBtn).css(settings.activeBtnCss);
					if (page+settings.nbrToShow != totalScreen) {
						page++;
						//if (page+page)
						var movementNext = $container.offset().left - $screens.eq(page).offset().left;
						$container.stop().animate({
							'left':movementNext
						},settings.timing,function() {
							if (page+settings.nbrToShow == totalScreen) { $(settings.nextBtn).css(settings.inactiveBtnCss); }
							else { $(settings.nextBtn).css(settings.activeBtnCss); }
						});
					}
				} else {
					if (page != 0) {
						page--
						$(settings.nextBtn).css(settings.activeBtnCss);
						var movementPrevious = $container.offset().left - $screens.eq(page).offset().left;
						$container.stop().animate({
							'left':movementPrevious
						},settings.timing,function() {
							if (page == 0) { $(settings.prevBtn).css(settings.inactiveBtnCss); }
							else { $(settings.prevBtn).css(settings.activeBtnCss); }
						})
					}
				}
			}

			$screens.each(function() {
				var border_left = parseInt($(this).css('border-left-width'));
				var border_right = parseInt($(this).css('border-right-width'));
				var padding_left = parseInt($(this).css('padding-left'));
				var padding_right = parseInt($(this).css('padding-right'));
				var margin_left = parseInt($(this).css('margin-left'));
				var margin_right = parseInt($(this).css('margin-right'));
				widthElem = $(this).width();
				if (!isNaN(margin_left)) widthElem += margin_left;
				if (!isNaN(margin_right)) widthElem += margin_right;
				if (!isNaN(padding_left)) widthElem += padding_left;
				if (!isNaN(padding_right)) widthElem += padding_right;
				if (!isNaN(border_left)) widthElem += border_left;
				if (!isNaN(border_right)) widthElem += border_right;
				baseWidth += widthElem;
			});

			$container.wrap('<div class="'+c(settings.classInsideWrapper)+'"></div>')

			$(settings.classInsideWrapper)
				.css('overflow','hidden')
				.find(settings.insideContainer).css({
				'width':baseWidth
				});

			$(settings.nextBtn).click(function() { nextPrevSlide('next'); });
			$(settings.prevBtn).click(function() { nextPrevSlide('previous'); });

			$(window).load(function() {
        var highestElem = 0;
				var highestContainer = 0;
				$screens.each(function() {
					var border_top = parseInt($(this).css('border-top-width'));
					var border_bottom = parseInt($(this).css('border-bottom-width'));
					var padding_top = parseInt($(this).css('padding-top'));
					var padding_bottom = parseInt($(this).css('padding-bottom'));
					var margin_top = parseInt($(this).css('margin-top'));
					var margin_bottom = parseInt($(this).css('margin-bottom'));
					var heightElem = $(this).height();
					if (!isNaN(padding_bottom)) heightElem += padding_top;
					if (!isNaN(padding_top)) heightElem += padding_top;
					if (!isNaN(border_top)) heightElem += border_top;
					if (!isNaN(border_bottom)) heightElem += border_bottom;

					var heightContainer = heightElem;
					if (!isNaN(margin_bottom)) heightContainer += margin_bottom;
					if (!isNaN(margin_top)) heightContainer += margin_top;

					if (heightContainer > highestContainer)
						highestContainer = heightContainer;

          if (heightElem > highestElem)
						highestElem = heightElem;

				});
        $screens.css('height', highestElem);
				$this.find(settings.classInsideWrapper).css('height', highestContainer <= 0 ? 100 : highestContainer);
			});
		}
	});
})(jQuery);


/*
	Plugin addPrintLink par Olivier Gorzalka
	Permet d'insérer un lien Imprimer cette page et de lui attribuer l'action d'impression de page
	Dernière mise �  jour : 6 avril 2009
*/
(function($) {
	$.fn.extend({
		addPrintLink: function (options) {
			// Default options
			var settings = {
				txt:'Imprimer cette page', // text �  afficher
				tag:'p', // balise du conteneur du lien
				className:'print', // classe du conteneur du lien
				mode:'appendTo' // mode d'insertion (insertBefore, insertAfter, appendTo)
			};
			if(options) $.extend(settings, options);
			function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector

			var htmlPrintLink = '<'+settings.tag+' class="'+c(settings.className)+'">';
			htmlPrintLink += '<a href="#print" title="'+settings.txt+'">'+settings.txt+'</a>'
			htmlPrintLink += '</'+settings.tag+'>';

			if (settings.mode == 'appendTo') { $(htmlPrintLink).appendTo($(this)); }
			else if (settings.mode == 'insertBefore') { $(htmlPrintLink).insertBefore($(this)); }
			else if (settings.mode == 'insertAfter') { $(htmlPrintLink).insertBefore($(this)); }

			$(settings.className).click(function() { window.print(); });
		}
	});
})(jQuery);








var newsNum = 0; // position du pointeur
// total de news

function nextNews(totalNews) {
	var totalNews = $('.focus div div:parent').length-1;
	if (newsNum == totalNews) {
		newsNum = 0;
		previousNews = totalNews;
	} else {
		newsNum++;
		previousNews = newsNum-1;
	}

	$('.focus .fadingnews div').eq(previousNews).css({
		'background-color':'#fff',
		'z-index':2
	});
	$('.focus .fadingnews div').eq(newsNum)
		.css({
			'background-color':'#fff',
			'z-index':3
		})
		.fadeIn(500,function() {
		$('.focus .fadingnews div').eq(newsNum).css('background-color','transparent')
		$('.focus .fadingnews div').eq(previousNews).hide();
	});
}

/*
	Plugin clearMorphingBg par Olivier Gorzalka
	Permet de gérer un fond animé (fadeIn/FadeOut d'images)
	Dernière mise �  jour : 9 avril 2009
*/
(function($) {
	$.fn.extend({
		clearMorphingBg: function (options) {
			// Default options
			var settings = {
				divList:'#overlay1,#overlay2,#overlay3', // liste des classes ou id �  attribuer au panneaux défilants
				htmlBg: {},
				timing:2500, // délai entre chaque changement d'image
				durationAnim:500, // durée de l'animation Fading
				widthBg:null, // forcer la largeur du fond
				functionsBefore: function() {},
				functionsInInterval: function() {}
			};
			if(options) $.extend(settings, options);
			var $this = $(this);

			settings.declareVars;

			settings.functionsBefore;
			var padding_left = parseInt($this.css('padding-left'));
			var padding_right = parseInt($this.css('padding-left'));
			if (settings.widthBg == null) { settings.widthBg = $this.width()+padding_left+padding_right; }

			function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
			var listDiv = settings.divList.split(',');
			var totalDiv = listDiv.length-1;

			var divListHtml = '<div class="morphBg" style="position:relative;z-index:1;height:0;width:0;left:-'+padding_left+'px">';
			$(listDiv).each(function(i,item) {
				var innerHtml = settings.htmlBg[item] ? settings.htmlBg[item] : '';
				if (item.indexOf('#') > -1) { divListHtml += '<div style="width:'+settings.widthBg+'px" id="'+c(item)+'">'+innerHtml+'</div>'; }
				else { divListHtml += '<div style="width:'+settings.widthBg+'px" class="'+c(item)+'">'+innerHtml+'</div>'; }
			});
			divListHtml += '</div>';
			$this.wrapInner('<div class="wrapperMorphBg" style="position:relative;z-index:2"></div>')
			$(divListHtml)
				.insertBefore($this.find('.wrapperMorphBg'))
				.find('div').hide().css('z-index',1);
			if (!$.support.cssFloat) { $this.find('.wrapperMorphBg').css('float','left') };

			$this.find('.morphBg div:first').css('z-index','3').show();
			var bgNum = 0;

			function nextBg() {
				if (bgNum == totalDiv) {
					bgNum = 0;
					previousScreen = totalDiv;
				} else {
					bgNum++;
					previousScreen = bgNum-1;
				}
				$this.find('.morphBg div').eq(previousScreen).css('z-index',2);
				$this.find('.morphBg div').eq(bgNum).css('z-index',3).fadeIn(settings.durationAnim,function() {
					$this.find('.morphBg div').eq(previousScreen).hide();
				});

			}

			setInterval(function() {
				nextBg();
				nextNews(); // �  ne pas mettre dans le plugin
			},settings.timing);

		}
	});
})(jQuery);


/* Fonction permettant d'afficher le cadre de news défilante sur la home */
function blockProductHome() {
	if (!$('#home_page').length) return
	highest = 0;

	$(window).load(function() {
		$('.focus div div:parent').each(function() {
			heightElem = $(this).eq(0).height();
			if (heightElem >= highest) {
				highest = heightElem; // on récupère le cadre de div le plus grand
			}
		})

		$('.focus')
			.addClass('jsApplied')
			.css({
				'height':highest
			})
			.after('<div style="position:absolute;bottom:83px;left:20px;z-index:1" class="focus newFocus"><div style="height:'+highest+'px"></div></div>');

		$('.focus .fadingnews div:parent').hide() // on masque toutes les news
		$('.focus .fadingnews div:first').css('z-index','3').show(); //  on affiche que la première

		$('<div class="roundedImg"></div>').appendTo('.focus.jsApplied .fadingnews');
		if (isIE) {
			$('.roundedImg').clearPng();
		}
	})

}

/* Permet de précharger le contenu HTML pour zoom dans la FancyBox */

(function($) {
	$.fn.extend({
		loadFancyContent: function (options) {
			var $this = $(this);

			// Default options
			var settings = {
				imgSelector:'.productImg',
				contentSelector:'.descProduct'
			};
			if (options)
				$.extend(settings, options);

			// remove the "." form the class selector
			function c(classSelector) {
				return classSelector.substr(1, classSelector.length);
			}

			// insère #zoomHtml
			if (!$('#zoomHtml').length)
			  $('<div style="position:absolute;top:-9999px" id="zoomHtml"></div>').appendTo('body');

			// Ajout de la fonctionnalité de bloc HTML zoomable
			// pour chaque col
			$this.each(function(i,item) {
				var $elem = $(item);

				var image = $elem.find(settings.imgSelector)
				var content = $elem.find(settings.contentSelector)
				var already_applied = $elem.find('.wrappercontenttxt_'+i)

				if (!image.length || !content.length || already_applied.length)
					return;

				var lightbox_link = image.find('a[rel^=lightbox]')
				var zoomedImg = lightbox_link.attr('href')
				var zoomedImgTitle = lightbox_link.attr('title')
				lightbox_link.addClass('specialContent').attr('href', '#zoomHtml_'+i)

				var widthTxt = content.width()
				var heightBlock = content.height() || $elem.height()

				// if (!image.next('div').length) alert('Error: missing a div')
				var parseHtml = image.next('div').html()

				var htmlBlock = '<div style="padding-bottom:20px"'
				htmlBlock += ' class="wrappercontenttxt_'+i+'" id="zoomHtml_'+i+'">'
				htmlBlock += '<div class="illustr"></div>'
				htmlBlock += '<div class="contenttxt">'+parseHtml+'</div>'
				htmlBlock += '</div>'
				$(htmlBlock).appendTo('#zoomHtml');

				var preloading = '<img id="preloadImg_'+i+'" src="'+zoomedImg+'" alt="" />'
				$(preloading).appendTo('#zoomHtml_'+i+' .illustr');

				// une fois que les images sont chargées
				// et donc que les tailles d'images sont calculées
				$(window).load(function() {
					var widthImg = $('#preloadImg_'+i).width();
					var heightImg = $('#preloadImg_'+i).height()

					if (heightImg > heightBlock)
						heightBlock = heightImg;

					var optionSize = { width: widthImg + 20 }
					if ($.support.minHeight())
						optionSize.minHeight = heightBlock + 20
					else
						optionSize.height = heightBlock + 25

					$('#zoomHtml_'+i).css(optionSize)

				}); // fin window load


			}); // fin pour chaque col

		}
	});
})(jQuery);



/* Gestion des tailles dynamique �  des conteneurs ayant des blocs flottant */
(function($) {
	$.fn.adjustWidth = function(options) {
		var settings = {
			floatingParentTag:'li', // tag des conteneurs du conteneur
			baseWidth:0 // taille de base (permet de procéder �  des corrections)
		};
		if(options) $.extend(settings, options);
		if (!$.support.borderRadius || $.browser.safari) {
			$(this).each(function(i,container) {
				var width=settings.baseWidth;
				$(container).find(settings.floatingParentTag+':parent').each(function(i,item) {
					var widthBlock = parseInt($(item).width());
					var border_left = parseInt($(item).css('border-left-width'));
					var border_right = parseInt($(item).css('border-right-width'));
					var padding_left = parseInt($(item).css('padding-left'));
					var padding_right = parseInt($(item).css('padding-right'));
					var margin_left = parseInt($(item).css('margin-left'));
					var margin_right = parseInt($(item).css('margin-right'));
					if (!isNaN(widthBlock)) width += widthBlock;
					if (!isNaN(padding_left)) width += padding_left;
					if (!isNaN(padding_right)) width += padding_right;
					if (!isNaN(margin_left)) width += margin_left;
					if (!isNaN(margin_right)) width += margin_right;
					if (!isNaN(border_left)) width += border_left;
					if (!isNaN(border_right)) width += border_right;
				});
				$(container).css('width',width);
			});
		}
	}
})(jQuery);

/* Plugin num�rotant les �l�ments via des classes */
(function($) {
	$.fn.clearNumberize = function(options) {
		var settings = {
			prefixClass:'eq' // prefix de classe pour la num�rotation
		};
		if(options) $.extend(settings, options);
		var idOffset;
		var j = 0;
		$(this).each(function() {
			var testValue = idOffset;
			if (typeof testValue != 'undefined' && $(this).parent('ol').offset().top != testValue) j = 0;
			idOffset = $(this).parent('ol').offset().top;
			$(this).addClass(settings.prefixClass+(j))
			j++;
		});

	}
})(jQuery);

/* Contraire de la fonction wrap de jQuery ;) */
(function($){
	$.fn.unwrap = function(elem){
		var elements;

		if (elem == null){ elements = jQuery(this); }
		else if (typeof elem == "string"){ elements = jQuery(this).find(elem); }
		else if (typeof elem == "object"){ elements = elem; }
		else alert("unknow elem");

		elements.each(function(){ jQuery(this).parent().replaceWith(jQuery(this)); });
	}

})(jQuery);

/* Vérifie si les champs du formulaire sont bien remplis */
(function($) {

	$.fn.clearCheckForm = function() {
		var $this = $(this);

		/* Patterns pour la vérification des types de champs */
		var mailPattern = new RegExp(/^(.+)@([^\(\);:,<>]+\.[a-zA-Z]{2,4})/);
		var minLengthPattern = new RegExp(/required\[([0-9]*)\]/);
		var numericPattern = new RegExp(/^([0-9]*)$/);

		var minLength;
		var errorTxt = new Array();
		var htmlError = '<span class="error_form"></span>'; // html du code de l'erreur

		// Ajoute les styles d'erreur sur le champ parcouru
		function addErrorStyle($elem,classError,htmlError) {
			if (!$elem.next(classError).length) {
				$elem.after(htmlError).closest('p').addClass('error_field');
			}
		}
		$this.submit(function() {

			$this.find('.errorRadio').each(function() {
				$(':radio').each(function() {
				    if ($(this).parent('.errorRadio').length) {
				        $(this).unwrap();
				    }
				})

				$(this).replaceWith($(this).html()); // on retire les span eventuels autour des boutons radio
			});
			var error = 0; // total d'erreur au lancement du submit

			// on parcoure l'ensemble des champs requis
			$(':input[class*=required]').each(function(i,item) {
				var e = 0 // variable d'incrémentation pour les messages d'erreurs
				errorTxt[i] = new Array(); // on créé une array de messages d'erreurs

				// cas des boutons radio
				if ($(this).is(':radio') && !$(this).parent('span').length) {
					var attrName = $(this).attr('name'); // récupère le name du champs

					// on vérifie pour les champs ayant le même champs name si un des boutons radio est bien selectionné
					if ($this.find(':radio[name='+attrName+']').is(':checked') == false) {
						$this.find(':radio[name='+attrName+']').wrap('<span class="errorRadio"></span>').closest('p').addClass('error_field'); // on ajoute un style pour les erreurs
						errorTxt[i][e] = ''; // pseudo-message d'erreur
						e++;  // incrémentation du nombre de messages d'erreur
					}
				} else {
					minLength = $(this).attr('class').match(minLengthPattern); // nombre minimum de caractère requis
					value = $(this).val(); // value du champs parcouru

					// si la valeur est vide
					if (value == '') {
						addErrorStyle($(this),'.error_form',htmlError); // on ajoute un style pour les erreurs s'il n'est pas déj�  présent
						errorTxt[i][e] = 'Vous devez préciser votre '+$(this).prev('label').text().replace('*','').toLowerCase();
						e++;
						$(this).closest('p').addClass('error_field');
					}

					// si le nombre minimum de caractère requis n'est pas atteint
					else if (minLength && value.length < minLength[1]) {
						addErrorStyle($(this),'.error_form',htmlError); // on ajoute un style pour les erreurs s'il n'est pas déj�  présent
						// ajout du message d'erreur
						errorTxt[i][e] = 'Ce champs requiert '+minLength[1]+' caractère' + (minLength[1] > 1 ? 's' : '') + ' minimum';
						e++; // incrémentation du nombre de messages d'erreur
					}

					// si le champs numérique n'est pas valide
					if ($(this).hasClass('numeric') && !value.match(numericPattern)) {
						addErrorStyle($(this),'.error_form',htmlError); // on ajoute un style pour les erreurs s'il n'est pas déj�  présent
						// ajout du message d'erreur
						errorTxt[i][e] = 'Ce champs n\'accepte que les caractères numériques';
						e++; // incrémentation du nombre de messages d'erreur
					}

					// si le champs email n'est pas une adresse email valide
					if ($(this).hasClass('email') && !value.match(mailPattern)) {
						addErrorStyle($(this),'.error_form',htmlError); // on ajoute un style pour les erreurs s'il n'est pas déj�  présent
						// ajout du message d'erreur
						errorTxt[i][e] = 'Cette adresse email n\'est pas correcte';
						e++; // incrémentation du nombre de messages d'erreur
					}

					// on affiche les messages d'erreur associés au champs parcouru
					$(this).next('.error_form').html(errorTxt[i].join("<br />"));
				}

				// si le nombre de messages d'erreurs est supérieur �  Zero, on incrémente le total d'erreur
				if (errorTxt[i].length > 0) {
					error++;
				}
			});

			if (error > 0) {
				if (error == 1) {
					alert(error+' champs requis n\'a pas été renseigné'); // on affiche une alerte comprenant le nombre d'erreur sur le formulaire
				} else {
					alert(error+' champs requis n\'ont pas été renseignés'); // on affiche une alerte comprenant le nombre d'erreur sur le formulaire
				}

				return false; // on empèche le formulaire d'être soumis
			}
		});

		$this.find(':input').focus(function() {
			$(this).next('.error_form').remove();
			if ($(this).is(':radio')) {
				var attrName = $(this).attr('name');
				if ($(this).parent('.errorRadio').length) {
					$(':radio[name='+attrName+']').unwrap();
				}
				$(this).attr('checked','checked');
				$(':radio[name='+attrName+']').closest('p').removeClass('error_field');

			} else {
				$(this).closest('p').removeClass('error_field');
			}

		});

	}
})(jQuery);


function initPoints($this,totalAddress,pos) {
	addressVcard = new GLatLng($this.find('.latitude').text(), $this.find('.longitude').text(), true);
	//addressVcard = $this.find('.street-address').text()+' '+$(this).find('.postal-code').text()+' '+$(this).find('.locality').text();
	/*$('#map').jmap('SearchAddress', {
		'query': addressVcard,
		'returnType': 'getLocations'
	}, function(result, options) {*/
		//var valid = Mapifies.SearchCode(result.Status.code);
		//if (valid.success) {
			var point = new GPoint($this.find('.longitude').text(), $this.find('.latitude').text());//$(result.Placemark)[0];
			var latitude = $this.find('.latitude').text();//point.ExtendedData.LatLonBox.north;
			var longitude = $this.find('.longitude').text();//point.ExtendedData.LatLonBox.west;

			/*$('#map').jmap('AddMarker',{
				'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
				'pointHTML':$this.find('.info').html(),
				pos: pos
			});*/

			$('#map').jmap('AddMarker',{
				'pointLatLng':[$this.find('.latitude').text(), $this.find('.longitude').text()],
				'pointHTML':$this.find('.info').html(),
				pos: pos
			});

			if (pos+1 == totalAddress || pos == 9) {
				$('#map').jmap('MoveTo', {
					mapCenter: [latitude,longitude],
					mapType : 'map',
					mapZoom:12,
					centerMap:true,
					centerMoveMethod:'pan'
				});

			}
	//}
	/*});*/
	return false;
}

function moveToPoint(addressVcard) {
	$('#map').jmap('SearchAddress', {
		'query': addressVcard,
		'returnType': 'getLocations'
	}, function(result, options) {
		var valid = Mapifies.SearchCode(result.Status.code);
		if (valid.success) {
			var point = $(result.Placemark)[0];
			var latitude = point.ExtendedData.LatLonBox.north;
			var longitude = point.ExtendedData.LatLonBox.west;
			$('#map').jmap('MoveTo', {
				mapCenter: [latitude,longitude],
				mapType : 'map',
				mapZoom:15
			});
	} else {
			alert('Nous ne sommes pas parvenus à localiser cet installateur')
		}
	});
}


/* Au chargement de la page */

$(document).ready(function(){
	
	// HTML du formulaire de contact
	var htmlContact = '<div style="display:none" id="SendToFriend">';
	htmlContact    +='<div class="contactForm">';
	htmlContact    +='<h3>Envoyer cette page à un ami</h3>';
	htmlContact    +='<div id="formEnvoiFriend">';
	htmlContact    +='<p>Renseignez vos coordonnées ainsi que celles du destinataire pour lui envoyer le lien vers cette page par email.<br />Vos coordonnées ne seront pas conservées. Tous les champs sont obligatoires.</p>';
	htmlContact    +='<form action="#" method="post">';
	htmlContact    +='<fieldset>';
	htmlContact    +='<p class="first"><label for="sfName1" >Votre nom&nbsp;:</label><input class="text" id="sfName1" name="name1" type="text" value="" /></p> ';
	htmlContact    +='<p><label for="sfEmail1" >Votre email&nbsp;:</label><input class="text" id="sfEmail1" name="from" type="text" value="" /></p>';
	htmlContact    +='<p><label for="sfNameD1" >Nom du contact&nbsp;:</label><input class="text" id="sfNameD1" name="nameD1" type="text" value="" /></p>';
	htmlContact    +='<p><label for="sfEmailD1" >Email du contact&nbsp;:</label><input class="text" id="sfEmailD1" name="emailD1" type="text" value="" /></p>';
	htmlContact    +='<p class="button"><input type="hidden" name="formid"  value="SendToFriend" /><input id="sfRecommend" name="recommend" type="submit"  value="Envoyer" /></p>';
	htmlContact    +='</fieldset>';
	htmlContact    +='</form>';
	htmlContact    +='</div>';
	htmlContact    +='</div>';
	
	$(htmlContact).appendTo('body');
	
	$('.productlist').adjustWidth();
  $('ol li').clearNumberize();
	
	// Gère les liens externes
	$("body").addClass('jsActive').live("click", function(e){
		var $target = $(e.target);
		if ($target.is('[rel=external]')) {
			window.open($target.attr('href'));
			return false;
		}
	 	});
	
	if (!$.support.cssFloat) {
		$('body').addClass('iemode');
	}
	
	// gère les blocs sur lesquel on applique le filtre PNG pour IE
	if (isIE) {
		var heightBlock;
		heightMax = 0;
		$('div.blocHome').each(function() {
			heightBlock = $(this).find('div').height()+100;
			if (heightBlock >= heightMax) { heightMax = heightBlock; }
			var leftPos = Math.round($(this).offset().left)-Math.round($('#content').offset().left);
			var topPos = Math.round($(this).offset().top)-Math.round($('#content').offset().top);
			idBlock = $(this).attr('id')+'_alternate';
			$block = $(this).find('div');
			$block
				.insertBefore($(this))
				.attr('id',idBlock)
				.addClass('blocHome')
				.css({
					'position':'absolute',
					'top':topPos,
					'left':leftPos,
					'z-index':'10'
				});
		});
		$('div.blocHome')
			.css('height',heightMax)
			.clearPng();
	}
	
	/* Gestion du champs de formulaire de recherche */
	$('form.search')
		.find('input[type=text]')
		.attr('value',$('form.search').find('label').text())
		.focus(function(){
			$(this).attr('value','');
		});
	
	/* Menu déroulant*/
	function showmenu(){ $(this).addClass('shownmenu'); $(this).removeClass('hiddenmenu'); }
	function hidemenu(){ $(this).removeClass('shownmenu'); $(this).addClass('hiddenmenu'); }
	$(".submenu").parent('li').hoverIntent({
		interval: 50,
		over: showmenu,
		timeout: 500,
		out: hidemenu
	});
	$(".submenu").parent('li').addClass('jsActive hiddenmenu');
	
	/* Insertion du lien Imprimer cette page */
	$('#functions .sendafriend').addPrintLink({
		txt:'Imprimer cette page',
		tag:'li',
		className:'.print',
		mode:'insertBefore'
	});
	
	
	
	/* Ajout de la fonctionnalité de zoom sur les images */
	$('#menu').accordionMenu({
		hideOnLoad:'trueIfNoActive', // cacher tout les items au chargement de la page (true, false, trueIfNoActive)
		classActiveMenu:'.active', // classe des menus actifs
		showActiveMenu:true, // ouvrir le sous menu actif
		alwaysShowActive:true // laisser l'item actif toujours ouvert
	});
	
	
	/* clearAccordion */
	/* Insertion des arrondis */
	var roundedCornerHtml = '<span class="cornerrighttop">&nbsp;</span><span class="cornerlefttop">&nbsp;</span>';
	$(roundedCornerHtml).appendTo('#accordion');
	
  $('#accordion').clearAccordion({
    panelTag:'li',
    clickZone:'h6',
    correctLengthSlide:7
  });
	
	/* ClearCarousel */
	/* Insertion des boutons de controles */
	var prevBtnHtml = '<span class="previousitem">Précedent</span>';
	var nextBtnHtml = '<span class="nextitem">Suivant</span>';
	$(prevBtnHtml).insertBefore('.slidenavigation:not(.simpleproduct) ul')
	$(nextBtnHtml).insertAfter('.slidenavigation:not(.simpleproduct) ul')
	
	$('.slidenavigation:not(.simpleproduct)').clearCarousel({
		insideContainer:'ul',
		panelTag:'li',
		nextBtn:'.nextitem',
		prevBtn:'.previousitem',
		classInsideWrapper:'.wrappernavigation',
		nbrToShow:5,
		correctBottomTopHeight:8
	});
	
	if ($('.simpleproduct.slidenavigation li').length/2 <= 2)
		$('.simpleproduct.slidenavigation ul').css('width', 250);
	
	/* Fond de Page animé sur la homepaghe*/
	$('#home_page #wrapper').clearMorphingBg({
		divList:'#overlay1,#overlay2,#overlay3',
		timing:5000,
		htmlBg: {
			'#overlay1':$('#textebgdindex').html()
		},
		functionsBefore: blockProductHome()
	});
	
	// Préchargement du contenu HTML des caractéristiques produit �  zoomer via la fancybox
	$('.productdetails').loadFancyContent();
	
	// Correctif pour les images en positionnement flottant disposant de loupe (lightbox)
	$('a[rel^=lightbox]')
		.addClass('zoomable')
		.fancybox({ Speed:1000 }) // on applique la fancybox
		.filter(':has(img)') // uniquement dans les liens ayant des images
		.append('<span class="zoom"></span>') // on ajoute un span contenant une image zoom
		.each(function() {
			var $this = $(this);
			// on définit les options css selon le type d'image
			if ($this.find('.illustr')) {
				$this.addClass('linkIllustr');
				$this.css({
					// width: $this.find('img').width()
				});
			} else if ($this.find('.illustr2')) {
				$this.css({
					position: 'relative',
					width: $this.find('img').width(),
					height: $this.find('img').height()
				});
			}
		})

	// Ajustement de l'alignement vertical des onglets dans les pages produits
	$('.tabnavigation li a span').each(function() {
		if ($(this).height() > 13)
			$(this).closest('li').addClass('tab_h'+$(this).height());
	});

	// Génère tabs
	$('.tabulize').tabGenerator({
		separator : 'h3', // separator
		navigation: '.nav', // tab links class or id
		tabClassName: '.tabApplied'
	});


	/* Bloc focus scrollable */
	if ($('#sidebar').height()+80 < $('#content').height()) {
		// on ajuste la hauteur de la sidebar avec la taille du contenu
		var height = $('#content').height()-80-($('.nav') != undefined ? $('.nav').height() : 0);
		//var height = $('#content').height()-80;

		if ($.support.minHeight())
			$('#sidebar').css({ minHeight: height });
		else
			$('#sidebar').css({ height: height });
		//$('#sidebar .focus').clearScroll({ speed:500 }); // on lance le clearScroll
    if (!$('#home_page').length) {
      $('#sidebar .focus').clearScroll({ speed:500 }); // on lance le clearScroll
    }
	}


	$('.defaultForm form').clearCheckForm();

	/* Google Map */
	if (typeof(Mapifies) != "undefined") {
		var addressVcard;
		var point,marker,num,htmlReadMore;

		$('#map').jmap('init', {
			mapType:'map',
			mapCenter:[46, 2],
			mapZoom:5,
			mapControl:'large',
			mapShowjMapsIcon:false,
      mapEnableScrollZoom:true,
			mapEnableType:true
		});

		var lengthAdress = $('.adresslist li').length;
		$('.adresslist li').each(function(i,item) {
			initPoints($(this),lengthAdress,i);
		});

		/* Pagination javascript des résultats */
		var per_page = 5;
		var hashCurrent = 0;
		var hash = window.location.hash;
		var nbrePage = Math.ceil( $('.adresslist li').length / per_page )
		hashPage = parseInt(hash.substr(1));

		if (!isNaN(hashPage) && hashPage <= nbrePage) { hashCurrent = hashPage; }

		function pageselectCallback(page_index, jq){
			$('.adresslist li').hide().slice(page_index*per_page,page_index*per_page+per_page).show();
			$('.pagination :first').before('<span class="pagenumber">Page '+(page_index+1)+'/'+nbrePage+'</span>');
		}

		$('<div class="pagination"></div>').insertAfter('.adresslist');

		var max_elem = $('.adresslist li').length;
		$(".pagination").pagination(max_elem,{
			items_per_page:per_page,
			current_page:hashCurrent,
			link_to:"#__id__",
			prev_text:"&lt;",
			next_text:"&gt;",
			ellipse_text:"...",
			prev_show_always:true,
			next_show_always:true,
			num_edge_entries: 1,
			callback:pageselectCallback
		})

		$('.adresslist li').each(function(i) {
			htmlReadMore = '<p class="clearboth">'+$(this).find('.n').text()+'</p>';
			htmlReadMore += '<p class="readmore clearboth">';
			htmlReadMore += '<a href="javascript:Mapifies.OpenWindow('+i+');" title="Plus d\'informations sur '+$(this).find('h3').text()+'">';
			htmlReadMore += '&gt;&nbsp;En savoir plus</a>';
			htmlReadMore += '</p>';

			$(htmlReadMore).appendTo(this).bind('click', function() {
      	addressVcard = new GLatLng($(this).parent('li').find('.latitude').text(), $(this).parent('li').find('.longitude').text(), true);
				//addressVcard = $(this).parent('li').find('.street-address').text()+' '+$(this).find('.postal-code').text()+' '+$(this).find('.locality').text()+' FRANCE';
				moveToPoint(addressVcard);
			});
		})

	} // fin Google Map


	$('#results').clearHighlight({
		searchTerm: 'radiateur',
		insensitive: true,
		classHighlight: '.highlight',
		tagHighlight: 'strong'
	});


	// si page carte
	if ($('#carte').length) {
		// désactive clics sur la carte
		$('#carte').click(function(){ return false })

		// insère la popup
		$('body').after('<div id="carte-popup" style="display:none"></div>')

		// au mouvement de la souris sur la carte
		$('#carte').mousemove(function(e) {
			var region = e.target.hash // région survolée (eg. "#region-42")
			if (!region || !region.match(/^#region-/))
				return;

			region = $(region)
			var popup = $('#carte-popup')

			// on m� j l'html juste si les classes sont différentes
			if (region[0].className != popup[0].className) {
				popup.html(region.html()) // html pris dans id="#region-42"
				popup[0].className = region[0].className
			}

			// doit-on afficher la bulle �  gauche ou �  droite ?
			var is_left = popup[0].className.match(/-0(1|2|3|4)$/)

			// on affiche et déplace la popup �  environ 10 cm de la souris
			popup.css({
				display: 'block',
				left: e.pageX + (is_left ? -230 : 10),
				top: e.pageY - 130
			})
		})

		// si on on on essaie de survoler la popup, la masquer
		// permettant d'éviter qqes bugs de blocages
		$('#carte-popup').mousemove(function(){$(this).hide()})

	}


});

// 
// // Mets-� -jour #carte-popup �  partir du #hash dans l'url
// function show_department_from_hash() {
// 	var popup = $('#carte-popup');
// 	if (!popup.length)
// 		return;
// 
// 	// remplace l'html de la popup par celui de #departement-42
// 	var hash = window.location.hash;
// 	if (hash && hash.match(/#region-/))
// 		popup.html($(hash).html());
// 
// 	// si vide applique la classe empty
// 	popup[(popup.html() ? 'remove' : 'add')+'Class']('empty');
// }

/* A faire une fois que la page est chargée */
$(window).load(function() {
	//$('.productdetails > div:not(.dynamicsize)').equalHeights();
  $('.productdetails > div').equalHeights(0,0,1);
  $('.slidenavigation > ul > li').equalHeights();
});


