/**
 * 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!
 */


 jQuery.fn.lightGallery = function(settings) {

 // Set defaults
  var settings = jQuery.extend({
    loadingIcon : 'ajax-loader.gif'
  }, 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;
  }

  // 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');
  }


  /**
   * 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().fadeOut('normal', function() {
			jQuery(_this.frame).find('img').remove();
			_this.loadImage();
		})
		return false;
  }
  
  
  this.nextImage = function() {
  		return _this.skip(true);
  }
  this.previousImage = function() {
  	   return _this.skip(false);
  }



  /**
   * 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'	:	'20px'});

			// Add skip image navigation links
			var nextLink = jQuery('<a style="cursor: pointer;  display: block; float: right;" id="lightGalleryPreviousButton" class="lightGalleryButton" title="Click for next image">&raquo;</a>');
			jQuery(nextLink).click(_this.nextImage);
			jQuery(_this.frame).append(nextLink);

			var prevLink = jQuery('<a style="cursor: pointer;  display: block; float: left;" id="lightGalleryNextButton" class="lightGalleryButton" title="Click for previous image">&laquo;</a>');
			jQuery(prevLink).click(_this.previousImage);
			jQuery(_this.frame).append(prevLink);



			// Hide links for now
			jQuery(_this.frame).find('a').hide();

			// Append image 'frame' to doc
			jQuery('body').append(_this.frame);
		
		


		}

		// Add current image to frame
		jQuery(_this.frame).prepend(_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() },
											'slow',
											'swing',
											function() {
                                  	jQuery(this).children('img').fadeIn('slow',function() {
                                       	jQuery(_this.frame).find('a').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();
			});


		})
  })
  


}