/*
	The Customize Slimbox
	Original
	Slimbox v2.02 (c) 2007-2009 Christophe Beyls <http://www.digitalia.be>

	////
	Rel names
	// lightbox = single
	href="image" title="caption" img alt="title"
	// lightbox_xxx = multi
	href="image" title="caption" img alt="title"
	// lightbox[listcategory] = listcategory
	href="#xxx" title="title" >> ul id="xxx" >> {id:[[image,caption]]}
	// lightbox[listgroupe] = listgroupe
	href="#xxx" title="title" >> ul id="xxx" >> 
*/

(function($) {

	// Global variables
	var links = {}, mode, images, options, lock = false,
	// DOM
	_lbOverlay, _lbLoading, _lbBody, _lbImageBody, _lbImage, _lbBottom, _lbTitle, _lbHeading, _lbHeadingTop, _lbCaption, _lbNumber, _lbClose, _lbNext, _lbPrev, _lbFrameTop, _lbFrameBottom, _lbControl, _lbNextTop, _lbPrevTop,
	// Size & Position
	clientParm, imageSize, wrapSize, lbmargin,
	// Image
	activeURL, activeImage, prevImage, nextImage, preload = {}, preloadPrev = new Image(), preloadNext = new Image(),
	// IE6
	ie6 = !window.XMLHttpRequest,
	// List Global variables
	listID, categoryID, listPage, listAllPage, listW = 0, listCnt,
	// List DOM
	_lbList, _lbListWrap, _lbListBody, _lbListNextLink, _lbListPrevLink, _lbListLinks;

	$(function() {
		// Append the HTML code
		/*
		<div id="lbOverlay"></div>
		<div id="lbControl">
			<div id="lbControlWrap">
				<table><tr>
				<td><a href="#" id="lbPrevLinkTop">PREV</a></td>
				<th><span id="lbHeadingTop"></span><span id="lbNumber"></span></th>
				<td><a href="#" id="lbNextLinkTop">NEXT</a></td>
				</tr></table>
			</div>
		</div>
		<div id="lbBody">
			<div id="lbLoading"></div>
			<div id="lbFrameTop"></div>
			<div id="lbImageBody">
				<img id="lbImage">
				<a href="#" id="lbPrevLink">&nbsp;</a>
				<a href="#" id="lbNextLink">&nbsp;</a>
			</div>
			<div id="lbBottom">
				<p id="lbHeading"></p>
				<div id="lbCaption"></div>
				<div id="lbClose"><a href="#" id="lbCloseLink">CLOSE</a></div>
			</div>
			<div id="lbFrameBottom"></div>
		</div>
		//
		<a href="#" id="lbListPrevLink">PREV</a><a href="#" id="lbListNextLink">NEXT</a>
		*/
		$("body").append('<div id="lbOverlay"></div><div id="lbControl"><div id="lbControlWrap"><table><tr><td><a href="#" id="lbPrevLinkTop">PREV</a></td><th><span id="lbHeadingTop"></span><span id="lbNumber"></span></th><td><a href="#" id="lbNextLinkTop">NEXT</a></td></tr></table></div></div><div id="lbBody"><div id="lbLoading"></div><div id="lbFrameTop"></div><div id="lbImageBody"><img id="lbImage"><a href="#" id="lbPrevLink">&nbsp;</a><a href="#" id="lbNextLink">&nbsp;</a></div><div id="lbBottom"><p id="lbHeading"></p><div id="lbCaption"></div><div id="lbClose"><a href="#" id="lbCloseLink">CLOSE</a></div></div><div id="lbFrameBottom"></div></div>');
		$("#lbList").append('<a href="#" id="lbListPrevLink">PREV</a><a href="#" id="lbListNextLink">NEXT</a>');
		_lbOverlay = $("#lbOverlay").click(close);
		_lbLoading = $("#lbLoading").hide();
		_lbBody = $("#lbBody");
		_lbImageBody = $("#lbImageBody").hide();
		_lbImage = $("#lbImage");
		_lbBottom = $("#lbBottom").hide();
		_lbHeading = $("#lbHeading");
		_lbTitle = $("#lbTitle");
		_lbCaption = $("#lbCaption");
		_lbFrameTop = $("#lbFrameTop");
		_lbFrameBottom = $("#lbFrameBottom");
		$("#lbCloseLink").click(close);
		//Control
		_lbControl = $("#lbControl");
		_lbHeadingTop = $("#lbHeadingTop");
		_lbNumber = $("#lbNumber");
		_lbNext = $("#lbNextLink").click(next);
		_lbPrev = $("#lbPrevLink").click(previous);
		_lbNextTop = $("#lbNextLinkTop").click(next);
		_lbPrevTop = $("#lbPrevLinkTop").click(previous);
		//List
		_lbList = $("#lbList");
		_lbListBody = $("#lbListBody");
		_lbListNextLink = $("#lbListNextLink").click(listNext);
		_lbListPrevLink = $("#lbListPrevLink").click(listPrev);
		_lbListBody.find("ul").hide();
	});

	$.lightbox = function(startImage) {
		// Options
		options = {
			scaling: true,
			imageMargin: 0,
			bodyMargin: 20,
			duration: 400,
			overlayOpacity: 0.8,
			resizeEasing: "swing",
			initialW: 250,
			initialH: 250,
			counterText: "Image {x} of {y}",
			listLinkMarginSide: 15,
			listLinkMarginTop: 10,
			listHoverClass: "lbListHover"
		};
		// IE6
		if (ie6) {
			_lbOverlay.css({"position": "absolute"});
			positionOverlay();
		}

		// Initialize
		lbmargin = options.imageMargin * 2;
		wrapSize = imageSize = {"w": options.initialW, "h": options.initialH};
		_lbFrameTop.css({"height": options.imageMargin});
		_lbFrameBottom.css({"height": options.imageMargin});
		_lbOverlay.css({"opacity": options.overlayOpacity}).fadeIn(options.duration);
		if (mode != "single") {
			_lbControl.fadeIn(options.duration);
		}
		_lbBody.css({"width": options.initialW, "height": options.initialH});
		getClientParm();
		if (mode == "listgroupe" || mode == "listcategory") { 
			listInit();
		}
		_lbBody.show();
		position();
		setup(1);
		return changeImage(startImage);
	};

	$.fn.lightbox = function() {
		var modetype = function(rel) {
			var m;
			if (rel.indexOf("[listgroupe]",0) != -1) {
				m = "listgroupe";
			} else if (rel.indexOf("[groupe]",0) != -1) {
				m = "groupe";
			} else if (rel.indexOf("[listcategory]",0) != -1) {
				m = "listcategory";
			} else if (rel.indexOf("[category]",0) != -1) {
				m = "category";
			} else {
				m = (rel.length > 8) ? "multi": "single";
			}
			return m;
		};
		var mapper = function(el,cap) {
			return [el, el.href, el.title, cap];
		};
		for (var i = 0; i < this.length; ++i) {
			var link = this[i];
			// Mode
			var m = modetype(link.rel);
			if (m == "listcategory") {
				continue;
			} else if (m == "category") {
				var id = link.rel.slice(18);
				var rel = "category#" + id;
				links[rel] = lbCategory[id];
			} else if (m == "listgroupe") {
				var id = $(link).attr("href");
				var tg = $(id).find("a");
				var rel = "listgroupe" + id;
				if (!links[rel]) {
					links[rel] = [];
				}
				for (j = 0; j < tg.length; ++j) {
					var cap = $(tg[j]).find("span").html();
					links[rel].push(mapper(tg[j], cap));
				}
			} else if (m == "groupe") {
				continue;
			} else {
				var rel = link.rel;
				if (!links[rel]) {
					links[rel] = [];
				}
				var cap = $(link).find("span").html();
				links[rel].push(mapper(link, cap));
			}
		}
		
		// Click Event
		this.unbind("click").click(function() {
			if (lock) {
				return false;
			}
			mode = modetype(this.rel);
			var startImage = 0;
			if (mode == "listcategory") {
				listID = $(this).attr("href");
				var idname = this.rel.slice(22);
				rel = "category#" + idname;
				categoryID = idname;
			} else if (mode == "category") {
				var idname = this.rel.slice(18);
				rel = "category#" + idname;
				images = links[rel];
				return (categoryID != idname)? listChangeCategory(idname) : false;
			} else if (mode == "listgroupe") {
				listID = $(this).attr("href");
				rel = "listgroupe" + listID;
			} else if (mode == "groupe") {
				var selectImage = $(this).parent().prevAll().length;
				return (activeImage != selectImage)? changeImage(selectImage) : false;
			} else {
				rel = this.rel;
				for (var i = 0; i < links[rel].length; ++i) {
					if (this == links[rel][i][0]) {
						startImage = i;
						break;
					}
				}
			}
			if (mode != "groupe") {
				images = links[rel];
				return $.lightbox(startImage);
			}
		});
	};

	/* Position */
	function position() {
		getClientParm();
		var top = clientParm.cy - wrapSize.h / 2 - _lbBottom.height() / 2;
		if (mode != "single" && mode != "multi") { // List
			var listL = clientParm.cx - _lbList.width() / 2;
			var listT = clientParm.y + clientParm.h - _lbList.height() - options.bodyMargin;
			if (options.scaling) {
				top -= (_lbList.height() + options.bodyMargin) / 2;
				top += (_lbControl.height() + options.bodyMargin) / 2;
			} else {
				top = clientParm.y + _lbControl.height() + options.bodyMargin * 2;
				if (clientParm.h - _lbControl.height() - _lbList.height() - options.bodyMargin * 4 < wrapSize.h + _lbBottom.height()) {
					var listT = clientParm.y + wrapSize.h + _lbBottom.height() + _lbControl.height() + options.bodyMargin * 3;
				}
			}
			_lbList.css({"top": listT, "left": listL});
		}
		_lbControl.css({"top": clientParm.y + options.bodyMargin});
		_lbBody.css({"top": top, "left": clientParm.cx - wrapSize.w / 2});
		if (ie6) {
			_lbOverlay.css({left: clientParm.x, top: clientParm.y, width: clientParm.w, height: clientParm.h});
		}
	}
	function positionOverlay() {
		getClientParm();
		_lbOverlay.css({left: clientParm.x, top: clientParm.y, width: clientParm.w, height: clientParm.h});
	}

	/* Setup */
	function setup(open) {
		var fn = open ? "bind" : "unbind";
		$(window)[fn]("resize", position);
		if (options.scaling) {
			$(window)[fn]("resize scroll", position);
		} else {
			$(window)[fn]("resize", position);
		}
		if (ie6) { $(window)[fn]("scroll", positionOverlay); }
	}

	/* Previous & Next */
	function previous() {
		this.blur();
		if (lock) {
			return false;
		} else {
			lock = true;
			changeImage(prevImage);
			return false;
		}
	}
	function next() {
		this.blur();
		if (lock) {
			return false;
		} else {
			lock = true;
			changeImage(nextImage);
			return false;
		}
	}

	/* ChangeImage */
	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			lock = true;
			activeImage = imageIndex;
			activeURL = images[activeImage][1];
			prevImage = nextImage = -1;
			if (mode != "single") {
				prevImage = activeImage - 1;
				nextImage = ((activeImage + 1) % images.length) || -1;
				if (prevImage < 0) {
					_lbPrev.hide();
					_lbPrevTop.hide();
				} else {
					_lbPrev.show();
					_lbPrevTop.show();
				}
				if (nextImage < 0) {
					_lbNext.hide();
					_lbNextTop.hide();
				} else {
					_lbNext.show();
					_lbNextTop.show();
				}
			}
			if (mode != "single" && mode != "multi") { listUpdate(); } // List
			stop();
			_lbLoading.css({width: "100%", height: _lbBody.height()}).show();
			preload = new Image();
			preload.onload = sizingBox;
			preload.src = activeURL;
		}
		return false;
	}

	/* Sizing */
	function sizingBox() {
		var image, scale;
		_lbLoading.hide();
		position();
		// Set Heading & Caption
		var head = images[activeImage][2];
		var capt = images[activeImage][3];
		if (mode == "listcategory" || mode == "category") {
			_lbHeadingTop.html(images[activeImage][0] + "&nbsp;&gt;&nbsp;" + head + "&nbsp;:&nbsp;");
			_lbHeading.html(images[activeImage][4]);
		} else {
			_lbHeadingTop.html(head);
			_lbHeading.html(head);
		}
		_lbCaption.html(capt);
		_lbNumber.html((((mode != "single") && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));
		// Get Scaling
		scale = scalingBox();
		// Set Size
		preload.width *= scale;
		preload.height *= scale;
		imageSize = {w: preload.width, h: preload.height};
		wrapSize = {w: preload.width + lbmargin, h: preload.height + lbmargin};
		_lbImageBody.css({height: imageSize.h, width: imageSize.w});
		// Image
		if (prevImage >= 0) { preloadPrev.src = images[prevImage][1]; }
		if (nextImage >= 0) { preloadNext.src = images[nextImage][1]; }
		image = document.getElementById("lbImage");
		image.src = activeURL;
		image.width = preload.width;
		image.height = preload.height;
		animateBox();
	}

	/* Scaling */
	function scalingBox() {
		var scale = 1;
		if (options.scaling) {
			var w, h, lh = 0;
			if (mode != "single" && mode != "multi") { lh = _lbList.height() + _lbControl.height() + options.bodyMargin * 2; }
			var getScale = function(initW, initH, s) {
				var cW = (clientParm.w - lbmargin - options.bodyMargin * 2) / (initW * s);
				var cH = (clientParm.h - lbmargin - options.bodyMargin * 2 - _lbBottom.height() - lh) / (initH * s);
				var sc = (cW <= cH)? cW: cH;
				return (sc >= 1)? s: sc * s;
			};
			// scaling Filter
			var scalingFilter = 3;
			while (scalingFilter--) {
				if (scale <= 0 || scale > 1) {
					scale = 1;
					break;
				}
				_lbBottom.css({width: preload.width * scale});
				var s = getScale(preload.width, preload.height, scale);
				if (s == scale) {
					break;
				} else {
					scale = s;
				}
			}
		}
		return scale;
	}

	/* Animation */
	function animateBox() {
		// Style
		_lbImageBody.css({opacity: ""});
		_lbBottom.css({width: imageSize.w, opacity: ""});
		// Animate
		var top = clientParm.cy - wrapSize.h / 2 - _lbBottom.height() / 2;
		var left = clientParm.cx - wrapSize.w / 2;
		if (options.scaling) {
			if (mode != "single" && mode != "multi") { // List
				top -= (_lbList.height() + options.bodyMargin) / 2;
				top += (_lbControl.height() + options.bodyMargin) / 2;
			}
		} else {
			if (mode != "single" && mode != "multi") { // List
				top = clientParm.y + _lbControl.height() + options.bodyMargin * 2;
				if (clientParm.h - _lbControl.height() - _lbList.height() - options.bodyMargin * 4 < wrapSize.h + _lbBottom.height()) {
					_lbList.animate({"top": clientParm.y + wrapSize.h + _lbBottom.height() + _lbControl.height() + options.bodyMargin * 3}, options.duration);
				} else {
					_lbList.animate({"top": clientParm.y + clientParm.h - _lbList.height() - options.bodyMargin}, options.duration);
				}
			}
		}
		_lbBody.animate({top: top, "left": left, width: wrapSize.w, height: wrapSize.h}, options.duration, options.resizeEasing);
		_lbBody.queue(function() {
			_lbImageBody.fadeIn(options.duration, animateBox2);
		});
	}
	function animateBox2() {
		lock = false;
		_lbBottom.show();
		_lbBody.queue([]).animate({height: wrapSize.h + _lbBottom.height()}, options.duration, function(){
			if (prevImage >= 0) { $("#lbPrevLink").show(); }
			if (nextImage >= 0) { $("#lbNextLink").show(); }
		});
	}

	/* Client Size & Positions */
	function getClientParm() {
		clientParm = {
			w: document.documentElement.clientWidth || document.body.clientWidth,
			h: document.documentElement.clientHeight || document.body.clientHeight,
			x: document.body.scrollLeft || document.documentElement.scrollLeft,
			y: document.body.scrollTop || document.documentElement.scrollTop
		};
		clientParm.cx = Math.floor(clientParm.w / 2 + clientParm.x);
		clientParm.cy = Math.floor(clientParm.h / 2 + clientParm.y);
	}

	/* Stop */
	function stop() {
		preload.onload = null;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		_lbBody.stop(true);
		_lbImageBody.stop(true).hide();
		_lbBottom.stop(true).hide();
	}

	/* Close */
	function close() {
		if (activeImage >= 0) {
			stop();
			lock = false;
			activeImage = prevImage = nextImage = -1;
			_lbBody.hide();
			_lbControl.hide();
			_lbOverlay.stop().fadeOut(options.duration, setup);
			if (mode != "single" && mode != "multi") { listClose(); } // List
		}
		return false;
	}



	/* list functions */
	function listInit() {
		var thumW, wrapW, thumAllCnt, thumMaxW;
		_lbListPrevLink.hide();
		_lbListNextLink.hide();
		_lbList.css({"display": "block"});
		$(listID).show();
		_lbListLinks = $(listID).find("img").parent();
		thumW = $(listID).find("li").eq(0).width() + options.listLinkMarginSide;
		thumMaxW = _lbList.width() - _lbListPrevLink.width() - _lbListNextLink.width();
		listCnt = Math.floor(thumMaxW / thumW);
		thumAllCnt = _lbListLinks.length;
		listPage = 0;
		listAllPage = Math.floor(thumAllCnt / listCnt);
		if (listCnt >= thumAllCnt) {
			listW = thumAllCnt * thumW;
		} else {
			listW = listCnt * thumW;
			_lbListNextLink.show();
		}
		_lbListBody.css({"left": _lbList.width() / 2 - (listW - options.listLinkMarginSide) / 2, "width": listW - options.listLinkMarginSide});
		$(listID).css({"left": 0, "width": thumAllCnt * thumW + 100});
		$(listID).find("li").css({"margin-right": options.listLinkMarginSide, "margin-top": options.listLinkMarginTop});
		var listH = $(listID).height() + options.listLinkMarginTop;
		var listT = clientParm.y + clientParm.h - listH - options.bodyMargin;
		_lbList.css({"top": listT,"left": clientParm.cx - _lbList.width() / 2, "height": listH});
	}
	function listNext() {
		listPage++;
		if (listPage >= listAllPage) {
			$(this).hide();
			_lbListPrevLink.show();
		}
		return listBtn();
	}
	function listPrev() {
		listPage--;
		if (listPage <= 0) {
			$(this).hide();
			_lbListNextLink.show();
		}
		return listBtn();
	}
	function listBtn() {
		var x = listPage * listW;
		$(listID).animate({left: -x});
		return false;
	}
	function listChangeCategory(idname) {
		var startImage = 0;
		categoryID = idname;
		return changeImage(startImage);
	}
	function listUpdate() {
		if (mode == "listcategory" || mode == "category") {
			_lbListLinks.removeClass(options.listHoverClass);
			var rel = 'lightbox[category]' + categoryID;
			$(listID).find("a[rel='" + rel +"']").addClass(options.listHoverClass);
			var cnt = 0;
			var act = 0;
			for (var key in lbCategory) {
				if (key == categoryID) act = cnt;
				cnt++;
			}
			var page = Math.floor(act / listCnt);
			if (page != listPage) {
				listPage = page;
				$(listID).css({left: -(listPage * listW)});
				_lbListPrevLink.css({"display": (listPage <= 0)? "none": "block"});
				_lbListNextLink.css({"display": (listPage >= listAllPage)? "none": "block"});
			}
		} else {
			_lbListLinks.removeClass(options.listHoverClass);
			_lbListLinks.eq(activeImage).addClass(options.listHoverClass);
			var page = Math.floor(activeImage / listCnt);
			if (page != listPage) {
				listPage = page;
				$(listID).animate({left: -(listPage * listW)});
				_lbListPrevLink.css({"display": (listPage <= 0)? "none": "block"});
				_lbListNextLink.css({"display": (listPage >= listAllPage)? "none": "block"});
			}
		}
	}
	function listClose() {
		_lbListLinks.removeClass(options.listHoverClass);
		_lbList.stop().hide();
		$(listID).queue([]).stop().hide();
		_lbList.css({opacity: ""});
		mode = "";
	}

})(jQuery);

jQuery(function($) {
	$("a[rel^='lightbox']").lightbox();
});
