var functions = {
	waitingTime: 5000,
	
	// vide des champs de types text
	clearInputText: function(){
		$('.clearInputText').bind('focus', function(){ $(this).attr('value',''); });
	},
	
	// Met la premiere lettre d'une phrase en majuscule
	ucfirst: function(str){
		str += '';
		var f = str.charAt(0).toUpperCase();
		return f + str.substr(1);
	},
	
	// Met la premiere lettre d'une phrase en minuscule
	lcfirst: function(str){
		str += '';
		var f = str.charAt(0).toLowerCase();
		return f + str.substr(1);
	},
	
	// Maximise un contenu pour qu'il prenne toute la page
	maximize: function(divObj){
		var bodyWith = $('body').width();
		var h = Math.max( (window.innerHeight?window.innerHeight:0), $('body').offsetHeight, $('html').offsetHeight );
		divObj.height( h+'px' );
		divObj.width(bodyWith);
		divObj.show();
	},

	// Fonction qui va ecrire la balise d'appel du flash
	embedFlash: function(flash,id,div,flashvars,width,height){
		var so = new SWFObject(flash, id, width, height, "8", "#FFFFFF");
		so.addParam("scale", "noscale");
		so.addParam("wmode", "transparent");
		so.addParam("allowFullScreen", "true");
	
		for (var i = 0;i<flashvars.length;i++)
		{
			so.addVariable(flashvars[i].nom, flashvars[i].value);
		}
		so.write(div);
	},
	
	// Retourne la taille du document
	getDocHeight: function(){
		return Math.max(
			( ($.browser.msie && $.browser.version < 8)? 0 : Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) ),
			Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
			Math.max(document.body.clientHeight, document.documentElement.clientHeight)
		);
	},
	
	// Cache le logo sur la page Boutique Luxe
	hideLogo: function(){
		var logoTimeOut = setTimeout( "$('#logo.autoHidden').animate({opacity:0}, 500)", functions.waitingTime );
		$('#logo.autoHidden').hover(
			function(){
				clearTimeout(logoTimeOut);
				$(this).animate({opacity:1}, 500);
			},
			function(){
				$(this).stop(true, true);
				$(this).animate({opacity:0}, 500);
			}
		);
	}
	
};
	
var menus = {
	// Main menu
	mainMenu: function(){
		$('#conteneur_menu > ul > li').hover(function(){
		   //alert(document.getElementById("content_moviie"));
		   /*if (document.getElementById("content_moviie") != null){
		   	document.getElementById("content_moviie").style.visibility="hidden";
		   }*/
			if( $(this).find('ul').css('display') != 'block' ){
				$('#conteneur_menu > ul > li > ul').hide(1).removeClass('hover');
				$(this).addClass('hover').find('ul').slideDown('fast');
			}
			if($.browser.msie && $.browser.version < 7 && ( $(this).attr('id') == 'femme' || $(this).attr('id') == 'accessoiresOn' || $(this).attr('id') == 'homme' )){
				$('#produitsDecroissant').css('visibility', 'hidden');
			}
		},function(){
			$(this).find('ul').slideUp('fast');
			$(this).removeClass('hover');
			if($.browser.msie && $.browser.version < 7){
				$('#produitsDecroissant').css('visibility', 'visible');
			}
			$('#conteneur_menu > ul > li > ul').stop(false, true);
		});
	},
	
	// Vertical menu
	verticalMenu: function(){
		$('#smenu > h3').not('.link').each(function(){
			$('#smenu > h3').not('.link').not('.on').next().hide();
			$(this).bind('click', function(){
				$(this).next().slideToggle('slow').siblings("ul:visible").slideUp('fast');
				$(this).toggleClass('on').siblings('#smenu > h3.on').not('.link').removeClass('on');
			});
		});
	},
	
	// Overflow Scroll Effect on vertical menu
	overflowScrollMenu: function(){

		if( $('#conteneurSmenu').prev('h3').not('.notFixed').is('#titreFriseProduit') ){
			var titreMarginTop = $('#titreFriseProduit').height() + parseInt( $('#titreFriseProduit').css('margin-top') ) + parseInt( $('#titreFriseProduit').css('padding-top') );
		}else{
			var titreMarginTop = ( $('#conteneurSmenu').parent().children().eq(0).is('h2') || $('#conteneurSmenu').parent().parent().children().eq(1).is('h2') )? 0 : 43;
		}
		$('#conteneurSmenu').css( 'margin-top', titreMarginTop+'px' );
		
		var topByDefault = 0;
		var topFromWindow = 136+titreMarginTop;
		$(window).bind('scroll',function(){
			if( typeof( window.pageYOffset ) == 'number' ) {
				//Netscape compliant
				scrOfY = window.pageYOffset;
			} else if( document.body && document.body.scrollTop ) {
				//DOM compliant
				scrOfY = document.body.scrollTop;
			} else if( document.documentElement && document.documentElement.scrollTop ) {
				//IE6 standards compliant mode
				scrOfY = document.documentElement.scrollTop;
			}
			if( scrOfY > topFromWindow ){
				$('#conteneurSmenu').not('.notFixed').animate({top: ( scrOfY - topFromWindow )}, 1 );
			}else if( scrOfY >= 0 &&  parseInt( $('#conteneurSmenu').css('top') ) >= topByDefault ){
				$('#conteneurSmenu').not('.notFixed').animate({top: topByDefault}, 1 );
			}
			
		});
	}
};

var slides = {
	durationSSProduct: 1000,
	durationSSCard: 500,
	
	// Automatic SlideShow Home 
	runSlideShowHome: function(){
		if( $('#conteneurSlidesHome').length > 0 ){
			var slideShowInterval = setInterval('slides.SlideShowHome("#conteneurSlidesHome")',3000);
			$('#numberspage').find('.numberpage').each(function(i){
				$(this).click(function(){
					if(!$(this).hasClass('current')){
						$('#conteneurSlidesHome').find('.slide').removeClass('actual');
						$('#numberspage').find('.numberpage').removeClass('current');
						var _block = $('#conteneurSlidesHome').find('.slide')[i];
						$(_block).addClass("actual");
						$(this).addClass('current');
					}
					clearInterval(slideShowInterval);
				});
			});
		}
	},
	// SlideShow Home
	SlideShowHome: function(container){
		var _active = $(container).find('.actual').length ? $(container).find('.actual') : $(container).find('.slide:last');
		var _next =  _active.next().length ? _active.next() : $(container).find('.slide:first');
		_active.addClass('last-actual');
		_next.css({opacity: 0.0})
			.addClass('actual')
			.animate({opacity: 1.0}, 1000, function() {
				_active.removeClass('actual last-actual');
			});
		
		var _activePager = $('#numberspage').find('.current').length ? $('#numberspage').find('.current') : $('#numberspage').find('.slide:last');
		var _nextPager =  _activePager.next().length ? _activePager.next() : $('#numberspage').find('.numberpage:first');
		_activePager.removeClass('current');
		_nextPager.addClass('current');
	},
	
	// SlideShow Fiche Produits
	SlideShowProduct: function(){
		$('.diaporama').each(function(){
			$(this).children('.nextDiapo').bind('click', function(){
				var diaporama = $(this).parent().children('.ListDiapos');
				if(!diaporama.find('.current').is(':last-child')){
					var _active = $(this).parent().find('.ListDiapos > .diapo.current');
					var decal = parseInt( _active.width() ) + parseInt( _active.css('margin-right') ) + parseInt( _active.css('margin-left') );
					diaporama.animate({marginLeft: '-='+decal},slides.durationSSProduct);
					$(this).parent().find('.ListDiapos > .diapo').removeClass('current');
					_active.next().addClass('current');
				}
			});
			$(this).children('.prevDiapo').bind('click', function(){
				var diaporama = $(this).parent().children('.ListDiapos');
				if(!diaporama.find('.current').is(':first-child')){
					var _active = $(this).parent().find('.ListDiapos > .diapo.current');
					var decal = parseInt( _active.width() ) + parseInt( _active.css('margin-right') ) + parseInt( _active.css('margin-left') );
					diaporama.animate({marginLeft: '+='+decal},slides.durationSSProduct);
					$(this).parent().find('.ListDiapos > .diapo').removeClass('current');
					_active.prev().addClass('current');
				}
			});
		});
	},
	
	// SlideShow Choix Cartes
	SlideShowCard: function(){
		$('#choisirCartes').find('.picto').children('a').bind('click',function(){
			if( !$(this).parent().parent().hasClass('current') ){
				var indexThis = $('#choisirCartes').children('ul').children('li').index( $(this).parent().parent() );
				slides.SlideShowCardEffect( indexThis );
			}
		});
		
		var _paginationLinks = $('#choisirCartes').next('#pagination');
		var _paginateCardLinks = _paginationLinks.children().children('.paginateCard');
		_paginationLinks.find('a').bind('click',function(){
			if( $(this).hasClass('next') ){
				var indexPage = _paginateCardLinks.index( _paginationLinks.children().children('.current') )+1;
			}else if( $(this).hasClass('prev') ){
				var indexPage = _paginateCardLinks.index( _paginationLinks.children().children('.current') )-1;
			}else{
				var indexPage = _paginateCardLinks.index( $(this) );
			}
			_paginateCardLinks.removeClass('current');
			_paginationLinks.find('.paginateCard').eq( indexPage ).addClass('current');
			slides.SlideShowCardEffect( indexPage );
		});
		
		// Pagination with verticals mini-cards
		var _rightLink = $('#choixCard').not('.blocked').children('li').children('a');
		_rightLink.bind('click',function(){
			var indexCurrent = _rightLink.index( $(this) );
			_rightLink.removeClass('current');
			$(this).addClass('current');
			$('#conteneurSlideShow').animate({marginLeft: '-'+(indexCurrent*475)},{queue:true, duration:slides.durationSSCard});;
		});
	},
	// Effect of SlideShow Choix Cartes
	SlideShowCardEffect: function( newIndexCurrent ){
		var _currentLI = $('#choisirCartes').find('.current');
		var _allLI = $('#choisirCartes').children('ul').children('li');
		
		_currentLI.find('.privilege').stop({gotoEnd: true}).fadeOut('fast').attr('style','');
		_currentLI.find('.picto').find('img').stop({gotoEnd: true}).animate({width: '159', height: '125', marginTop: '0'},{queue:false, duration:slides.durationSSCard, complete:function(){
			_currentLI.removeClass('current');
			_allLI.eq( newIndexCurrent ).addClass('current');
			$('#choisirCartes').children('ul').animate({left: '-'+(newIndexCurrent*178)},{queue:true, duration:slides.durationSSCard}).height('260');
			_allLI.eq( newIndexCurrent ).find('.picto').find('img').animate({width: '300', height: '236', marginTop: '-44'},{queue:true, duration:slides.durationSSCard, complete:function(){
				_allLI.eq( newIndexCurrent ).find('.privilege').show().attr('style','');
				_allLI.not('.current').find('.picto').find('img').css('margin-top','0');
			}})
		}});
		$('#choisirCartes').next('#pagination').find('.paginateCard').removeClass('current').eq( newIndexCurrent ).addClass('current');
		slides.HidePrevNext();
	},
	// Hide next or prev links in pagination
	HidePrevNext: function(){
		var _paginationLinks = $('#choisirCartes').next('#pagination');
		var _paginateCardLinks = _paginationLinks.children().children('.paginateCard');
		var _prevLink = _paginationLinks.find('.prev');
		var _nextLink = _paginationLinks.find('.next');
		
		_prevLink.show();
		_nextLink.show();
		if( _paginateCardLinks.index( _paginationLinks.children().children('.current') ) == 0 ){
			_prevLink.toggle();
		}
		if( _paginateCardLinks.index( _paginationLinks.children().children('.current') ) == _paginateCardLinks.length-1 ){
			_nextLink.toggle();
		}
	}
	
};

var popIn = {
	overlayID: 'BgPopup',
	menuID: 'conteneur_menu',
	footerID: 'conteneur_footer',
	menuZIndex: 13,
	popinZIndex: 30,
	
	// Affiche la pop-in
	open: function(){
		$('.openPopIn').bind('click', function(){
 			popIn.maximizeOverlay();
			var popInDiv = 'Div'+functions.ucfirst($(this).attr('id'));
			$('#'+popInDiv).show().addClass('popInOpened');
			$('#'+popIn.menuID).css('z-index', -1);
			$('#'+popIn.footerID).css('z-index', -1);
			// Si on ouvre une nouvelle popin depuis une autre, on passe cette derniÃ¨re derriÃ¨re l'overlay.
			if( $(this).offsetParent().hasClass('popInOpened')){
				$(this).offsetParent().hide().removeClass('popInOpened');
			}
			// On cache les select sous IE6
			if($.browser.msie && $.browser.version < 7){
				$('select').css('visibility', 'hidden');
				$('#'+popInDiv).find('select').css('visibility', 'visible');
			}
			$('#'+popInDiv).find('.closedPopIn').bind('click',function(){
				popIn.closed(popInDiv);
			});
		});
	},
	
	// Affiche la pop-in Panier quand on clique sur "j'achÃ¨te"
	openPanier: function(){
		$('#DivPanier').show().addClass('popInOpened');
		$('#'+popIn.menuID).css('z-index', -1);
		$('#'+popIn.footerID).css('z-index', -1);
		// Si on ouvre une nouvelle popin depuis une autre, on passe cette derniÃ¨re derriÃ¨re l'overlay.
		if( $(this).offsetParent().hasClass('popInOpened')){
			$(this).offsetParent().hide().removeClass('popInOpened');
		}
		// On cache les select sous IE6
		if($.browser.msie && $.browser.version < 7){
			$('select').css('visibility', 'hidden');
			$('#DivPanier').find('select').css('visibility', 'visible');
		}
		$('#DivPanier').find('.closedPopIn').bind('click',function(){
			popIn.closed('DivPanier');
		});
	},
	
	// Ferme la pop-in
	closed: function(container){
		$('#'+popIn.overlayID).hide();
		$('#'+container).hide().removeClass('popInOpened');
		$('#'+popIn.menuID).css('z-index', popIn.menuZIndex);
		$('#'+popIn.footerID).css('z-index', 1);
		// On affiche les select sous IE6
		if($.browser.msie && $.browser.version < 7){
			$('select').css('visibility', 'visible');
		}
	},
	
	// Agrandi l'Overlay pour qu'il prenne tout le body
	maximizeOverlay: function(){
		var bodyWith = $('body').width();
		var windowWith = Math.max($(window).width(), bodyWith, ( ( $.browser.msie && $.browser.version < 8 )? 0 : $('html').width() ) );
		var goToLeft = (windowWith - bodyWith)/2;
		$('#'+popIn.overlayID).height(0).width(0).css('margin-left', 0);
		var h = functions.getDocHeight();
		if (goToLeft > 0){
			$('#'+popIn.overlayID).css('margin-left', -goToLeft);
		}		
		$('#'+popIn.overlayID).height(h).width(windowWith).show();
	},
	
	// Redimentionne l'overlay quand on redimensionne la page
	resizeOverlay: function(){
		$(window).bind('resize', this, function() {
			if( $('#'+popIn.overlayID).css('display') == 'block' ){
				popIn.maximizeOverlay();
			}
		});
	}
};

var accordion = {
	open: function(){
		$('.open').each(function(){
			$(this).bind('click', function(){
				$('.accordion > li').removeClass('visible');
				$(this).parent().addClass('visible');
			});
		});
	},
	
	close: function(){
		$('.close').each(function(){
			$(this).bind('click', function(){
				$('.accordion > li').removeClass('visible');
			});
		});
	}
};

var callAjax = {
	// Appel Ajax quand on clique sur "j'achÃ¨te"
	buy: function(){
		$('.openPanier').bind('click', function(){
			$.ajax({
				type: 'GET',
//				url: 'http://gl-recette.cyo.fr/index.php',
				url: 'index.php',
				data: 'nv=panier_deroulant&action=add&language=fr',
				beforeSend: function() {
					popIn.maximizeOverlay();
				},
				success: function(msg) {
					popIn.openPanier();
				}
			});
		});
	}
};

$(document).ready(function (){
	menus.mainMenu();
	menus.verticalMenu();
	menus.overflowScrollMenu();
	functions.clearInputText();
	slides.runSlideShowHome();
	slides.SlideShowProduct();
	slides.SlideShowCard();
	slides.HidePrevNext();
	popIn.open();
	popIn.resizeOverlay();
	accordion.open();
	accordion.close();
	callAjax.buy();
	functions.hideLogo();
});