/**
 * Lightgallery plugin
 * v 0.1
 * Author:		J A Carmichael
 *	Company:		SiteClick Ltd  
 * Website:		www.siteclick.co.uk
 * License:  	BSD
 * Please leave this notice in place - enjoy!
 *
 * Modified 25/01/2010 to fix issue due to page scrolling on positioned elements
 */


 jQuery.fn.lightGallery = function(settings) {

 // Set defaults
  var settings = jQuery.extend({
    loadingIcon : 'js/ajax-loader-circle.gif',
    showTitles	:	false
  }, settings);

  // Create local reference to this
  var _this = this;

  // JavaScript image object
  this.currentImage	=  null;

  // Current jquery node: image contained with link
  this.currentNode	= null;
  
  // The parent node (UL) containing the gallery
  this.parentNode		= null;

  // The 'frame' div surrounding the main image
  this.frame			= null;


  /**
   * Destroys the overlay and frame
   */
  this.destroy = function() {
  		jQuery('#lightGalleryOverlay').remove();
  		jQuery('#lightGalleryFrame').remove();
  		_this.currentImage = null;
  		_this.currentNode	 = null;
  		_this.parentNode	 = null;
  		_this.frame			 = null;
  		return false;
  }

  // Function to open the gallery by adding the overlay
  this.overlayFadeIn = function() {

  		// Add overlay
  		var overlay = jQuery('<div id="lightGalleryOverlay"></div>');

		jQuery(overlay).css({	'cursor'					:	'wait',
										'position'				:	'fixed',
										'display'				:	'block',
										'width'					:	'100%',
										'height'					:	'100%',
										'z-index'				:	'1000',
										'background-color'	:	'black',
										'top'						:	0,
										'left'					:	0,
										'opacity'				:	0 });

		jQuery('body').prepend(overlay);



		jQuery(overlay).fadeTo('normal', 0.80, _this.loadImage);

		jQuery(overlay).click(_this.destroy);

  		return false;
  }
  

  
  /**
   * Load the required image
   */
  this.loadImage = function() {

  		// Add loading icon
  		_this.loadingIcon	= jQuery('<img id="lightGalleryLoadingIcon" src="' + settings.loadingIcon + '" style="position: fixed; top: 50%; left: 50%; z-index: 1020" />');
      jQuery('body').prepend(_this.loadingIcon);

  		// Indicate overlay is now clickable
  		jQuery('#lightGalleryOverlay').css({cursor: 'pointer'});

		_this.currentImage = new Image();

		// Unbind existing event
		jQuery(_this.currentImage).unbind('load');

		// Create new onload event
		jQuery(_this.currentImage).load(function() {

      	// Remove the loading icon
      	jQuery('#lightGalleryLoadingIcon').remove();

			// Hide the image
			jQuery(_this.currentImage).hide();
			jQuery('body').append(_this.currentImage);

			// Create/resize frame
			_this.animateFrame();
		})


		// Set new image source alt and title attributes
		_this.currentImage.src 		= jQuery(_this.currentNode).attr('href');
		_this.currentImage.alt 		= jQuery(_this.currentNode).attr('alt');
		_this.currentImage.title	= jQuery(_this.currentNode).attr('title');
		_this.currentImage.id			= 'lightGalleryMainImage';
		jQuery(_this.currentImage).css({'padding-bottom'	:	5});
  }


  /**
   * Next/previous image
   */
  this.skip = function (bNext) {



  		// Get next link node containing image or first link if end of sequence
  		if(bNext) {
  			_this.currentNode = jQuery(_this.currentNode).parent().next().children('a');
			  if(_this.currentNode.length == 0)
			  	_this.currentNode = jQuery(_this.parentNode).children('li:first-child').children('a');
  		}
  		// Get previous link or last if start of sequence
		else {
         _this.currentNode = jQuery(_this.currentNode).parent().prev().children('a');
     		if(_this.currentNode.length == 0)
				_this.currentNode = jQuery(_this.parentNode).children('li:last-child').children('a');
  		}




		// Fade out current and load next
  	jQuery(_this.frame).children('a,span,#lightGallerySkip').hide();

		jQuery(_this.frame).children('#lightGalleryMainImage').fadeOut('normal', function() {
			jQuery(_this.frame).find('#lightGalleryMainImage').remove();
			_this.loadImage();
		})
		return false;
  }
  
  
  this.nextImage = function() {
  		return _this.skip(true);
  }
  this.previousImage = function() {
  	   return _this.skip(false);
  }
  
  
  this.addSkipButtons = function() {

      // Add absolutely positioned container for the skip buttons
      var skipCont = jQuery('<div id="lightGallerySkip" style="position: absolute; width: ' + jQuery(_this.currentImage).width() + 'px; margin-top: ' + ((jQuery(_this.currentImage).height()/2)-10) + 'px"></div>');
      jQuery(_this.frame).append(skipCont);

			// Add skip image navigation links
			var prevLink = jQuery('<a id="lightGalleryPrevButton" style="float: left" class="lightGalleryButton" title="Click for previous image" href="#"><img src="js/gallery_prev.png" alt="Previous" /></a>');
			jQuery(prevLink).click(_this.previousImage);
			jQuery(skipCont).append(prevLink);

			var nextLink = jQuery('<a id="lightGalleryNextButton" style="float: right" class="lightGalleryButton" title="Click for next image" href="#"><img src="js/gallery_next.png" alt="Next" /></a>');
			jQuery(nextLink).click(_this.nextImage);
			jQuery(skipCont).append(nextLink);
			

			
			// Css the previous/next links
	   jQuery(prevLink).add(nextLink).css({  'z-index'   : '1002',
	                                         'top'       : (jQuery(_this.currentImage).height()/2)-10,
	                                         'cssFloat'  : 'left'});
	   jQuery(nextLink).css({                'cssFloat'  : 'right'});
	   

  }
	
	
	/**
	 * Close button
	 */
	this.addCloseButton = function() {
			// Add close button
			var cloBut = jQuery('<a href="#" title="Close gallery" class="lightGalleryClose"><img src="js/gallery_close.png" alt="Close" /></a>');
			jQuery(_this.frame).append(cloBut);
			jQuery(cloBut).click(_this.destroy);
			jQuery(cloBut).css({	'margin'		:	0,
														'padding'		:	0,
														'background':	'white',
														'float'			:	'right',
														'cursor'		:	'pointer'});
			jQuery(cloBut).hide();
	}
	
	/**
	 * Keyboard shortcuts
	 */
	this.keyboardShortcuts = function() {
		jQuery('body').keydown(function(ev) {
			switch(ev.which) {
				case 27:
					_this.destroy();
					break;
			  case 110:
			  case 78:
			  case 39:
			  	_this.skip(true);
			  	break;
			  case 112:
			  case 80:
			  case 37:
			  	_this.skip(false);
			  	break;
			}
		})
	}



  /**
   * Animate frame to correct size
   */
  this.animateFrame = function() {

		// Create frame if it doesn't exist
		if(!_this.frame) {

			// Create 'frame' div
      	_this.frame = jQuery('<div id="lightGalleryFrame"></div>');
      	jQuery(_this.frame).css({	'color'		:	'#444',
			                            'font'			:	'18px/18px arial, sans',
																	'width'		:	0,
																	'height'	:	0,
																	'top'			:	'50%',
																	'left'		:	'50%',
																	'position':	'fixed',
      														'z-index'	:	'1001',
      														'border'		:	'1px solid #ccc',
      														'background':	'white',
																	'padding'	:	'10px'});





			_this.addSkipButtons();
			_this.addCloseButton();
			_this.keyboardShortcuts();




 			// Add title
			var tit = jQuery('<span style="margin: 3px 0 0 0; color: #666; font: 14px/16px helvetica, arial, sans">class="lightGalleryTitle"></span>');
			if(settings.showTitles)
				jQuery(_this.frame).append(tit);

			// Add line break
			jQuery(_this.frame).append('<br clear="all" />');


			// Hide links for now
			jQuery(_this.frame).find('a,span').hide();

			// Append image 'frame' to doc
			jQuery('body').append(_this.frame);
		}

		// Add current image to frame
		jQuery(_this.frame).find('#lightGallerySkip').after(_this.currentImage);

		// Animate
		var leftPosition = Math.round( ($(window).width()  - jQuery(_this.currentImage).width()) /  2);
		var topPosition  = Math.round( ($(window).height() - jQuery(_this.currentImage).height()) / 2);

		$(_this.frame).animate({	'top'		:	topPosition + 'px',
											'left'	:	leftPosition + 'px',
											'width'	:	jQuery(_this.currentImage).width(),
											'height'	:	jQuery(_this.currentImage).height()+20 },
											'slow',
											'swing',
											function() {
                          jQuery(this).children('img#lightGalleryMainImage').fadeIn('slow',function() {


                                    // Show links
                                    jQuery(_this.frame).find('a,#lightGallerySkip').fadeIn();

                                    // Set title
                                    jQuery(_this.frame).find('span').text(jQuery(_this.currentNode).children('img').attr('alt'));
                                    jQuery(_this.frame).find('span').fadeIn();

													});
												});
			

  }



  // For each item
  return this.each(function(){

  		// Iterate over links contained within LI elements
		jQuery.each(jQuery(this).children('li').children('a'), function(i) {

        	// Set up onclick handler
        	jQuery(this).click(function() {

				// Destroy any existing
				_this.destroy();

				// Reset parent node
				_this.parentNode = jQuery(this).parents('ul');

				_this.currentNode = this;
				return _this.overlayFadeIn();
			});


		})
  })
  


}