(function(jQuery) {
	
	var productParam = {
		urlProduct : '',
		sku : ''
	}
	
	var scene7isVisible = false;
	var mouseisoutquickview = false;
	var productAddToCartFormForIe;
	
/*  // ================================================ \\
   || ========== get product page with ajax =========== || 
   \\ ================================================ // */
	
	var openQuickview = function(e) {
		productParam.urlProduct = e.href;
		jQuery.ajax({
			url: productParam.urlProduct,
			beforeSend : function() {
				jQuery('#quickview').html('');
				jQuery('#quickview').hide();
				jQuery('.category-products').show();
				if(jQuery('.loader-quickview').length == 0){
					jQuery('body').append('<div class="loader-quickview"></div>');
				}else {
					jQuery('.loader-quickview').show();
				}
			},
			success: function( data ) {
				jQuery('.loader-quickview').hide();
				jQuery('#mask-quickview').show();
				
				//on cache la liste des produits
				jQuery('.bloc-infos-product').hide();
				jQuery('.category-products').hide();
				
				var page = jQuery(data).find('.page');
				
				jQuery('#quickview').html(page);
				jQuery('#quickview').show();
				
				//récupère des datas necessaires pour la séléction des couleurs
				var data = jQuery(page).find('#data');
				var incr = jQuery(data).data('incr');
				var initSku = jQuery(data).data('initsku');
				var initId = jQuery(data).data('initid');
								
				
				//Initialisation des fonctions necessaires à l'ajout au panier
				var productAddToCartForm = new VarienForm('product_addtocart_form');

				loadCartFunctions(productAddToCartForm);
				 
				//Initialisation des fonctions necessaires au slider
				loadSliderFunctions(incr, initSku);
			
				//PLUS DE VUE
				jQuery('.link-more-views a').live('click', function() {
					changeImage(jQuery(this).data('sku'));
					
					jQuery(page).find('.more-view').show();
			   		jQuery(page).find('.more-view img').hide();
					rel = jQuery(this).attr('rel');
					jQuery(rel).show();
				});
				
				//INIT SCENE7
				jQuery('.scene7zoom').live('click', function() {
					getScene7()
				});
				
				initZoom(initSku);

				//AFFICHAGE DES BOUTONS SOCIAUX				
				initSocialButtons();
				
				//SI ON AJOUTE AU PANIER ET QU'AJAXCARTPRO EST DESACTIVÉ
				jQuery('.btn-cart').live('click', function(){
					productAddToCartForm.submit(this);
				});
								
			},
			complete: function () {
				//On cache le loader et on ajoute le lien fermer
				jQuery('.loader-quickview').fadeOut();
				jQuery('#quickview .product_right').append('<a href="" title="close" class="close">FERMER</a>');
			}
			
		});
	}
	
	/* 
	* Init des fonctions pour le slider de couleur
	*/
	var loadSliderFunctions = function(incr, initId) {
		jQuery('#slides .loader').each(function(){
				
			var str = jQuery(this).attr('rel');
			var currentLoader = jQuery(this);
			var img = new Image();
			  
			jQuery(img).load(function () {
			
				jQuery(currentLoader).hide();
				//jQuery(currentLoader+' img:eq(0)').remove();
				jQuery(currentLoader).removeClass('loading').append(this);
				
				jQuery(currentLoader).fadeIn();
			
			}).error(function () { /* ?? */ }).attr('src', str);
		});

		jQuery("#slider-color").scrollable({
			horizontal: true,
			circular: false
		}).navigator(".picto-colors");

       
		 var api = jQuery("#slider-color").data("scrollable");
		 
		 api.seekTo(incr);
		
		// On Seek EVENT 
		api.onSeek(function() {

			var target='.link-color:eq('+this.getIndex()+')';
			refreshColorValue(target);
							
		});
		
		jQuery("#attribute80").val(initId);

	}
	
	/* 
	* Init des fonctions pour l'ajout au panier
	*/
	var loadCartFunctions = function(productAddToCartForm) {
		
		// CONFIGURATION DE L'AJOUT AU PANIER STANDARD		
		productAddToCartForm.submit = function(button, url) {
			if (this.validator.validate()) {
			        var form = this.form;
			        var oldUrl = form.action;
			
			        if (url) {
			           form.action = url;
			        }
			        var e = null;
			        try {
			            this.form.submit();
			        } catch (e) {
			        }
			        this.form.action = oldUrl;
			        if (e) {
			            throw e;
			        }
			
			        if (button && button != 'undefined') {
			            button.disabled = true;
			        }
			    }
			    return false;
			}.bind(productAddToCartForm);

		
		//Pour qu'ajaxcartpro fonctionne, on doit relancer certaines fonctions (copier/coller de js/ajaxcartpro/ajaxcartpro-1.4.6.js)
		function addSubmitEvent(){
		    if (typeof productAddToCartForm != 'undefined'){
		        productAddToCartForm.submit = function(url){
		            if(this.validator && this.validator.validate()){
		                ajaxcartsend('?awacp=1', 'form', this, '');
		            }
		            return false;
		        }
		
		        productAddToCartForm.form.onsubmit = function() {
		            productAddToCartForm.submit();
		            return false;
		        };
		    }
		}
		
		if(!Prototype.Browser.IE6){
		    var cnt1 = 20;
			__intId = setInterval(
				/* Hangs event listener for @ADD TO CART@ links*/
				function(){
					cnt1--;
					if(typeof productAddToCartForm != 'undefined'){
						try {
							// This fix is applied to magento <1.3.1
		                    $$('#product_addtocart_form '+aw_addToCartButtonClass).each(function(el){
		                        el.setAttribute('type', 'button')
		                    })
						}catch(err){}
						
		                if (AW_ACP.hasFileOption == false) addSubmitEvent();
		                
						clearInterval(__intId);
					}
					if(!cnt1) clearInterval(__intId);
				},
				500
			);
		
			var cnt2 = 20;
			__intId2 = setInterval(
				/* This hangs event listener on @DELETE@ items from cart*/
				function(){	
					cnt2--;
					if(typeof aw_cartDivClass!= 'undefined' && $$(aw_cartDivClass).length || ((typeof AW_ACP !== 'undefined') && AW_ACP.isCartPage)){
		                updateDeleteLinks();
						clearInterval(__intId2);
					}
					if(!cnt2) clearInterval(__intId);
				},
				500
			);
		}
	}
	
	/* 
	* Placement des boutons sociaux et change fait pointer les url vers la page produit
	*/
	var initSocialButtons = function() {
		var socialButton = jQuery('#social-button').clone();
		jQuery('#social-bookmarking').html('').append(socialButton);
		
		//on change l'url de googleplus avec l'url de la page produit
		var gplusUrlVars = jQuery.getUrlVars(jQuery(socialButton).children('#___plusone_0').children().attr('src'));
		var gplusId = jQuery(socialButton).children('#___plusone_0').children().attr('id');
		gplusUrlVars.url = encodeURIComponent(productParam.urlProduct);
		var newUrlGplus = 'https://plusone.google.com/u/0/_/+1/fastbutton?url='+gplusUrlVars.url+'&size='+gplusUrlVars.size+'&count='+gplusUrlVars.count+'&annotation='+gplusUrlVars.annotation+'&hl='+gplusUrlVars.hl+'&jsh='+gplusUrlVars.jsh+'='+gplusId+'&parent='+gplusUrlVars.parent+'&rpctoken='+gplusUrlVars.rpctoken+'&_methods='+gplusUrlVars._methods;
		jQuery(socialButton).children('#___plusone_0').children().attr('src', newUrlGplus);
		
		//on change l'url de twitter
		var twitterUrlVars = jQuery.getUrlVars(jQuery(socialButton).children('.twitter-share-button').attr('src'));
		twitterUrlVars.url = encodeURIComponent(productParam.urlProduct);
		var newTwitterUrl = 'http://platform.twitter.com/widgets/tweet_button.html?count='+twitterUrlVars.count+'&id='+twitterUrlVars.id+'&lang='+twitterUrlVars.lang+'&original_referer='+twitterUrlVars.original_referer+'&text='+twitterUrlVars.text+'&url='+twitterUrlVars.url+'&via='+twitterUrlVars.via;
		jQuery(socialButton).children('.twitter-share-button').attr('src', newTwitterUrl);
		
		//on change l'url de facebook
		var facebookUrlVars = jQuery.getUrlVars(jQuery(socialButton).children('.facebook').attr('src'));
		facebookUrlVars.href = encodeURIComponent(productParam.urlProduct);
		var newFacebookUrl = 'http://www.facebook.com/plugins/like.php?app_id='+facebookUrlVars.app_id+'&href='+facebookUrlVars.href+'&send='+facebookUrlVars.send+'&layout='+facebookUrlVars.layout+'&width='+facebookUrlVars.width+'&show_faces='+facebookUrlVars.show_faces+'&action='+facebookUrlVars.action+'&colorscheme'+facebookUrlVars.colorscheme+'&font='+facebookUrlVars.font+'&height='+facebookUrlVars.height;
		jQuery(socialButton).children('.facebook').attr('src', newFacebookUrl);
		
		//on affiche les boutons sociaux
		jQuery(socialButton).removeClass('no-display');
	}
	
	var changeImage = function(imageSku) {
		productParam.sku = imageSku;
		//console.log('changeImage -> '+sku);
		return false;
	}
	
	var initZoom = function(initSku) {
		productParam.sku = initSku;
	}
	
	var changeColor = function(colorSKU) {
		productParam.sku = colorSKU;
		return false;
	}
	
	var getScene7 = function() {
		scene7isVisible = true;
		
		//on enlève la position absolute de la quickview.
		var flashvars = {
				serverUrl:"http://lancaster.scene7.com/is/image/",
			    contentRoot:"http://lancaster.scene7.com%2fskins",
				image:"Lancaster%2F" + productParam.sku,
				config:"Lancaster/yb",
				contentRoot:"/skins/"
		};
	 
		var params = {
		        menu: "false",
		        quality: "high",
		        scale: "noscale",
		        salign: "LT",
		        bgcolor: "#ffffff",
		        allowScriptAccess: "always",
		        wmode: "#FFF"
		};
		
		swfobject.embedSWF("http://lancaster.scene7.com/skins/Lancaster/ZoomLancaster2011/ZoomLancaster_Final_07092011.swf", "scene7Container", "100%", "100%", "9.0.0", "http://www.lancaster.fr/scene7/expressInstall.swf", flashvars, params);
		
		return false;
	}
 

	
	var closeQuickview = function() {
		jQuery('#quickview').fadeOut(10, function() {
			jQuery('#mask-quickview').hide();
			jQuery('.category-products').show();
			document.body.style.cursor = 'default';
			mouseisoutquickview = false;
		});

	}
	
	var  refreshColorValue  = function(target){
		
		jQuery('.link-color').removeClass('selected');
			jQuery(target).addClass('selected');
			jQuery("#attribute80").val(jQuery(target).attr("id"));
			jQuery('.message-out-of-stock').css("visibility","hidden");
			jQuery('.add-to-cart').show();
			jQuery('.more-view').hide();
			var sku = jQuery(target).attr('rel');
			changeColor(sku);
			
			if(jQuery(target).hasClass('outofstock'))
			{
				jQuery('.message-out-of-stock').css("visibility","visible");
				jQuery('.add-to-cart').hide();
			}

	
	}
	
	
	
	jQuery('document').ready(function() {
		jQuery('body').append('<div id="mask-quickview"></div>');

		// ! La quickview part d'ici		
		jQuery('.category-caroussel a').live('click', function(e) {
				e.preventDefault();
				//par précaution on cache toute les div "bloc-infos-product"

				//on affiche la quickview
				openQuickview(this);
			});
			
		//SI ON CLICK SUR UN PRODUIT RELATIF, ON RELOAD LA QUICKVIEW
		jQuery('#quickview #block-related a').live('click', function(e) {
			e.preventDefault();
			openQuickview(this);
		});
				
		// Function CLICK sur les couleurs
	    jQuery('.link-color').live('click', function() {
				refreshColorValue(this);
		});
		
		// Function mouseOver/out sur plus de vue
		jQuery(".link-more-views").live("mouseover mouseout", function () {
			jQuery('.link-more-views ul').css("visibility","visible");
			}, function () { /* Out */ }
		);
		
		//FERME LA QUICKVIEW au click sur le bouton close
		jQuery('#quickview .close').live('click', function(e) {
				e.preventDefault();
				closeQuickview();
		});
		
		//FERME LA QUICKVIEW ou le zoom quand on appuie sur escape
		jQuery(document).keyup(function(e) {
			if (e.keyCode == 27 && jQuery('#quickview').is(':visible') ) {
				if(scene7isVisible){ close(); }
				else closeQuickview();
			}
		});
		
		
		//FERME LA QUICKVIEW AU CLICK A L'EXTERIEUR DE CELLE-Ci		
		jQuery('#mask-quickview').live('mouseover', function() {
			if(jQuery('#quickview').is(':visible')) {
				document.body.style.cursor = 'pointer';
				mouseisoutquickview = true;

			}
		});
		
		jQuery('#quickview').live('mouseover', function() {
				document.body.style.cursor = 'default';
				mouseisoutquickview = false;

		});
		
		jQuery(document).bind('click', function() {
			if(mouseisoutquickview && jQuery('#quickview').is(':visible')) { closeQuickview(); }
		});

		
		//set scene7isVisible à false depuis les fichiers list.phtml et list-query.phtml
		jQuery(document).bind('setSceneSevenToFalse', function() {
			 scene7isVisible = false; 
		});
		
		/* fix for IE6 et 7 : on doit rebinder le click de l'ajout au panier dans le dom ready et relancer les fonctions d'ajout au panier */
		if(Prototype.Browser.IE6 || Prototype.Browser.IE7) {
			jQuery('.add-to-cart .btn-cart').live('click', function(){
				var formIe = new VarienForm('product_addtocart_form');
				loadCartFunctions(formIe);
				formIe.submit(this);
				
			});
		}
	});
	
  
   // !! AUCUN CODE ICI !! \\
 
   
})(jQuery);
