// Gestion du zoom de la page produit
$(window).load(function() {
    
	var slider = $("#sheet-content-slider"),         // Slider de la page product
	    images = slider.find(".product-small"),      // Et ses images
	    target = $("#sheet-content .product-large"), // Cible des minis
	    
	    minLen = 4,     // Nombre d'images minimum pour activer le scroll
	    moving = false, // En mouvement ?
	    arrOvr = null,  // Contient la flèche sur lequel le mouseover est actif
        
        clsEnb = "sheet-content-slider-ctrl-in",  // Controleur actif
        clsDsb = "sheet-content-slider-ctrl-out", // Controleur inactif
        idBack = "sheet-content-slider-back",     // Id controleur arrière ou haut
        idNext = "sheet-content-slider-next",     // Id controleur avant ou bas
        idView = "sheet-content-slider-view",     // Id fenêtre mouvante
        
	    move, // Hauteur de base
	    back, // Bouton vers le haut
	    next, // Bouton vers le bas
	    view, // Fenêtre mouvante
	    last; // Dernière image chargée
    
    // Animation du view port
	function slide() {
		arrOvr = this;
		
        if(this.className.indexOf("out") < 0) {
    	    var dir = this.id == idBack ? 1: -1,
    	        top = parseInt(view.css("top"));
            
    	    if(!moving) {
    	        moving = true;
               
    	        view.animate(
                    { top: top + (dir * move) },
                    { complete: slided, duration: "fast" }
    	        );
            }
        }
	}
	
	function slideOff() {
		arrOvr = null;
	}
    
    // Gestion des controlleurs (flèches haut et bas)
    function slided() {
        var top = parseInt(view.css("top"));
            moving = false;
            
        // max
        -top >= move * (images.length - minLen) ?
            next.removeClass(clsEnb).addClass(clsDsb):
            next.removeClass(clsDsb).addClass(clsEnb);
            
        // min
        top == 0 ?
            back.removeClass(clsEnb).addClass(clsDsb):
            back.removeClass(clsDsb).addClass(clsEnb);
        
        if(arrOvr)
        	slide.call(arrOvr);
    }
    
    // Détermine la hauteur de base
    function getHeight() {
        return images.eq(0).outerHeight(true);
    }
    
    if(images.length > minLen) {
	    back = $("<div />").attr("id", idBack).addClass(clsDsb).hover(slide, slideOff);
	    next = $("<div />").attr("id", idNext).addClass(clsEnb).hover(slide, slideOff);
	    view = $("<div />").attr("id", idView).append(images).appendTo(slider);
        move = getHeight();
        
	    // Hauteur de base
        if(!move) {
    	    images.eq(0).find("img").load(function() {
    	        move = getHeight();
    	    });
        }
        
        slider.before(back).before(next);
	}
    
    // Clic sur une image
    // On met à jour l'url de la grande photo
    images.find("a").mouseover(function(e) {
        target.find("a").attr("href", $(this).attr("href"));
        target.find("img:last").attr("src", $(this).attr("rel"));
    });
    
    images.find("a").click(function(e) {
    	e.preventDefault();
    	return false;
    });
    
    // Clic sur la grande photo
    // On collection les url et on démarre le slideshow
    target.find("a").click(function(e, s) {
        var a = [], i = 0,
        	tsrc = target.find("img:last").attr("src");
        
        images.each(function(j) {
        	var tmb = $(this).find("img").attr("src"),
        		prv = $(this).find("a").attr("href");
        	
        	a.push([tmb, prv]);
        	
        	if(tsrc == $(this).find("a").attr("rel")) {
        		i = j;
        	}
        });
        
        $.edlesLayer.slideShow({
        	title: "Diaporama " + $("#sheet-content-details h1").text()
        }, a, i);
        
        e.preventDefault();
    });
    
});

// Gestion du slide de la home
$(window).load(function() {
    
    var metadt = $("#home-slider-meta").text().split("-"),
        slider = $("#home-slider-viewport"),
        groups = slider.find(".home-slider-group").hide(),
        rotate = parseInt(metadt[0]),
        fademx = parseInt(metadt[1]),
        fademn = parseInt(metadt[2]),
        linkon = "home-slider-link-on",
        fading = false,
        
        links = slider.find(".home-slider-link"),
        timer = 0,
        index = 0;
    
    function timeout() {
        next();
        timer = setTimeout(timeout, rotate);
    }
    
    function goTo(i) {
        if(!fading && index != i) {
            clearTimeout(timer);
            
            fading = true;
            timer  = setTimeout(timeout, rotate);
            
            groups.eq(index).css("z-index", 2).fadeOut(fademn, off);
            groups.eq(index = i).css("z-index", 1).show();
            
            link(i);
        }
    }
    
    function off() {
        fading = false;
        $(this).hide();
    }
    
    function next() {
        var group = groups.eq(index),
            nxgrp = groups.eq(index + 1).length ? groups.eq(++index): groups.eq(index = 0);
        
        fading = true;
        group.css("z-index", 2).fadeOut(fademx, off);
        nxgrp.css("z-index", 1).show();
        
        link(index);
    }
    
    function link(i) {
        links.removeClass(linkon).eq(i).addClass(linkon);
    }
    
    if(groups.length > 1) {
        timer = setTimeout(timeout, rotate);
        link(index);
        
        links.click(function() {
            goTo(links.index(this));
        });
    } else {
        links.remove();
    }
    
    groups.eq(index).show();

});

// Gestion des popup souris
$.fn.mouseLayer = (function() {
	
	var layer = $("<div />").attr("id", "mouseLayer").css("opacity", 0).hide(),
		onair = false,
		animt = false,
		delay = 500,
		durtn = 150,
		offsX = 9,
		offsY = -9,
		offsT = 10,
		opcMn = 0,
		opcMx = 0.95,
		currE = null,
		currT = null;
	
	$(function() {
		$("body").append(layer);
	});
	
	// Démarre le timer
	function layerStart(ml) {
		return function(e) {
			currT = setTimeout(function() {
				layer.html(ml.content.html());
				layer.width(ml.content.width() || "auto");
				layer.height(ml.content.height() || "auto");
				layerShow(e);
			}, delay);
		};
	}
	
	// Affiche le layer
	function layerShow(e) {
		onair = true;
		
		layerMove(currE || e);
		
		var top = parseInt(layer.css("top"));
		layer.css("top", top - offsT)
		
		layer
			.show()
			.animate({
				opacity: opcMx,
				top: top
			}, {
				queue: false,
				duration: durtn
			});
	}
	
	// Cache le layer
	function layerHide() {
		onair = false;
		
		layer.animate({
			opacity: opcMn,
			top: parseInt(layer.css("top")) + offsT
		}, {
			queue: false,
			duration: durtn,
			complete: function() {
				layer.hide();
			}
		});
	}
	
	// Bouge le layer
	function layerMove(e) {
		if(!onair) {
			currE = e;
		} else {
			layer.css({
				left: e.pageX + offsX,
				top: e.pageY + offsY - layer.outerHeight()
			});
		}
	}
	
	function MouseLayer(el, content, eventOn, eventOff) {
		this.element = $(el);
		this.content = $(content);
		
		this.element
			.bind(eventOn, layerStart(this))
			.bind(eventOff, function() { clearTimeout(currT); layerHide(); })
			.bind("mousemove", layerMove);
	}
	
	return function(content, eventOn, eventOff) {
		if(content == "close") {
			layerHide();
		} else {
			new MouseLayer(this, content, eventOn, eventOff);
		}
		
		return this;
	};
	
})();

// Popup edles

$.edlesLayer = (function() {
	
	var SLIDESHOW =
		'<div id="edlesLayer-body-selected"></div>' +
		'<div id="edlesLayer-body-preview" style="float: right" class="product product-xxlarge">' +
			'<img src="" class="product-picture block" />' +
		'</div>' +
		'<div id="edlesLayer-body-thumbs"></div>';
	
	var SLIDESHOW_PIC =
		'<div class="product product-small">' +
			'<a href="#"><img src="" class="product-picture block" /></a>' +
		'</div>';
	
	var layer   = null,
		content = null,
		height  = 0,
        offHgt  = -20,
		animate = false,
		opened  = false,
		cache   = {},
        onclose = null;
	
	$(function() {
		layer   = $("#edlesLayer");
		content = layer.find("#edlesLayer-body");
		height  = layer.height();
		
		$("#edlesLayer-head-close, #edlesLayer-cover").click(function() {
            onclose = null;
            $.edlesLayer.close();
        });
	});
    
    function decode(title) {
        return title
            .replace(/\&eacute;/g, "é")
            .replace(/\&agrave;/g, "à");
    }
	
	return {
	
		open: function(options) {
			if(!animate && !opened) {
				$("#edlesLayer-head-title").text(decode(options.title));
				$("#edlesLayer-body").html(options.body)
				
                if(options.close)
                    onclose = options.close;
                
				// Animation
				animate = true;
				opened  = true;
				
				$("#edlesLayer-cover")
					.css("opacity", 0)
					.show()
					.animate({ opacity: 0.6 });
				
				layer.animate({
					top: 0
				}, {
					complete: function() {
						animate = false;
						if(options.callback) options.callback();
					}
				});
			}
		},
		
		close: function(e) {
			if(!animate && opened) {
				// Animation
				animate = true;
				
				$("#edlesLayer-cover").fadeOut(function() {
					$(this).hide();
				});
				
				layer.animate({
					top: -height + offHgt
				}, {
					complete: function() {
						animate = false;
						opened  = false;
						
                        if(e && typeof e == "function") {
                            e();
                        } else if(onclose) {
                            onclose();
                            onclose = null;
                        }
                        
                        content.empty();
					}
				});
			}
		},
		
		slideShow: function(options, images, index) {
			var div = $("<div />").html(SLIDESHOW),
				tmb = div.find("#edlesLayer-body-thumbs"),
				img = div.find("img");
			
			for(var i = 0; i < images.length; i++) {
				var p = $(SLIDESHOW_PIC);
				
				p.find("img").attr("src", images[i][0])
				p.find("a").attr("rel", images[i][1]);
				
				tmb.append(p);
			}
			
			div.find(".product-small").click(function() {
				img.attr("src", $(this).find("a").attr("rel"));
				$(this).append($("#edlesLayer-body-selected").show());
			});
			
			var cb = options.callback;
			
			options.callback = function() {
				div.find(".product-small").eq(index).click();
				if(cb) cb();
			};
			
			options.body = div;
			$.edlesLayer.open(options);
		},
		
		load: function(url, options, sub) {
			if(cache[url]) {
                options.body = cache[url];
				$.edlesLayer.open(options);
                
                if(options.nocache)
                    delete cache[url];
			} else {
                if(options.iframe) {
                    content.html("").append(
                        $("<iframe />").attr("src", url).load(function() {
                            $.edlesLayer.open(options);
                        })
                    );
                } else {
                    $.get(url, options.nocache ? { ts: new Date().getTime() }: null, function(resp) {
                        cache[url] = (sub ? $(resp).find(sub): $(resp)).html() || " ";
    					$.edlesLayer.load(url, options);
    				});
                }
			}
		},
        
        empty: function(close, fn) {
            content.html("");
            if(close) {
                $.edlesLayer.close(null, fn);
            }
        }
		
	};
	
})();




































