/*
 * Lightbox
 * Reusable custom jQuery lightbox
 *
 * @author Zach Waugh <zwaugh@gmail.com>
 * @version 0.5
 * @requires center() plugin
 *
 * Last update: 7/27/09
 *
 * TODO:
 * - animate between gallery images
 * - provide defaults/options
 */
(function($)
{
	var useAjax = false;
	var resizeTimer = null;
	
	$.fn.lightbox = function()
	{
		$(this).click(init);
	};
	
	/**
	 * Init lightbox and event bindings
	 */
	function init(event)
	{
		event.preventDefault();
		var source = $(this).attr('href');
		
		// Check if pointing another element
		if (source.substring(0, 1) == '#')
		{
		 	show($(source).html());
		}
		else if (source.substring(0, 7) == 'http://' || source.substring(0, 1) == '/' || isImage(source))
		{
			// 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) {
						show(html);
					});
				}
				else
				{
					show('<iframe width="960" height="680" src="' + source + '"></iframe>');
				}
			}
		}
		else
		{
			show('?????');
		}
	}
	
	/**
	 * Perform actual creating and display of lightbox
	 * @param {String} content - HTML to put in lightbox
	 */
	function show(content, size)
	{
		// If lightbox already visible, just update content area
		if ($('#lightbox').length > 0)
		{
			if (size !== undefined)
			{
				$('#lightbox_content').css({width: size.width});
			}
		
			$('#lightbox_content').html(content);
			
			Cufon.replace('.lightbox_nav', {fontWeight: 600, hover: true}); //BOLD
			
			$('#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 + 20) + 'px; width:' + size.width + 'px;">';
			}
			else
			{
				html += '<div id="lightbox_content">';
			}
			
			html += content;
			html += '</div>';
			html += '<a href="#" id="lightbox_close" title="Close">close</a>';
			html += '</div>';

			$('body').append(html);
			
			Cufon.replace('.lightbox_nav', {fontWeight: 600, hover: true}); //BOLD
			
			$('#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.95}, 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)
	{
		// Close lightbox on ESC
		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');
		var gallery = false;
		
		// Check if photo is part of collection
		var rel = element.attr('rel');
		
		if (rel !== undefined && rel != '')
		{
			var gallery = true;
		}
		
		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 = '<img src="' + url + '" width="' + size.width + '" height="' + size.height + '" alt="" />';
			html += '<br /><p class="caption">' + caption + '</p>';
			
			if (gallery)
			{
				var photos = $('a[rel=' + rel + ']');
				var current = photos.index(element) + 1;
				var previous = (current == 0) ? 0 : current - 1;
				var next = (current == photos.length) ? photos.length : current + 1;
				html += '<div class="lightbox_nav">';
				html += '<a href="#' + element.attr('rel') + '" rel="' + previous  + '" class="previous">&lsaquo; Previous</a>';
				html += '<span class="position">' + current + ' of ' + photos.length + '</span>';
				html += '<a href="#' + element.attr('rel') + '" rel="' + next + '" class="next">Next &rsaquo;</a>';
				html += '</div>';
			}
			
			show(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, padding)
	{
		padding = (padding === undefined) ? 100 : padding;
		
		var windowWidth = $(window).width();
		var windowHeight = $(window).height() - 50;
		var ratio = 1;
		var imgWidth = size.width;
		var imgHeight = size.height;

		if ((imgWidth + padding) >= windowWidth && (imgHeight + padding) >= windowHeight)
		{
			if (imgWidth > imgHeight)
			{
				ratio = imgHeight / imgWidth;
				imgWidth = windowWidth - padding;
				imgHeight = ratio * imgWidth;
				
				if ((imgHeight + padding) >= windowHeight)
				{
					ratio = imgWidth / imgHeight;
					imgHeight = windowHeight - padding;
					imgWidth = ratio * imgHeight;
				}
			} 
			else
			{
				ratio = imgWidth / imgHeight;
				imgHeight = windowHeight - padding;
				imgWidth = ratio * imgHeight;
				
				if ((imgWidth + padding) >= windowWidth)
				{
					ratio = imgHeight / imgWidth;
					imgWidth = windowWidth - padding;
					imgHeight = ratio * imgWidth;
				}
			}
		} 
		else if ((imgWidth + padding) >= windowWidth)
		{
			ratio = imgHeight / imgWidth;
			imgWidth = windowWidth - padding;
			imgHeight = ratio * imgWidth;
		} 
		else if ((imgHeight + padding) >= windowHeight)
		{
			ratio = imgWidth / imgHeight;
			imgHeight = windowHeight - padding;
			imgWidth = ratio * imgHeight;
		}

		return {width: Math.ceil(imgWidth), height: Math.ceil(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);