/*!
	Slimbox (Versão Extendida 1.0, 2008-08-07)
	por Emil Knorst
	- Modificado para uso de iFrames

	Based on:
	Slimbox v1.64 - The ultimate lightweight Lightbox clone
	(c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/

var Slimbox;

(function() {

	// Global variables, accessible to Slimbox only
	var state = 0, options, contents, activeContent, prevContent, nextContent, top, fx, preload, preloadPrev = new Image(), preloadNext = new Image(),
	// State values: 0 (closed or closing), 1 (open and ready), 2+ (open and busy with animation)

	// DOM elements
	overlay, center, content, prevLink, nextLink, bottomContainer, bottom, caption, number;

	/*
		Initialization
	*/

	window.addEvent("domready", function() {
		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$([
				overlay = new Element("div", {id: "lbOverlay"}).addEvent("click", close),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			]).setStyle("display", "none")
		);

		content = new Element("div", {id: "lblContent"}).injectInside(center).adopt(
			prevLink = new Element("a", {id: "lbPrevLink", href: "#"}).addEvent("click", previous),
			nextLink = new Element("a", {id: "lbNextLink", href: "#"}).addEvent("click", next)
		);

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			closeLink = new Element("a", {id: "lbCloseLink", href: "#"}).addEvent("click", close),
			caption = new Element("span", {id: "lbCaption"}),
			number = new Element("span", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);

		fx = {
			overlay: new Fx.Tween(overlay, {property: "opacity", duration: 500}).set(0),
			content: new Fx.Tween(content, {property: "opacity", duration: 500, onComplete: nextEffect}),
			bottom: new Fx.Tween(bottom, {property: "top", duration: 400})
		};
	});

	/*
		API
	*/

	Slimbox = {
		open: function(_contents, startContent, _options) {
			options = $extend({
				loop: false,              // Allows to navigate between first and last contents
				overlayOpacity: 0.8,      // 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				resizeDuration: 400,      // Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,  // Default transition in mootools
				initialWidth: 200,        // Initial width of the box (in pixels)
				initialHeight: 200,       // Initial height of the box (in pixels)
				animateCaption: true,
				showCounter: true,        // If true, a counter will only be shown if there is more than 1 content to display
				counterText: "{x} de {y}",// Translate or change as you wish
				closeText: "Fechar",      // Text for close button
				width: 0,                 // Total width of content (in pixels)
				height: 0,                 // Total height of content (in pixels)
				createdControlID: "lbTargetControl" // The ID for the control created
			}, _options || {});

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

			contents = _contents;
			options.loop = options.loop && (contents.length > 1);
			position();
			setup(true);
			top = window.getScrollTop() + (window.getHeight() / 10);
			fx.resize = new Fx.Morph(center, $extend({duration: options.resizeDuration, onComplete: function() { position(); nextEffect();} }, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			center.setStyles({top: top, width: options.initialWidth, height: options.initialHeight, marginLeft: -(options.initialWidth/2), display: ""});
			fx.overlay.start(options.overlayOpacity);
			state = 1;
			return changeContent(startContent);
		},
		closeSlimBox: function() {
			close();
		}
	};

	Element.implement({
		slimbox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).slimbox(_options, linkMapper);

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Slimbox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
					the content URL and the content caption (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the content collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title];
			};

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

			var links = this;

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

			return links;
		}
	});


	/*
		Internal functions
	*/

	function position() {
		var win_width = window.getScrollSize().x;
		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1){
			win_width = win_width - 17
		}
		overlay.setStyles({top: 0, height: window.getScrollSize().y, width: win_width});
	}

	function setup(open) {
		$$("object", Browser.Engine.trident ? "select" : "embed").each(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";
		window[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		switch(event.code) {
			case 27:	// Esc
			case 88:	// 'x'
			case 67:	// 'c'
				close();
				break;
			case 37:	// Left arrow
			case 80:	// 'p'
				previous();
				break;	
			case 39:	// Right arrow
			case 78:	// 'n'
				next();
		}
		// Prevent default keyboard action (like navigating inside the page)
		return false;
	}

	function previous() {
		return changeContent(prevContent);
	}

	function next() {
		return changeContent(nextContent);
	}

	function changeContent(contentIndex) {
		if ((state == 1) && (contentIndex >= 0)) {
			state = 2;
			activeContent = contentIndex;
			prevContent = ((activeContent || !options.loop) ? activeContent : contents.length) - 1;
			nextContent = activeContent + 1;
			if (nextContent == contents.length) nextContent = options.loop ? 0 : -1;

			$$(prevLink, nextLink, content, bottomContainer).setStyle("display", "none");
			fx.bottom.cancel().set(0);
			fx.content.set(0);
			center.className = "lbLoading";
			
			// Dispose controls created before
			$each($$("#"+options.createdControlID), function(item) { item.dispose() });								
			
			// Is image?
			var isImage = (contents[contentIndex][0].match(/\.(jpe?g|png|gif|bmp)/i) == null) ? false : true;
		
			if (isImage)
			{
				preload = new Image();
				preload.id = options.createdControlID;
				preload.onload = nextEffect;
				preload.src = contents[contentIndex][0];
				preload.alt = contents[activeContent][1];
			}
			else
			{
				preload = new IFrame({
					id: options.createdControlID,
					src: contents[contentIndex][0],
					frameborder: 0,
					scrolling: 'no',
					width: (options.width  > 0) ? options.width - 2 : 'auto', 						
					height: (options.height  > 0) ? options.height - 2 : 'auto'
				});
				nextEffect();
			}
		}
		return false;
	}

	function nextEffect() {
		switch (state++) {
			case 2:
				var isIFrame = preload.tagName.toLowerCase() == "iframe";
				
				center.className = "";
				
				var contentWidth  = (isIFrame) ? preload.width.toInt() + 5 : preload.width;
				var contentHeight = (isIFrame) ? preload.height.toInt() + 5 : preload.height;
				
				content.adopt(preload);
				
				if (isIFrame && Browser.Engine.trident4) // IE6 Bug
					preload.src = preload.src;
					
				content.setStyles({display: "", width: contentWidth, height: contentHeight});
				bottom.setStyle("width", contentWidth);
				$$(prevLink, nextLink).setStyle("height", contentHeight);

				$("lbCloseLink").set('html', options.closeText);
				caption.set('html', contents[activeContent][1] || "");
				number.set('html', (options.showCounter && (contents.length > 1)) ? options.counterText.replace(/{x}/, activeContent + 1).replace(/{y}/, contents.length) : "");

				if (prevContent >= 0) preloadPrev.src = contents[prevContent][0];
				if (nextContent >= 0) preloadNext.src = contents[nextContent][0];

				if (center.clientHeight != content.offsetHeight) {
					fx.resize.start({height: content.offsetHeight});
					break;
				}
				
				state++;
			case 3:
				if (center.clientWidth != content.offsetWidth) {
					fx.resize.start({width: content.offsetWidth, marginLeft: -content.offsetWidth/2});
					break;
				}
				state++;
			case 4:
				bottomContainer.setStyles({top: 0, height: center.offsetTop, width: center.offsetWidth, marginLeft: center.style.marginLeft, visibility: "hidden", display: ""});
				fx.content.start(1);
				break;
			case 5:
				if (prevContent >= 0) prevLink.style.display = "";
				if (nextContent >= 0) nextLink.style.display = "";
				
				if (options.animateCaption) {
					fx.bottom.set(bottomContainer.offsetHeight).start(bottomContainer.offsetHeight - bottom.offsetHeight);
				}
				
				bottomContainer.style.visibility = "";
				state = 1;
				break;
		}
	}

	function close() {
		if (state) {
			state = 0;
			preload.onload = $empty;
			for (var f in fx) fx[f].cancel();
			$$(center, bottomContainer).setStyle("display", "none");
			fx.overlay.chain(setup).start(0);
		}
		return false;
	}
})();

