/**
 * mediaGallery
 *
 * @version 2.1
 * @requires jQuery 1.4
 * @author Nathan Walasek
 * @website http://www.walasekdesign.com
 *
 **************************
 * USAGE: Default Options *
 **************************
 
$(window).load(function() {
	$('.mediaGallery a').mediaGallery();
});

 *************************
 * USAGE: Custom Options *
 *************************
 
**/

(function($){  
	$.fn.mediaGallery = function(options) {

		/* Set default options */
		var defaults = {
			loadGif:			'images/loader.gif',
			overlayColor:		'black',
			overlayOpacity:		0.5,
			fadeSpeed:			500,
			keyNav:				true,
			squareThumbs:		true,
			thumbSize:			100,
			thumbBorder:		true,
			thumbBorderSize:	1,
			thumbBorderColor:	'#333333',
			buttonNextText:		'Next Image',
			buttonPrevText:		'Previous Image',
			textColor:			'white',
			textBackground:		'#333333',
			textSize:			14,
			textFont:			'Verdana',
			imageCaption:		true,
			imageShadow:		true
		};
		
		/* Load custom options */
		var options = $.extend(defaults, options);
		
		var galleryItems = this.children();
		
		/* Get browser size */
		var _win = {};
		_win.w = $(window).width();
		_win.h = $(window).height();
		_win.ratio = _win.w / _win.h;
		$(window).resize(function() {
			_win.w = $(window).width();  
			_win.h = $(window).height();
			_win.ratio = _win.w / _win.h;
		});
		
		var _pop = {};
		
		/* Loads an image into the popup */
		_pop.load = function(_url, _current, fade) { 
			_pop.current = _current;
			_pop.create(fade);
			/* Check to see if image is first/last */
			if(!_pop.current.next().length) _pop.nextBtn.html('Close');
			if(!_pop.current.prev().length) _pop.prevBtn.html('Close');
			_pop.img = $('<img />');
			_pop.img.hide();
			/* Do stuff once image is loaded */
			_pop.img.bind('load', function() {
				$(this).css({
					position: 'relative',
					display: 'block',
					margin: 'auto'
				});
				/* Apply drop shadow */
				if(options.imageShadow == true) {
					$(this).css({
						'-moz-box-shadow': '0 0 20px #000000',
						'-webkit-box-shadow': '0 0 20px #000000',
						'box-shadow': '0 0 20px #000000'
					});
				}
				/* Resize image if necessary */
				_pop.img.w = this.width;
				_pop.img.h = this.height;
				_pop.img.ratio = _pop.img.w / _pop.img.h;
				if(_win.ratio > _pop.img.ratio) { //window more landscape than image
					if(_pop.img.h > _win.h) { //image is larger than overlay
						$(this).attr({
							width: _win.h * _pop.img.ratio,
							height: _win.h
						});
					}
				}
				if(_win.ratio < _pop.img.ratio) { //window more portrait than image
					if(_pop.img.w > _win.w) { //image is larger than window
						$(this).attr({
							width: _win.w,
							height: _win.w / _pop.img.ratio
						});
					}
				}
				/* Set top margin */
				$(this).css('margin-top', (_win.h - _pop.img.attr('height')) / 2);
				/* Display caption */
				if(options.imageCaption == true) {
					_pop.info.caption.html(_pop.current.find('img').attr('alt') + ' [' + (_pop.current.index() + 1) + '/' + galleryItems.length + ']');
					_pop.info.caption.attr({
						href: _url,
						target: '_blank',
						title: 'Click to view full-size'
					});
					_pop.info.caption.css({
						fontFamily: options.textFont
					});
				}
			});
			_pop.img.appendTo(_pop.container);
			_pop.img.click(function() { _pop.remove(true); });
			_pop.img.attr('src', _url);
		}
		
		/* Creates the elements of the popup */
		_pop.create = function(fade) {
			_pop.container = $('<div />'); //holds all elements
			_pop.container.css({
				position: 'fixed',
				zIndex: 9999,
				top: 0,
				left: 0,
				width: _win.w,
				height: _win.h,
				background: 'url(' + options.loadGif + ') center no-repeat'
			});
			_pop.container.appendTo('body');

			_pop.overlay = $('<div />'); //transparent overlay
			_pop.overlay.css({
				position: 'absolute',
				top: 0,
				left: 0,
				width: _win.w,
				height: _win.h,
				background: options.overlayColor,
				opacity: options.overlayOpacity
			});
			_pop.overlay.hide();
			_pop.overlay.appendTo(_pop.container);
			if(fade == true) {
				_pop.overlay.fadeIn(options.fadeSpeed);
			} else {
				_pop.overlay.show();	
			}
			_pop.overlay.click(function() { _pop.remove(true); });
			
			_pop.info = $('<div />'); //info bar with buttons
			_pop.info.css({
				position: 'absolute',
				bottom: 0,
				display: 'none',
				zIndex: 9999,
				padding: '5px 0',
				width: _win.w,
				textAlign: 'center',
				lineHeight: '26px',
				background: options.textBackground,
				color: options.textColor,
				fontSize: options.textSize,
				fontFamily: options.textFont
			});
			_pop.info.appendTo(_pop.container).delay(options.fadeSpeed).fadeIn(options.fadeSpeed);
			
			if(options.imageCaption == true) {
				_pop.info.caption = $('<a></a>'); //caption
				_pop.info.caption.css({
					float: 'none',
					color: options.textColor,
					textDecoration: 'none'
				});
				_pop.info.caption.appendTo(_pop.info);
			}
			
			_pop.nextBtn = $('<button />'); //next button
			_pop.nextBtn.html(options.buttonNextText);
			_pop.nextBtn.css({
				float: 'right',
				marginRight: 20
			});
			_pop.nextBtn.prependTo(_pop.info);
			_pop.nextBtn.click(function() {
				_pop.next();							  
			});

			_pop.prevBtn = $('<button />'); //previous button
			_pop.prevBtn.html(options.buttonPrevText);
			_pop.prevBtn.css({
				float: 'left',
				marginLeft: 20
			});
			_pop.prevBtn.prependTo(_pop.info);
			_pop.prevBtn.click(function() {
				_pop.prev();							  
			});

			/* Listen for key input */
			if(options.keyNav == true) {
				$(document).keydown(function(e) {
					if(e.which == 39) _pop.next(); //right arrow key
					if(e.which == 37) _pop.prev(); //left arrow key
					if(e.which == 27) _pop.remove(true); //esc key
				});
				/* Display keyboard hints */
				if(typeof _pop.hint == 'undefined') { //only show once
					_pop.hint = $('<div />');
					_pop.hint.html('Hint: Use arrow keys to navigate; Esc to close.');
					_pop.hint.css({
						position: 'absolute',
						top: 0,
						display: 'none',
						zIndex: 9999,
						padding: '5px 0',
						width: _win.w,
						textAlign: 'center',
						background: options.textBackground,
						color: options.textColor,
						fontSize: options.textSize,
						fontFamily: options.textFont
					});
					_pop.hint.appendTo(_pop.container).delay(options.fadeSpeed).fadeIn(options.fadeSpeed).delay(5000).fadeOut(options.fadeSpeed);
				}
			}
		}
		
		/* Removes the popup */
		_pop.remove = function(fade) {
			if(fade == true) {
				_pop.container.fadeOut(options.fadeSpeed, function() {
					$(this).remove();
				});
			} else {
				_pop.container.remove();	
			}
			$(document).unbind('keydown'); //stop listening for input
		}
		
		/* Loads the next image */
		_pop.next = function() {
			_current = 	_pop.current.next();
			if(_current.length) {
				_pop.remove();
				_url = _current.attr('href');
				_pop.load(_url, _current);
			} else {
				_pop.remove(true);
			}
		}
		
		/* Loads the previous image */
		_pop.prev = function() {
			_current = 	_pop.current.prev();
			if(_current.length) {
				_pop.remove();
				_url = _current.attr('href');
				_pop.load(_url, _current);
			} else {
				_pop.remove(true);	
			}
		}

		/* Create square thumbnails */
		if(options.squareThumbs == true) {
			galleryItems.each(function(i, _thmb) {
				$(_thmb).css({ //image wrapper
					display: 'block',
					overflow: 'hidden',
					width: options.thumbSize,
					height: options.thumbSize,
					border: function() {
						if(options.thumbBorder == true) {
							return options.thumbBorderSize + 'px solid ' + options.thumbBorderColor;
						} else {
							return 'none';	
						}
					}

				});
				_thmb.img = $(_thmb).find('img'); //image
				_thmb.img.w = _thmb.img.width();
				_thmb.img.h = _thmb.img.height();
				_thmb.img.ratio = _thmb.img.w / _thmb.img.h;
				/* Resize images and set margins to center */
				if(_thmb.img.ratio > 1) { //landscape
					_thmb.img.css({
						width: options.thumbSize * _thmb.img.ratio,
						height: options.thumbSize,
						marginLeft: -((options.thumbSize * _thmb.img.ratio - options.thumbSize) / 2)
					});
				}
				if(_thmb.img.ratio < 1) { //portrait
					_thmb.img.css({
						width: options.thumbSize,
						height: options.thumbSize / _thmb.img.ratio,
						marginTop: -((options.thumbSize / _thmb.img.ratio - options.thumbSize) / 2)
					});
				}
				if(_thmb.img.ratio == 1) { //square
					_thmb.img.css({
						width: options.thumbSize,
						height: options.thumbSize
					});
				}
			});
		}
		
		/* Attach events to thumbnails */
		galleryItems.click(function() {
			_pop.load(
				$(this).attr('href'),	// _url
				$(this),				// _current
				true					// fade?
			);			
			return false;
		});
	}
})(jQuery); 

