/* 
 * Center plugin - center element on screen
 * v0.2 - 12/11/2008
 * - added ability to center in another element besides window
 */
(function($){
	$.fn.center = function(el)
	{
		// Get element dimensions
		var height = $(this).innerHeight();
		var width = $(this).innerWidth();
		
		// Figure out offset of container
		if(el)
		{
			var left = ($(el).innerWidth() - width) / 2;
			var top = ($(el).innerHeight() - height) / 2;
		}
		else
		{
			var scroll = $(window).scrollTop();
			var left = ($(window).width() - width) / 2;
			var top = (($(window).height() - height) / 2) + scroll;
		}
		
		// Make sure lightbox doesn't go above top of window
		if (top < 50)
		{
			top = 50;
		}
		
		$(this).css({left: left, top: top});
		
		return this;
	};
})(jQuery);

/*
 * Lightbox
 * Reusable custom jQuery lightbox
 *
 * @author Zach Waugh <zwaugh@gmail.com
 * @version 0.4
 * @requires center() plugin
 *
 * TODO:
 * - animate between gallery images
 * - provide defaults/options
 */
(function($){
	var useAjax = false;
	var resizeTimer = null;
	
	$.fn.lightbox = function(options)
	{
		if (options && options.trigger === true)
		{
			initLightbox.call(this);
		}
		else
		{
			$(this).click(initLightbox);	
		}
	};
	
	/**
	 * 
	 */
	function initLightbox()
	{
		var source = $(this).attr('href');
		
		// Check if pointing another element
		if (source.substring(0, 1) == '#')
		{
		 	showLightbox($(source).html());
		}
		else if (source.substring(0, 7) == 'http://' || source.substring(0, 1) == '/')
		{
			// Check if URL is pointing to an image
			if (isImage(source))
			{
				loadImage($(this));
			}
			else
			{
				// Load the contents via AJAX or into an iframe
				if (useAjax)
				{
					$.get(source, function (html) {
						showLightbox(html);
					});
				}
				else
				{
					showLightbox('<iframe width="960" height="680" src="' + source + '"></iframe>');
				}
			}

		}
		else
		{
			showLightbox('?????');
		}
		
		return false;
	}
	
	/**
	 * Perform actual creating and display of lightbox
	 * @param {String} content - HTML to put in lightbox
	 */
	function showLightbox(content, size)
	{
		// If lightbox already visible, just update content area
		if ($('#lightbox').length > 0)
		{
			if (size !== undefined)
			{
				$('#lightbox_content').css({width: size.width, height: size.height + 35});
			}
		
			$('#lightbox_content').html(content);
			$('#lightbox a.previous, #lightbox a.next').click(loadGalleryImage);
			$('#lightbox').center();
		}
		else
		{
			var html = '<div id="lightbox_overlay"></div>';
			html += '<div id="lightbox" style="display:none;">';
			
			if (size !== undefined)
			{
				html += '<div id="lightbox_content" style="height:' + (size.height +  35) + 'px; width:' + size.width + 'px;">';
			}
			else
			{
				html += '<div id="lightbox_content">';
			}
			
			html += content;
			html += '</div>';
			//html += '<br class="clear" />';
			html += '<a href="#" id="lightbox_close" title="Close">close</a>';
			html += '</div>';

			$('body').append(html);
			$('#lightbox a.previous, #lightbox a.next').click(loadGalleryImage);
			$('#lightbox_close').click(closeLightbox);
			$('#lightbox_overlay').css({opacity: 0}).one('click', closeLightbox);
			$('#lightbox_overlay').animate({opacity: 0.75}, 350);
			$('#lightbox').center().fadeIn(250);
			$('body').keydown(keyboardListener);
		}

		$(window).resize(resizeWindow);
	}
	
	/**
	 * Close lightbox if ESC key is pressed
	 * @param {jQuery Event Object} event
	 */
	function keyboardListener(event)
	{
		if (event.which == 27)
		{
			closeLightbox(event);
		}
	}
	
	/**
	 * Load an image based on href of link
	 * @param {jQuery Object} element
	 *
	 */
	function loadImage(element)
	{
		var url = element.attr('href');
		var caption = element.attr('title');
		
		// Check if photo is part of collection
		var rel = element.attr('rel');
		var gallery;
		
		if (rel !== '')
		{
			gallery = $('a[rel=' + element.attr('rel') + ']');
		}
		else
		{
			gallery = [];
		}
		
		var image = new Image();
		image.onload = function() {
			// Resize image to make sure it's not bigger than window
			var size = resizeImage({width: image.width, height: image.height});
			
			var html = '<div><img src="' + url + '" width="' + size.width + '" height="' + size.height + '" alt="" />';
			html += '</div><p class="caption">' + caption + '</p>';
			
			if (gallery.length > 0)
			{
				var current = gallery.index(element) + 1;
				var previous = (current == 0) ? 0 : current - 1;
				var next = (current == gallery.length) ? gallery.length : current + 1;
				html += '<div class="lightbox_nav">';
				html += '<a href="#' + element.attr('rel') + '" rel="' + previous  + '" class="previous">&lsaquo; Previous</a>';
				html += '<span>' + current + ' of ' + gallery.length + '</span>';
				html += '<a href="#' + element.attr('rel') + '" rel="' + next + '" class="next">Next &rsaquo;</a>';
				html += '</div>';
			}
			
			showLightbox(html, size);
		}
		
		image.src = url;
	}

	/**
	 * Load next/previous image from a gallery
	 * @param {jQuery Event Object} event
	 */
	function loadGalleryImage(event)
	{
		var href = $(this).attr('href');
		var rel = href.substr(href.indexOf('#') + 1);
		var gallery = $('a[rel=' + rel + ']');
		var index = $(this).attr('rel') - 1;
		loadImage(gallery.eq(index));
		
		return false;
	}
	
	/**
	 * Hide lightbox and remove from DOM, unbind event handlers
	 * @param {jQuery Event Object} event
	 */
	function closeLightbox(event)
	{
		// Unbind event handlers outside #lightbox
		$(window).unbind('resize');
		$('body').unbind('keydown');
		
		// Fade out and remove from DOM
		$('#lightbox, #lightbox_overlay').fadeOut(250, function()
		{
			$(this).remove();
		});
		
		return false;
	}
	
	/**
	 * Resize an image to ensure it's not bigger than window
	 * @param {Object} size - object with images width and height
	 */
	function resizeImage(size)
	{
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var ratio = 1;
		var padding = 200;
		var imgWidth = size.width;
		var imgHeight = size.height;
		
		if ((size.width + padding) >= windowWidth && (size.height + padding) >= windowHeight)
		{
			if (size.width > size.height)
			{
				ratio = imgHeight / imgWidth;
				imgWidth = windowWidth - padding;
				imgHeight = ratio * imgWidth;
			}
			else
			{
				ratio = imgWidth / imgHeight;
				imgHeight = $(window).height() - padding;
				imgWidth = ratio * imgHeight;
			}
		}
		else if ((size.width + padding) >= windowWidth)
		{
			ratio = imgHeight / imgWidth;
			imgWidth = windowWidth - padding;
			imgHeight = ratio * imgWidth;
		}
		else if ((size.height + padding) >= windowHeight)
		{
			ratio = imgWidth / imgHeight;
			imgHeight = windowHeight - padding;
			imgWidth = ratio * imgHeight;
		}
		
		return {width: parseInt(imgWidth), height: parseInt(imgHeight)};
	}
	
	/**
	 * Check if a url points to an image
	 * @param {String} url
	 */
	function isImage(url)
	{
		url = url.toLowerCase();
		if (url.indexOf('png') != -1 || url.indexOf('jpg') != -1 || url.indexOf('gif') != -1)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * Handle window resize event
	 */
	function resizeWindow()
	{
		if (resizeTimer)
		{
			clearTimeout(resizeTimer);
		}
		
		resizeTimer = setTimeout(resizeLightbox, 100);
	}
	
	/**
	 * Recenter lightbox as window is resized
	 */
	function resizeLightbox()
	{
		$('#lightbox').center();
	}
})(jQuery);