jQuery(document).ready(function() {
	
	var win							= jQuery(window),
		BBTool_pageSizes 			= BBTool_getPageSize(),
		BBTool_pageScroll 			= BBTool_getPageScroll();
		BBVars.pageWidth 			= BBTool_pageSizes[0],
		BBVars.pageHeight 			= BBTool_pageSizes[1],
		BBVars.windowWidth 			= BBTool_pageSizes[2],
		BBVars.windowHeight 		= BBTool_pageSizes[3],
		BBVars.pageScrollX 			= BBTool_pageScroll[0],
		BBVars.pageScrollY 			= BBTool_pageScroll[1],
		BBVars.dspAreaWidth			= win.width(),
		BBVars.dspAreaHeight		= win.height(),
		BBVars.dataSendContentID	= (jQuery(".dataSend").length>0) ? jQuery(".dataSend").attr("id") : "",
		
	win.bind('resize', function() {
		BBTool_pageSizes		= BBTool_getPageSize(),
		BBVars.pageWidth		= BBTool_pageSizes[0],
		BBVars.pageHeight		= BBTool_pageSizes[1],
		BBVars.windowWidth		= BBTool_pageSizes[2],
		BBVars.windowHeight		= BBTool_pageSizes[3],
		BBVars.dspAreaWidth		= win.width(),
		BBVars.dspAreaHeight	= win.height();
	}).bind("scroll", function() {
		BBTool_pageScroll 		= BBTool_getPageScroll(),
		BBVars.pageScrollX 		= BBTool_pageScroll[0],
		BBVars.pageScrollY 		= BBTool_pageScroll[1];
	});
	
	initCartBlock();
	initDebug();
	initSymbols();
	initPictColorList();
	BBTool_flash();
	BBSlider();
	initCGVMenu();
	bannerRand();
	
	$("#search").autocomplete(BBVars.pagesURL + "/ajax/search.cfm",
		{
			minChars:2,
			delay:200,
			autoFill:false,
			matchSubset:false,
			matchContains:1,
			cacheLength:10,
			selectOnly:1
		}
	);
	
	switch( BBVars.currentPageName ) {
	
		case "panier":
			if (show_kdo) {	
					BBTool_openMsgBox(jQuery("#conainer_goodies").html(), true);
					jQuery("#conainer_goodies").html("");
			}
			jQuery(".modifyBasket").bind("click", function() {
				var panier_id = jQuery(this).attr("id").replace("lien_","");
				jQuery(".modifyOptions_layer").css({height:0,width:0}).html("");
				BBChangePanier(panier_id);
			});	
			break;
			
		// ------------------------------------ FICHE ---------------------------------- //
		case "fiche":
			/*
			jQuery("#illusProduct img").batchImageLoad({
				loadingCompleteCallback: MagicMagnify_findMagnifiers()
			});
			*/
			
			initThumbGallery();
			initProductCare();
			initSymbols();
			initDspDesc();
			initColorsPictos();
			initScrollable("#otherProducts div.scrollable");

			jQuery(".mainImg").epicZoom({
				magnification: 1,
				size: 200,
				blankCursor: false,
				hideCursor: true,
				newPosition: true
			});
			
			jQuery("#BBTool_galMainImg").bind("mouseenter", function() {
				jQuery(".picto.selected").stop().animate({opacity: 0}, function() { jQuery(this).css("display", "none") });
				if(jQuery(".eiz-container").length==0) {
					jQuery(".mainImg").epicZoom({
						magnification: 1,
						size: 200,
						blankCursor: false,
						hideCursor: true,
						newPosition: true
					});
				}
			}).bind("mouseleave", function() {
				jQuery(".picto.selected").css({display: "block", opacity: 0}).stop().animate({opacity: 1}, function() {
						if(BBVars.isMsIE)
							this.style.removeAttribute("filter");
					});
			});
			
			jQuery("#noAttribLayer")
				.css("display", "block")
				.animate({opacity: 0})
				
			jQuery(".tailleList li a").bind("click", function(e) {
				e.preventDefault();
				var ItemID = jQuery(this).parent().attr("id");
				var ItemStock = jQuery(this).parent().attr("stock");
				if(ItemStock > 0) BBCart('setAttrib', ItemID, setAttrib_callBack, 1);
			});
			
			break;
			
		// ------------------------------------ COMPTE SUIVI ---------------------------------- //
		case "compte_suivi":
			jQuery(".suivi_table td.orderLink a").bind("click", function(e) {
				e.preventDefault();
				loader = jQuery("#cmdDetailsLayer div.loader");
				loader.css({opacity: 0, display: "block", height: jQuery("#cmdDetailsLayer").outerHeight() }).animate({opacity: 1});
				jQuery("#cmdDetailsLayer").css({display: "block"});
				jQuery("#cmdDetails").empty();
				jQuery.get(
					jQuery(this).attr("href"),
					function(data) {
						BBTool_openMsgBox(data, true);
						loader.animate({opacity: 0}, function() { jQuery(this).css("display", "none"); });
					}
				);
			});
			break;
		
		// ------------------------------------ COMPTE ---------------------------------- //
		case "compte":
			if(jQuery("#search_ok").length == 1)
				jQuery('html,body').stop().animate({scrollTop: jQuery("#search_ok").offset().top-35}, "slow");
			break;
		// ------------------------------------ INDEX ---------------------------------- //
		case "index":

			// ---------------------- BANNIEREs PRINCIPALES ---------------------------------//
			
			var layer = jQuery("#mainBannerLayer div.bannerContenerLayer"),
				bannerList = jQuery(".mainHomeBanner", layer),
				links = jQuery("#mainBannerLayer div.bannerControlsLayer a");
				
			links.bind("click", function() {
				switchBanner( links.index( jQuery(this) ) );
			});
			links.eq(0).addClass("selected");
			
			bannerList.eq(0).css({display: "block", opacity: 0}).animate({opacity: 1});
			if( bannerList.length > 1 ) {
				BBVars.timer = setTimeout("switchBanner()", 4000);
			}
					
			// ----------------------- SELECTIONS PRODUITS ---------------------------------//
			/*var divSelected = jQuery("#homeSelLayer div.selListLayer div.selected").attr("id");
			initCarousel(divSelected);*/
			
			initScrollable("#homeSelLayer div.selListLayer div.scrollable.selected");

			var tabList = jQuery("#homeSelLayer ul.tabList");
			
			jQuery("li.tab", tabList).each( function(i,el) {
				jQuery(this).bind("click", function(e) {
					e.preventDefault();
					tab = jQuery(this);
					if(!tab.hasClass("selected")) {
					
						currentTab = jQuery(".selected", tabList),
						currentList = jQuery("#" + jQuery("a", currentTab).attr("rel") ),
						newList = jQuery("#" + jQuery("a", tab).attr("rel") );
						currentTab.removeClass("selected");
						tab.addClass("selected");
						
						currentList.stop().animate({opacity: 0}, 500, function() {
							jQuery(this).css("display", "none");
							newList.css({display: "block", opacity: 0});
							initScrollable(newList);
							newList.animate({opacity: 1}, function() {
								if(BBVars.isMsIE)
									this.style.removeAttribute("filter");
							});
						});
					}
				});
			});
			
			// ---------------------- SILHOUETTE DU BAS ---------------------------------//
			var tooltipOptions = {
					xOffset: 		30,
		            yOffset: 		100,
		            tooltipID: 		'BBTTip',
					tTipHeight:		"auto",
					tTipWidth:		"auto",
					tTipDspPos:		"hrzt",
					pointer:		false,
					pointerPos:		"auto",
					pointerOffset:	{x:0, y:0},
					classN:			"",
					events:			{
										init:	"mouseenter",
										show:	"mousemove",
										hide:	"mouseleave"
									}
				}, descTooltipOptions = {
					xOffset: 		30,
		            yOffset: 		0,
		            tooltipID: 		'BBTTip',
					tTipHeight:		"auto",
					tTipWidth:		300,
					tTipDspPos:		"hrzt",
					pointer:		true,
					pointerPos:		"auto",
					pointerOffset:	{x:0, y:0},
					classN:			"homeProdDesc",
					events:			{
										init:	"mouseenter",
										show:	"mousemove",
										hide:	"mouseleave"
									}
				}, descLayer = jQuery(".presentLayer .prodDesc");
			
			jQuery(".silLayer .BBTTip").tooltip( function(el) { return "<img height='253' src='"+jQuery(el).attr("rel")+"'>";}, tooltipOptions);
			
			jQuery(".linkLayer").bind("mouseenter", function(e) {
				jQuery("a", this).addClass("hover");
			}).bind("mouseleave", function(e) {
				jQuery("a", this).removeClass("hover");
			}).bind("click", function(e) {
				window.location = jQuery("a", this).attr("href");
			});
			
			if(descLayer.height()>71) {
				descLayer.css({overflow: "hidden", height: "60px"}).tooltip(
					function(el) { return jQuery(el).html();}
					, descTooltipOptions
				);
			}
			
			break;
			
		case "livraison":
			BBSlider("#slider");
			break;

		case "univers":
			/*if (document.location.hash == '#cat_id=&page=&tri=&rayon=&taille=&couleur=&maxrows=' || document.location.hash == '')
				{
					//smooth_effect(jQuery("#detailNouveautes").html());
					document.location.hash = BBVars.hash_init;
				}*/
				
			initialize();
			break;
			
		case "selection":
			/*if (document.location.hash == '#selection_id=&page=&tri=&rayon=&taille=&couleur=&maxrows=' || document.location.hash == '')
				{
					//smooth_effect(jQuery("#detailNouveautes").html());
					document.location.hash = BBVars.hash_init;
				}*/
				
			initialize();
			break;	
		case "mailing":
			CheckMobile();
			
			break;
	}
	
});

/* Carousel homepage */
function initCarousel (ID) {
	var carouselID = "homepage_carousel_"+ID;
	var numberItems = jQuery("#" + carouselID + "> li").size();
	if (numberItems > 5) {
		jQuery("#" + carouselID).jcarousel({
			wrap: 'circular',
			buttonNextEvent: 'click',
			scroll: 1,
			animation: 'normal'
		});
	}
}

function bannerRand() {

	var layer = jQuery(".rand");
	layer.each( function() {
		var bannersOrder = [],
			banners = jQuery(this).children();
		banners.each( function(i,el) {
			bannersOrder[i] = Math.random()*banners.length;
		});
		jQuery(bannersOrder).each( function(i,el) {
			banners.eq(bannersOrder[i]).css("display", ( (i<banners.length) ? "block" : "none" ) )
		});
		jQuery(this).css({opacity: 0, visibility: "visible"}).animate({opacity: 1});
	});

}

function switchBanner( index ) {
	var layer = jQuery("#mainBannerLayer div.bannerContenerLayer"),
		bannerList = jQuery(".mainHomeBanner", layer),
		btnList = jQuery("#mainBannerLayer div.bannerControlsLayer a"),
		currentBanner = jQuery(".mainHomeBanner:visible", layer),
		currentIndex = bannerList.index(currentBanner),
		nextIndex = (typeof(index)!="undefined") ? index : ((currentIndex==bannerList.length-1) ? 0 : currentIndex + 1),
		links = jQuery("#mainBannerLayer div.bannerControlsLayer a");
	
	clearTimeout( BBVars.timer );
	currentBanner.stop().animate({opacity: 0}, function() {
		jQuery(this).css("display", "none");
		links.removeClass("selected");
	});
	bannerList.eq(nextIndex).css({display: "block", opacity: 0}).stop().animate({opacity: 1}, function() { links.eq(nextIndex).addClass("selected"); });
	BBVars.timer = setTimeout("switchBanner()", 4000);
	
}

function initThumbGallery() {
	jQuery(".BBTool_galImg a").bind("click", function(e) {
		e.preventDefault();
		var newImg = jQuery(this).attr("rev");
		jQuery(".mainImg").attr("src",newImg);
		jQuery(".eiz-magnifier div").css('backgroundImage', "url(" + newImg + ")")
	});
}

function initCartBlock() {
		jQuery("#mainCartContent").bind("mouseenter", function(e) {
			jQuery('#cartDetailLayer').css({display: "block", opacity: 0}).stop().animate({opacity: 1}, function() {
					if(BBVars.isMsIE)
						this.style.removeAttribute("filter");
				});
		jQuery("#mainCartContent").bind("mouseleave", function(e) {
			jQuery("#cartDetailLayer").stop().animate({opacity: 0}, function() { jQuery(this).css("display", "none") });
		});	
	});
}

function initProductCare() {
	jQuery("#infosProduct .productCare").bind("mouseenter", function(e) {
		jQuery('.infosList .content').css({display: "block", opacity: 0}).stop().animate({opacity: 1}, function() {
				if(BBVars.isMsIE)
					this.style.removeAttribute("filter");
			});
	jQuery("#infosProduct .productCare").bind("mouseleave", function(e) {
			jQuery(".infosList .content").stop().animate({opacity: 0}, function() { jQuery(this).css("display", "none") });
		});	
	});
}

function initSymbols() {
	 jQuery("#symbolsList li").each( function(i) {
	 jQuery(this).hover( function(e) {
		 jQuery("#alertSymbols").css("background-position", -32-26*(4-i) +"px 100%");
		 jQuery("#alertSymbols").html(jQuery(this).html());
	 });
 });
}

function initPictColorList() {
	jQuery(".mainColor_layer").each( function() {
		var prodID = jQuery(this).attr("id");
		var nbColor = jQuery("#colorChoice_" + prodID + " ul > li").size();
		
		jQuery(this).bind("mouseenter", function(e) {
			if(nbColor > 1) {
				e.preventDefault();
				jQuery("#colorChoice_" + prodID).css({display: "block", opacity: 0}).stop().animate({opacity: 1}, function() {
						if(BBVars.isMsIE)
							this.style.removeAttribute("filter");
					}).bind("mouseleave", function(e) {
						jQuery("#colorChoice_" + prodID).stop().animate({opacity: 0}, function() { jQuery(this).css("display", "none") });
				});	
			}
		});
	
	});
}

function initScrollable( target ) {

	scrollable = (typeof(target)!="undefined") ? jQuery( target ) : jQuery(".scrollable");

	scrollable.each( function(i,el) {
	
		var currentLayer = jQuery(this),
			currentList	= jQuery("ul", currentLayer),
			currentListItems = jQuery("li", currentList),
			dspAreaWidth = currentList.parent().innerWidth(),
			itemWidth = 0,
			nbItem = currentListItems.length,
			nextBtn = jQuery(".next", currentLayer),
			prevBtn = jQuery(".prev", currentLayer),
			defaults = {
							index: 0,
							fx: false,
							callback: "",
							loop: true,
							menu: false,
							menuThumb: []
						},
			params = jQuery.extend({}, defaults, eval( "(" + currentList.attr("data-BBParams") + ")") );
		
		currentListItems.each( function() {
			itemWidth = (jQuery(this).outerWidth()>itemWidth) ? jQuery(this).outerWidth() : itemWidth;
		});
		currentListItems.css("width", itemWidth);
		
		var nbItemDsp = Math.floor(dspAreaWidth/itemWidth),
			listWidth = nbItem*itemWidth,
			scrollable = (listWidth>currentList.parent().innerWidth()) ? true : false,
			init = currentLayer.data("init");
		
		currentList.css("width", listWidth + "px");
		
		if( scrollable && !init ) {
			
			currentLayer.data("init", true);
			
			if(params.menu) {
				currentLayer.append("<ul class='menuBar'>");
				var menuBar = jQuery(".menuBar", currentLayer),
					menuItemWidth = Math.floor(dspAreaWidth/nbItem),
					totalItemWidth = menuItemWidth*currentListItems.length,
					menuBarWidth = menuBar.width();
					
				currentListItems.each( function(i,el) {
					currentItem = ( typeof(params.menuThumb[i]) != "undefined" ) ? "<img src='"+params.menuThumb[i]+"' alt='"+eval(i+1)+"'>" : "<span>"+eval(i+1)+"</span>";
					menuBar.append(
						jQuery("<li"+((i==params.index)?" class='selected'":"")+"><a href='##'>"+currentItem+"</a></li>")
							.css("width", menuItemWidth)
							.bind("click", function(e) {
								e.preventDefault();
								index = jQuery("li", menuBar).index(jQuery("li.selected", menuBar));
								step = i - index;
								jQuery("li", menuBar).removeClass("selected");
								jQuery(this).addClass("selected");
								if( step > 0 ) nextBtn.trigger("click", [step]);
								else if( step < 0) prevBtn.trigger("click", [Math.abs(step)]);
							})
					);
				});
				
				if(totalItemWidth<menuBar.width()) {
					marginWidth = menuBarWidth - totalItemWidth;
					menuBar.css({ width: menuBarWidth - marginWidth, paddingLeft: marginWidth/2, paddingRight: marginWidth/2});
				}
				
			}
			
			if(params.index!=0){
				start = currentListItems.slice(0,params.index),
				end = currentListItems.slice(params.index);
				currentList.empty().append(end).append(start);
			}
			
			nextBtn.bind("click", function( e, step ) {
				e.preventDefault();
				var clicked = false;
				if(typeof(step)=="undefined") {
					clicked = true;
					step = 4;
				}
				if(jQuery(":animated", currentLayer).length==0) {
					var allItems = jQuery("li", currentList),
						newElem = jQuery("li:lt("+step+")", currentList),
						lastItem = allItems.eq(allItems.length-1);
					newElem.clone(true).insertAfter(lastItem);
					if(params.fx) motionBlur();
					currentList.css({ position: "relative", width: listWidth + itemWidth*step }).animate({left: "-"+itemWidth*step }, 250*step, function() {
						newElem.remove();
						jQuery(this).css({left: 0, width: listWidth});
						if(jQuery.isFunction(params.callback)) {
							(params.callback).call();
						}
						if(params.menu&&clicked) {
							nextMenuItem = jQuery("li", menuBar).eq( jQuery("li", menuBar).index(jQuery("li.selected", menuBar)) + 1 );
							jQuery("li", menuBar).removeClass("selected");
							nextMenuItem.addClass("selected");
						}
					});
				}
			}).css("display", "block");
			
			prevBtn.bind("click", function( e, step ) {
				e.preventDefault();
				var clicked = false;
				if(typeof(step)=="undefined") {
					step = 4;
					clicked = true;
				}
				if(jQuery(":animated", currentLayer).length==0) {
					var allItems = jQuery("li", currentList),
						newElem = jQuery("li:gt("+eval(allItems.length-1-step)+")", currentList),
						firstItem = allItems.eq(0);
						
					currentList.css({ position: "relative", width: listWidth + itemWidth*step, left: -itemWidth*step })
					newElem.clone(true).insertBefore(firstItem);
					if(params.fx) motionBlur();
					currentList.animate({left: "+=" + itemWidth*step }, 250*step, function() {
						newElem.remove();
						if(jQuery.isFunction(params.callback)) {
							(params.callback).call();
						}
						if(params.menu&&clicked) {
							prevMenuItem = jQuery("li", menuBar).eq( jQuery("li", menuBar).index(jQuery("li.selected", menuBar)) - 1 );
							jQuery("li", menuBar).removeClass("selected");
							prevMenuItem.addClass("selected");
						}
					});
				
				}
			}).css("display", "block");
			
		} else {
			nextBtn.css("display", "none");
			prevBtn.css("display", "none");
		}

	});
	
}


function initCGVMenu() {
	
	jQuery("#CGVPageList li a").bind("click", function(e) {
		e.preventDefault();
		var currentItem = jQuery(".BBSlider .selected").next();
		var currentItemIndex = jQuery(".BBSlider dt").index(jQuery(".BBSlider .selected"));
		var selectedItem = jQuery(jQuery(this).attr("href"));
		var currentSelectedItemIndex = jQuery(".BBSlider h3").index(jQuery(selectedItem));
		var heightMod = (currentSelectedItemIndex>currentItemIndex) ? currentItem.outerHeight() : 0;
		jQuery('html,body').stop().animate({scrollTop: selectedItem.offset().top-heightMod-35}, "slow");
		selectedItem.trigger("click");
	});
	
	if(BBVars.currentPageName=="cgv") {
		var Index = eval( "(" + jQuery("#cgv .BBSlider").attr("data-BBParams") + ")" ).index;
		if(Index != 0)
		jQuery("html,body").stop().animate({scrollTop: jQuery("#art" + Index).offset().top-35}, "slow");
		
		jQuery("#footer_top a[rel]").bind("click", function(e) {
			e.preventDefault();
			jQuery("#CGVPageList li a").eq(jQuery(this).attr("rel")-1).trigger("click");
		});
		
	}

}
