
(function($)
{
	$.LightboxClass = function ( )
	{
		this.construct();
	};

	$.fn.lightbox = function ( options )
	{
		$.Lightbox = $.Lightbox || new $.LightboxClass();

		options = $.extend({start:false,events:true}, options);

		var group = $(this);

		if ( options.events )
		{
			$(group).click(function(){
				var obj = $(this);
				if ( !$.Lightbox.init($(obj)[0], group) )
				{	return false;	}
				if ( !$.Lightbox.start() )
				{	return false;	}
				return false;
			});
			$(group).addClass('lightbox-enabled');
		}
		
		if ( options.start )
		{
			var obj = $(this);
			if ( !$.Lightbox.init($(obj)[0], group) )
			{	return this;	}
			if ( !$.Lightbox.start() )
			{	return this;	}
		}
		return this;
	};
	
	$.extend($.LightboxClass.prototype,
	{
		images: {

			list:[],
			image: false,
			
			prev: function ( image )
			{
				if ( typeof image === 'undefined' )
				{	image = this.active();
					if ( !image ) { return image; }
				}

				if ( this.first(image) )
				{	return false;	}

				return this.get(image.index-1);
			},
			
			next: function ( image )
			{
				if ( typeof image === 'undefined' )
				{	image = this.active();
					if ( !image ) { return image; }
				}

				if ( this.last(image) )
				{	return false;	}

				return this.get(image.index+1);
			},
			
			first: function ( image )
			{
				if ( typeof image === 'undefined' )
				{	return this.get(0);	}
				return image.index === 0;
			},
			
			last: function ( image )
			{
				if ( typeof image === 'undefined' )
				{	return this.get(this.size()-1);	}

				return image.index === this.size()-1;
			},
		
			single: function ( )
			{
				return this.size() === 1;
			},
			
			size: function ( )
			{
				return this.list.length;
			},
			
			empty: function ( )
			{
				return this.size() === 0;
			},
			
			clear: function ( )
			{
				this.list = [];
				this.image = false;
			},
		
			active: function ( image )
			{
				if ( typeof image === 'undefined' )
				{	return this.image;	}

				image = this.get(image);
				if ( !image ) { return image; }

				this.image = image;
				return true;
			},
		
			add: function ( obj )
			{
				if ( obj[0] )
				{
					for ( var i = 0; i < obj.length; i++ )
					{	this.add(obj[i]);	}
					return true;
				}

				var image = this.create(obj);
				if ( !image ) { return image; }
				image.index = this.size();
				this.list.push(image);
				return true;
			},
			
			create: function ( obj )
			{
				var image = {
					src:	'',
					title:	'Untitled',
					description:	'',
					index:	-1,
					image:	true
				};

				if ( obj.image )
				{
					image.src = obj.src || image.src;
					image.title = obj.title || image.title;
					image.description = obj.description || image.description;
					image.index = obj.index || image.index;
				}
				else if ( obj.tagName )
				{
					obj = $(obj);
					if ( obj.attr('src') || obj.attr('href') )
					{
						image.src = obj.attr('src') || obj.attr('href');
						image.title = obj.attr('title') || obj.attr('alt') || image.title;
						var s = image.title.indexOf(': ');
						if ( s > 0 )
						{
							image.description = image.title.substring(s+2) || image.description;
							image.title = image.title.substring(0,s) || image.title;
						}
					}
					else
					{
						image = false;
					}
				}
				else
				{
					image = false;
				}
				
				if ( !image )
				{
					this.debug('We dont know what we have:', obj);
					return false;
				}

				return image;
			},
			
			get: function ( image )
			{
				if ( image === undefined || image === null )
				{
					return this.active();
				}
				else
				if ( typeof image === 'number' )
				{
					image = this.list[image] || false;
				}
				else
				{
					image = this.create(image);
					if ( !image ) { return false; }

					var f = false;
					for ( var i = 0; i < this.size(); i++ )
					{
						var c = this.list[i];
						if ( c.src === image.src && c.title === image.title && c.description === image.description )
						{	f = c;	}
					}
					image = f;
				}
				if ( !image )
				{
					this.debug('The desired image doesn\'t exist: ', image, this.list);
					return false;
				}
				return image;
			},

			debug: function ( )
			{
				return $.Lightbox.debug(arguments);
			}
			
		},
		
		baseurl:			'',
		
		files: {
			js: {
				lightbox:	'js/jquery.lightbox.js'
			},
			css: {
				lightbox:	'css/jquery.lightbox.css'
			},
			images: {
				prev:		'images/prev.gif',
				next:		'images/next.gif',
				blank:		'images/blank.gif',
				loading:	'images/loading.gif'
			}
		},
		
		text: {
			image:		'Image',
			of:			'of',
			close:		'Close X',
			closeInfo:	'You can also click anywhere outside the image to close',
			help: {
				close:		'Click to close',
				interact:	'Hover to interact'
			}	
		},
		
		keys: {
			close:	'c',
			prev:	'p',
			next:	'n'
		},
		
		opacity:	0.9,
		padding:	null,
		speed:		400,
		rel:		'lightbox',

		construct: function( )
		{
			this.baseurl = $('script[src*='+this.files.js.lightbox+']:first').attr('src');
			this.baseurl = this.baseurl.substring(0, this.baseurl.indexOf(this.files.js.lightbox));
			var me = this;
			$.each(this.files, function(group, val){
				$.each(this, function(file, val){
					me.files[group][file] = me.baseurl+val;
				});
			});

			return true;
		},
		
		domReady: function ( )
		{
			$('head').append('<link rel="stylesheet" type="text/css" href="'+ this.files.css.lightbox +'" media="screen" />');
			$('body').append('<div id="lightbox-overlay"><div id="lightbox-overlay-text"><p><span id="lightbox-overlay-text-close">'+this.text.help.close+'</span><br/>&nbsp;<span id="lightbox-overlay-text-interact">'+this.text.help.interact+'</span></p></div></div><div id="lightbox"><div id="lightbox-imageBox"><div id="lightbox-imageContainer"><img id="lightbox-image" /><div id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + this.files.images.loading + '" /></a></div></div></div><div id="lightbox-infoBox"><div id="lightbox-infoContainer"><div id="lightbox-infoHeader"><span id="lightbox-caption"><span id="lightbox-caption-title"></span><span id="lightbox-caption-description"></span></span></div><div id="lightbox-infoFooter"><span id="lightbox-currentNumber"></span><span id="lightbox-close"><a href="#" id="lightbox-close-button" title="'+this.text.closeInfo+'">' + this.text.close + '</a></span></div><div id="lightbox-infoContainer-clear"></div></div></div></div>');
			this.resizeBoxes();
			this.repositionBoxes();

			$('#lightbox,#lightbox-overlay,#lightbox-overlay-text-interact').hide();

			$.each(this.files.images, function()
			{
				var preloader = new Image();
				preloader.onload = function() {
					preloader.onload = null;
					preloader = null;
				};	preloader.src = this;
			});

			$(window).resize(function () { $.Lightbox.resizeBoxes(); $.Lightbox.repositionBoxes(); });

			$('#lightbox-nav-btnPrev').hover(function() {
				$(this).css({ 'background' : 'url(' + $.Lightbox.files.images.prev + ') left 45% no-repeat' });
			},function() {
				$(this).css({ 'background' : 'transparent url(' + $.Lightbox.files.images.blank + ') no-repeat' });
			}).click(function() {
				$.Lightbox.showImage($.Lightbox.images.prev());
// JOE: QUI PREV
				return false;
			});

			$('#lightbox-nav-btnNext').hover(function() {
				$(this).css({ 'background' : 'url(' + $.Lightbox.files.images.next + ') right 45% no-repeat' });
			},function() {
				$(this).css({ 'background' : 'transparent url(' + $.Lightbox.files.images.blank + ') no-repeat' });
			}).click(function() {
				$.Lightbox.showImage($.Lightbox.images.next());
// JOE: QUI NEXT
				return false;
			});

			$('#lightbox-overlay-text-about a').click(function(){window.open('http://jquery.com/plugins/project/jquerylightbox_bal'); return false;});
			$('#lightbox-overlay-text-close').hover(
				function(){
					$('#lightbox-overlay-text-interact').fadeIn();
				},
				function(){
					$('#lightbox-overlay-text-interact').fadeOut();
				}
			);

			$.Lightbox.relify();
			return true;
		},
		
		relify: function ( )
		{
			var groups = {};
			var groups_n = 0;
			var orig_rel = this.rel;

			$.each($('[rel*='+orig_rel+']'), function(index, obj){
				var rel = $(obj).attr('rel');
				if ( rel === orig_rel )
				{
					rel = groups_n;
				}
				if ( typeof groups[rel] === 'undefined' )
				{
					groups[rel] = [];
					groups_n++;
				}
				groups[rel].push(obj);
			});
			$.each(groups, function(index, group){
				$(group).lightbox();
			});
			return true;
		},
		
		init: function ( image /*int*/, images /*[]*/ )
		{
			if ( typeof images === 'undefined' )
			{
				images = image;
				image = 0;
			}
			this.images.clear();
			if ( !this.images.add(images) )
			{	return false;	}
			if ( this.images.empty() )
			{
				this.debug('Lightbox started, but no images: ', image, images);
				return false;
			}
			if ( !this.images.active(image) )
			{	return false;	}

			return true;
		},
		
		start: function ( )
		{
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			this.resizeBoxes();
			$('#lightbox-infoFooter').hide();
			$('#lightbox-overlay').css({
				opacity:	this.opacity
			}).fadeIn();
			$('#lightbox').show();
			$('#lightbox-overlay, #lightbox, #lightbox-loading-link, #lightbox-btnClose').click(function() {
				$.Lightbox.finish();
				return false;	
			});
			if ( !this.showImage(this.images.active()) )
			{	this.finish();	return false;	}
			return true;
		},
		
		finish: function ( )
		{
			$('#lightbox').hide();
			$('#lightbox-overlay').fadeOut(function() { $('#lightbox-overlay').hide(); });
			$('embed, object, select').css({ 'visibility' : 'visible' });//.show();
		},
		
		resizeBoxes: function ( )
		{
			var pageSize = this.getPageSize();

			$('#lightbox-overlay').css({
				width:		pageSize.largestWidth,
				height:		pageSize.largestHeight
			});
		},
		
		repositionBoxes: function ( options )
		{
			options = $.extend({}, options);
			var pageSize = this.getPageSize();
			var pageScroll = this.getPageScroll();
			var nHeight = options.nHeight || parseInt($('#lightbox').height(),10) || pageSize.largestHeight/3;
			var nTop = pageScroll.yScroll + (pageSize.windowHeight - nHeight) / 2.5;
			var nLeft = pageScroll.xScroll;
			$('#lightbox').animate({left:nLeft, top:nTop}, 'slow');
		},
		
		showImage: function ( image, options )
		{
			image = this.images.get(image);
			if ( !image ) { return image; }

// JOE, SHOW IMAGE
//pageTracker._trackPageview('/immagine/click/'+image);
// JOE, SHOW IMAGE

			options = $.extend({step:1}, options);
			var skipped_step_1 = options.step > 1 && this.images.active().src !== image.src;
			var skipped_step_2 = options.step > 2 && $('#lightbox-image').attr('src') !== image.src;
			if ( skipped_step_1 || skipped_step_2 )
			{
				this.debug('We wanted to skip a few steps: ', options, image);
				options.step = 1;
			}

			switch ( options.step )
			{
				case 1:
					this.KeyboardNav_Disable();
					$('#lightbox-loading').show();
					$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-infoBox').hide();
					$('#lightbox-imageBox').unbind();

					var preloader = new Image();
					preloader.onload = function() {
						$.Lightbox.showImage(null, {step:2, width:preloader.width, height:preloader.height});
						preloader.onload = null;
						preloader = null;
					};
					preloader.src = image.src;
					if ( !this.images.active(image) ) { return false; }
					break;
				case 2:
					$('#lightbox-image').attr('src', image.src);
					options = $.extend({width:null, height:null}, options);
					if ( this.padding === null || typeof this.padding === 'undefined' || this.padding === NaN )
					{
						this.padding = parseInt($('#lightbox-imageContainer').css('padding-left'), 10) || parseInt($('#lightbox-imageContainer').css('padding'), 10) || 0;
					}

					var iWidth  = options.width;
					var iHeight = options.height;
					var cWidth = $('#lightbox-imageBox').width();
					var cHeight = $('#lightbox-imageBox').height();
					var nWidth	= (iWidth  + (this.padding * 2));
					var nHeight	= (iHeight + (this.padding * 2));
					var dWidth  = cWidth  - nWidth;
					var dHeight = cHeight - nHeight;

					$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: iHeight + (this.padding * 2) }); 
					$('#lightbox-infoBox').css({ width: iWidth+this.padding*2 });

					if ( dWidth === 0 && dHeight === 0 )
					{
						if ( $.browser.msie ) {
							this.pause(250);
						} else {
							this.pause(100);	
						}
						$.Lightbox.showImage(null, {step:3});
					}
					else
					{
						$('#lightbox-imageBox').animate({ width: nWidth, height: nHeight }, this.speed, function ( ) { $.Lightbox.showImage(null, {step:3}); } );
						this.repositionBoxes({'nHeight':nHeight});
					}
					break;

				case 3:
					$('#lightbox-loading').hide();
					$('#lightbox-image').fadeIn('normal', function() {$.Lightbox.showImage(null, {step:4}); });
					this.preloadNeighbours();
					break;

				case 4:
					$('#lightbox-caption-title').html(image.title + (image.description ? ': ' : '') || 'Untitled');
					$('#lightbox-caption-description').html(image.description || '&nbsp;');
					
					if ( this.images.size() > 1 )
					{
						$('#lightbox-currentNumber').html(this.text.image + '&nbsp;' + ( image.index + 1 ) + '&nbsp;' + this.text.of + '&nbsp;' + this.images.size());
					} else
					{
						$('#lightbox-currentNumber').html('&nbsp;');
					}

					$('#lightbox-imageBox').unbind('mouseover').mouseover(function(){
						 $('#lightbox-infoBox').slideDown('fast');
					 });

					$('#lightbox-infoBox').unbind('mouseover').mouseover(function(){
						 $('#lightbox-infoFooter').slideDown('fast');
					 });

					$('#lightbox-nav-btnPrev, #lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + this.files.images.blank + ') no-repeat' });

					if ( !this.images.first(image) ) {
						$('#lightbox-nav-btnPrev').show();
					}

					if ( !this.images.last(image) ) {
						$('#lightbox-nav-btnNext').show();
					}
					$('#lightbox-nav').show();
					this.KeyboardNav_Enable();
					break;

				default:
					this.debug('Don\'t know what to do: ',options);
					return this.showImage(image, {step:1});
			}
			
			return true;
		},
		
		preloadNeighbours: function ( )
		{
			
			if ( this.images.single() || this.images.empty() )
			{	return true;	}
			
			var image = this.images.active();
			if ( !image ) { return image; }
			
			var prev = this.images.prev(image);
			var objNext;
			if ( prev ) {
				objNext = new Image();
				objNext.src = prev.src;
			}
			
			var next = this.images.next(image);
			if ( next ) {
				objNext = new Image();
				objNext.src = next.src;
			}
		},
		
		debug: function ( options )
		{
			var con = null;
			if ( typeof console !== 'undefined' && typeof console.log !== 'undefined' )
			{	con = console;	}
			else if ( typeof window.console !== 'undefined' && typeof window.console.log !== 'undefined')
			{	con = window.console;	}
			
			if ( con )
			{
				if ( typeof arguments !== 'undefined' && arguments.length > 1)
				{	con.log(arguments);	return arguments;	}
				else
				{	con.log(options);	return options;		}
			}
		},
		
		KeyboardNav_Enable: function ( ) {
			$(document).keydown(function(objEvent) {
				$.Lightbox.KeyboardNav_Action(objEvent);
			});
		},
		
		KeyboardNav_Disable: function ( ) {
			$(document).unbind();
		},
		
		KeyboardNav_Action: function ( objEvent ) {
			var keycode, escapeKey;
			if ( objEvent === null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			
			var key = String.fromCharCode(keycode).toLowerCase();
			
			if ( key === this.keys.close || keycode === escapeKey )
			{	return $.Lightbox.finish();		}
			
			if ( key === this.keys.prev || keycode === 37 )
			{
				return $.Lightbox.showImage($.Lightbox.images.prev());
			}
			
			if ( key === this.keys.next || keycode === 39 )
			{
				return $.Lightbox.showImage($.Lightbox.images.next());
			}
			
			return true;
		},
		
		getPageSize: function ( )
		{
			var xScroll, yScroll;
	
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else {
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
	
			var windowWidth, windowHeight;
	
			if (self.innerHeight) {
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) {
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) {
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
	
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
	
	
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}

			var largestWidth;
			var largestHeight;
			var smallestWidth;
			var smallestHeight;

			if ( pageWidth >= windowWidth )
			{	largestWidth = pageWidth; smallestWidth = windowWidth;	}
			else
			{	largestWidth = windowWidth; smallestWidth = pageWidth;	}

			if ( pageHeight >= windowHeight )
			{	largestHeight = pageHeight; smallestHeight = windowHeight;	}
			else
			{	largestHeight = windowHeight; smallestHeight = pageHeight;	}
			
			var arrayPageSize = {'pageWidth':pageWidth,'pageHeight':pageHeight,'windowWidth':windowWidth,'windowHeight':windowHeight,'largestWidth':largestWidth,'largestHeight':largestHeight};
			return arrayPageSize;
		},
		
		getPageScroll: function ( ) {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
			return arrayPageScroll;
		},
		
		
		pause: function ( ms ) {
			var date = new Date();
			var curDate = null;
			do { curDate = new Date(); }
			while ( curDate - date < ms);
		}
	
	});


	$(function() {
		$.Lightbox = $.Lightbox || new $.LightboxClass();

		$.Lightbox.domReady();
	});
	

})(jQuery);

