/*
	Slimbox v1.71 - The ultimate lightweight Lightbox clone
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
var dragParams = {
	sImageResize: true
};
var Slimbox = (function() {

	var win = window, ie6 = Browser.Engine.trident4, options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, galleryContainer, bottom, caption, number,
	fxOverlay, fxResize, fxImage, fxBottom, elDrag;

	win.addEvent("domready", function() {
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "lbOverlay", events: {click: close}}),
				galleryContainer = $("lbGalleryContainer"),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			).setStyle("display", "none")
		);

		image = new Element("div", {id: "lbImage"}).injectInside(center).adopt(
			sizer = new Element("div", {styles: {position: "relative"}})
		);
		sizer.adopt(
			new Element("a", {id: "lbZoomLink", href: "#", 'class': 'zoom_in'})
		);
		sizer.adopt(
			new Element("a", {id: "lbCloseLink", href: "#", events: {click: close}})
		);

		$("lbZoomLink").addEvent("click", function() {
			changeImage(activeImage, true);
			return false;
		});
		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			caption = new Element("div", {id: "lbCaption"}),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {id:"lbNavigator"}).adopt(
				prevLink = new Element("a", {id: "lbPrevLink", href: "#", events: {click: previous}}),
				nextLink = new Element("a", {id: "lbNextLink", href: "#", events: {click: next}})
			)
		);
		var el = $$("#lbGalleryContainer .pg_navigator div")[0];
		elDrag = new Drag.Move(el, {
			container: $$("#lbGalleryContainer .pg_navigator")[0],
			onDrag:function(el, ev) {
				var currX = el.offsetLeft - elDrag.limit["x"][0];
				var currY = el.offsetTop - elDrag.limit["y"][0];
				var x, y;
				if (elDrag.limit["x"][1] - elDrag.limit["x"][0] == 0) {
					x = 0
				} else {
					x = dragParams.imgW * currX / (elDrag.limit["x"][1] - elDrag.limit["x"][0]);
				}
				if (elDrag.limit["y"][1] - elDrag.limit["y"][0] == 0) {
					y = 0
				} else {
					y = dragParams.imgH * currY / (elDrag.limit["y"][1] - elDrag.limit["y"][0]);
				}
				image.setStyles({backgroundPosition: (-x) + "px " + (-y) + "px"});
			}
		});
		el.setStyle("opacity",.6);
	});

	function position() {
		var scroll = win.getScroll(), size = win.getSize();
		$$(center, bottomContainer, $("lbGalleryContainer")).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	}

	function setup(open) {
		["object", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});
		overlay.style.display = open ? "" : "none";
		var fn = open ? "addEvent" : "removeEvent";
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		var code = event.code;
		// Prevent default keyboard action (like navigating inside the page)
		return options.closeKeys.contains(code) ? close()
			: options.nextKeys.contains(code) ? next()
			: options.previousKeys.contains(code) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex, v) {
		if (imageIndex >= 0) {
			if (v === true) {
				dragParams.sImageResize = !dragParams.sImageResize;
			} else {
				dragParams.sImageResize = true;
			}
			activeImage = imageIndex;
			activeURL = images[imageIndex][0];
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);
			stop();
			center.className = "lbLoading";
			preload = new Image();
			preload.onload = animateBox;
			preload.src = activeURL;
		}

		return false;
	}

	function animateBox() {
		center.className = "";
		var dSize = document.body.getSize();
		var showNav = false;
		dragParams.imgW = xw = preload.width;
		dragParams.imgH = xh = preload.height;
		var showZoom = false;
		if (dragParams.sImageResize) {
			if (preload.width > dSize.x - 300) {
				var ww = dSize.x - 300;
				var hh = ww * preload.height /  preload.width;
				preload.width = ww;
				preload.height = hh;
				showZoom = true;
			}
			if (preload.height > dSize.y - 140) {
				var hh = dSize.y - 140;
				var ww = hh * preload.width /  preload.height;
				preload.width = ww;
				preload.height = hh;
				showZoom = true;
			}
		} else {
			if (preload.width > dSize.x - 300) {
				var tmpW = dSize.x - 300;
				preload.width = tmpW;
				showNav = true;
			}
			if (preload.height > dSize.y - 140) {
				var tmpH = dSize.y - 140;
				preload.height = tmpH;
				showNav = true;
			}
			showZoom = showNav;
			dragParams.imgW -= preload.width;
			dragParams.imgH -= preload.height;
		}
		var B = $$("#lbGalleryContainer .pg_navigator")[0];
		if (showNav) {
			var tmpImg = B.getChildren("img")[0];
			tmpImg.src = activeURL;
			B.setStyle("display","block");
 			var el = B.getElementsByTagName("div")[0];
 			el.setStyles({left:"",top:""});
 			//alert(preload.width + " - " + B.offsetWidth + " - " + xw)
 			ew = preload.width * tmpImg.offsetWidth / xw;
 			eh = preload.height * tmpImg.offsetHeight / xh;
 			el.style.width = ew + "px";
 			el.style.height = eh + "px";
		} else {
			B.setStyle("display", "none");
		}
		if (showZoom) {
			var elZoom  = $("lbZoomLink");
			elZoom.style.display = '';
			elZoom.removeClass("zoom_in");
			elZoom.removeClass("zoom_out");
			if (dragParams.sImageResize) {
				elZoom.addClass("zoom_in");
			} else {
				elZoom.addClass("zoom_out");
			}
		} else {
			$("lbZoomLink").style.display = 'none';
		}

		if (preload.width < 200) preload.width = 200;
		fxImage.set(0);
		sizer.setStyle("width", preload.width);
		$$(sizer).setStyle("height", preload.height);

		if (dragParams.sImageResize) {
			var rsImg = image.getElementsByTagName("div")[0].getElementsByTagName("img")[0];
			if (!rsImg) {
				rsImg = document.createElement("img");
				image.getElementsByTagName("div")[0].appendChild(rsImg);
				rsImg.style.width = '100%';
				rsImg.style.height = '100%';
				rsImg.style.position = 'absolute';
				rsImg.style.left = '0px';
				rsImg.style.top = '0px';
				rsImg.style.zIndex = '-1';
			}
			rsImg.src = activeURL;
			image.setStyles({background:"none",display: ""});
		} else {
			var tImg = image.getElementsByTagName("div")[0].getElementsByTagName("img")[0];
			if (tImg) {			
				image.getElementsByTagName("div")[0].removeChild(tImg);
			}
			image.setStyles({backgroundImage: "url(" + activeURL + ")", display: ""});
			image.setStyles({backgroundPosition: "0px 0px"});
		}
		caption.set("html", images[activeImage][1] || "");
		number.set("html", (((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));
		if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
		if (nextImage >= 0) preloadNext.src = images[nextImage][0];
		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight;
		var top = Math.max(0, middle - (centerHeight / 2)) - 20, check = 0, fn;
		if (center.offsetHeight != centerHeight) {
			check = fxResize.start({height: centerHeight, top: top});
		}
		$("lbGalleryContainer").setStyle("top", top + "px");
		if ($("lbGalleryContainer").getStyle("display") == "none") {
			$("lbGalleryContainer").setStyle("display", "");
			var lbG = $$("#lbGalleryContainer .imglist_vert img");
			lbG.each(function(itm){
				if (itm.offsetWidth > 80) {
					itm.setStyle("width", "80px");
				}
			});
		}

		if (Browser.Engine.trident === true && Browser.Engine.version <= 5) {
			var xLeft = ((dSize.x - centerWidth) / 2 + $("lbGalleryContainer").offsetWidth / 2);
			$("lbGalleryContainer").setStyle("left", (xLeft - $("lbGalleryContainer").offsetWidth - 4) + "px");
		} else {
			var mLeft = $("lbGalleryContainer").offsetWidth / 2;
			$("lbGalleryContainer").setStyle("margin-left", (-4 + mLeft - $("lbGalleryContainer").offsetWidth -centerWidth/2) + "px");
		}

		if (center.offsetWidth != centerWidth) {
			if (Browser.Engine.trident === true && Browser.Engine.version <= 5) {
				check = fxResize.start({width: centerWidth, marginLeft:0, left: xLeft});
			} else {
				check = fxResize.start({width: centerWidth, marginLeft: mLeft - centerWidth/2});
			}
		}
		fn = function() {
			if (Browser.Engine.trident === true && Browser.Engine.version <= 5) {
				bottomContainer.setStyles({width: centerWidth, top: top + centerHeight, left: xLeft, visibility: "hidden", display: ""});
			} else {
				bottomContainer.setStyles({width: centerWidth, top: top + centerHeight, marginLeft: mLeft-centerWidth/2, visibility: "hidden", display: ""});
			}
			fxImage.start(1);
		};
		if (check) {
			fxResize.chain(fn);
		} else {
			fn();
		}
	}

	function animateCaption() {
		if (prevImage >= 0) prevLink.style.display = "";
		if (nextImage >= 0) nextLink.style.display = "";
		fxBottom.set(-bottom.offsetHeight).start(0);
		bottomContainer.style.visibility = "";
		
	}

	function stop() {
		preload.onload = $empty;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
	}

	function close() {
		if (activeImage >= 0) {
			stop();
			activeImage = prevImage = nextImage = -1;
			center.style.display = "none";
			fxOverlay.cancel().chain(setup).start(0);
			$("lbGalleryContainer").setStyle("display", "none");
		}

		return false;
	}

	Element.implement({
		slimbox: function(_options, linkMapper) {
			$$(this).slimbox(_options, linkMapper);
			return this;
		}
	});

	Elements.implement({
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;
			var pgImages = [];
			var x = 0;
			links.each(function(itm){
				pgImages[x++] = itm.getChildren("img")[0].src;
			});

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredLinks = links.filter(linksFilter, this);
				return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options, pgImages);
			});
			return links;
		}
	});

	return {
		open: function(_images, startImage, _options, pgImages) {
			options = $extend({
				loop: false,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// false uses the mootools default transition
				initialWidth: 250,			// Initial width of the box (in pixels)
				initialHeight: 250,			// Initial height of the box (in pixels)
				imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
				captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
				counterText: "Image {x} of {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
				closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
				previousKeys: [37, 80],			// Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
				nextKeys: [39, 78]			// Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
			}, _options || {});

			// Setup effects
			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});
			fxResize = new Fx.Morph(center, $extend({
				duration: options.resizeDuration, link: "chain"}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			fxImage = new Fx.Tween(image, {property: "opacity", duration: options.imageFadeDuration, onComplete: animateCaption});
			fxBottom = new Fx.Tween(bottom, {property: "margin-top", duration: options.captionAnimationDuration});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [[_images, startImage]];
				startImage = 0;
			}


			middle = win.getScrollTop() + (win.getHeight() / 2);
			centerWidth = options.initialWidth;
			centerHeight = options.initialHeight;
			center.setStyles({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2, display: ""});
			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			fxOverlay.set(0).start(options.overlayOpacity);

			var lbG = $$("#lbGalleryContainer .imglist_vert div")[0];
			lbG.innerHTML = "";

			if (pgImages.length > 1) {
				var i = 0;
				pgImages.each(function(itm){
					var el = new Element("img", {src: itm, alt: ""});
					el.addEvent("click", function(i) {
						changeImage(i);
					}.pass(i++));
					lbG.adopt(el);
				});
				$$("#lbGalleryContainer table")[0].style.display = '';
			} else {
				$$("#lbGalleryContainer table")[0].style.display = 'none';
			}
			var myFxVertSB=new Fx.Scroll($$("#lbGalleryContainer .imglist_vert")[0], {
				duration:400,
				wait:false
			});
			$$("#lbGalleryContainer .product_pg input.top")[0].addEvent("click", function(){
				var s=$$("#lbGalleryContainer .imglist_vert")[0].getScroll();
				myFxVertSB.start(0, s.y-100);
			});
			$$("#lbGalleryContainer .product_pg input.bottom")[0].addEvent("click", function(){
				var s=$$("#lbGalleryContainer .imglist_vert")[0].getScroll();
				myFxVertSB.start(0, 100+s.y);
			});

			/*
			if (document.images) {
				tmp = new Image();
				tmp.src = dragParams.imgIn;
				tmp = new Image();
				tmp.src = dragParams.imgOut;
			}
			*/

			position();
			setup(1);


			images = _images;
			options.loop = options.loop && (images.length > 1);



			return changeImage(startImage);
		}
	};

})();



