(function($) {

	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			imageArray:				[],
			activeImage:			0
		},settings);
		
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			
			
			settings.imageArray.length = 0;
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let�s see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			
			_set_interface();
			_set_image_to_view();
		}
		
		
		function _set_interface() {
			
			pagedots = '<ul id="lightbox-dots">';
			for(var i = 0; i < settings.imageArray.length; ++i){
				pagedots += '<li><a href="#">'+ i +'</image></li>';
			}
			pagedots += '</ul>'	
			
			var markup = '<div id="lightbox-overlay"></div>';
			markup += '<div id="lightbox-loading"></div>';
			markup += '<div id="lightbox-content">';
			//<div id="lightbox-header"><a href="#" id="lightbox-close">Close</a></div>
			markup += '<img id="lightbox-image"><div id="lightbox-footer">';
			markup += '<a id="lightbox-previous" href="#">Previous</a>';
			markup += pagedots;
			markup += '<a id="lightbox-next" href="#">Next</a></div>';
			markup += '</div>';
			
			$('body').append(markup);	

			var w = 20 * (settings.imageArray.length + 2);
			$('#lightbox-dots').width(w);
			
			// INTERACTIVITY
			
			$('#lightbox-dots li a').each(function(myindex) {
				$(this).bind('click' , {index:myindex} ,function(e){
					settings.activeImage =  e.data.index;
					_set_image_to_view();
					return false;
				});
			});
			

			$('#lightbox-overlay').click(function() {
				_finish();	
				return false;
			});
			
			$('#lightbox-previous').bind('click',function() {
				settings.activeImage = settings.activeImage == 0 ?  settings.imageArray.length  -1 : settings.activeImage - 1;
				_set_image_to_view();
				return false;
			});
			
			
			$('#lightbox-next').bind('click',function() {
				settings.activeImage = settings.activeImage == settings.imageArray.length  -1 ? 0 : settings.activeImage + 1;
				_set_image_to_view();
				return false;
			});
				
			
			// APPEAR

			$('#lightbox-overlay').css('opacity' , '.6').fadeIn();
			
	
			$(window).resize(function() {			
				$('#lightbox-overlay').width($(window).width());
				$('#lightbox-overlay').height($(window).height());	
				console.log($('#lightbox-content').height());		
				$('#lightbox-content').centerX();
				$('#lightbox-content').centerY();
			});
			
			$(window).resize();
		}
		
		
		
		function _set_video(){
			$('#lightbox-image').hide();
			$("#lightbox-video-container").remove();
			$('#lightbox-content').prepend('<div id="lightbox-video-container"></div>');
			//$('<div id="lightbox-video-container"></div>').insertAfter('#lightbox-header');
			var toWidth = $('#lightbox-video-container').width();
			$('#lightbox-content').width(toWidth);
			var left = (toWidth - $('#lightbox-dots').width()) / 2;
			$('#lightbox-dots').css('marginLeft' , left + 'px');
			$(window).resize();
			
			var flashvars = {src:settings.imageArray[settings.activeImage][0]};
			var params = {bgcolor:'#000000' , allowFullScreen:"true"};
			swfobject.embedSWF("/static/swf/player.swf", "lightbox-video-container", "640", "340", "10.1.0", "/static/swf/expressInstall.swf",flashvars,params);
		};

		
		
		/**
		 * Prepares image exibition; doing a image�s preloader to calculate it�s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			$('#lightbox-dots li a').removeClass('selected');
			$('#lightbox-dots li a:eq('+ settings.activeImage +')').addClass('selected');
			
			var videoExtensions = ['flv' , 'f4v' , 'mp4'];
			var extension = String(settings.imageArray[settings.activeImage][0]).split('/');
			extension = extension[(extension.length - 1)];
			extension = extension.split('.');
			extension = String(extension[(extension.length - 1)]).toLowerCase();
			if(videoExtensions.indexOf(extension) > -1){
				_set_video();
				return;
			}
			
			$("#lightbox-video-container").remove();
			MainUI.getInstance().toggleWait(true);
			$('#lightbox-content').hide();
			
			
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);				
				
				$('#lightbox-image').height(this.height);
				$('#lightbox-content').width(objImagePreloader.width);
				 var left = (objImagePreloader.width - $('#lightbox-dots').width()) / 2;
				 $('#lightbox-dots').css('marginLeft' , left + 'px');
				 
				 _show_image();

				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		
		
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-image').show();
			$('#lightbox-content').fadeIn();
			MainUI.getInstance().toggleWait(false);
			$(window).resize();
		};
		
		
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#lightbox-content').remove();
			$('#lightbox-loading').remove();
			$('#lightbox-overlay').fadeOut(function() { $('#lightbox-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object
