(function($) {
	$.fn.lightbox = function(id, width, title, closeButton) {
		// Overlay contains the translucent background, inner is a wrapper that handles positioning.
		var overlay = $(document.createElement('div')).attr('id', 'overlay_' + id).addClass('overlay');
		var inner = $(document.createElement('div')).addClass('overlayInner').css('width', width).appendTo(overlay);

		if (title) {
			$(document.createElement('span')).addClass('overlayTitle').append(title).appendTo(inner);
		}
		
		if (closeButton) {
			$(document.createElement('img')).attr('src', 'images/gallery_close.png').addClass('overlayClose').appendTo(inner).bind('click', function() { $('.overlay').hide(); });
		}
		
		$(document.createElement('div')).addClass('clear').appendTo(inner);
		
		// Loop through the elements that lightbox where called on.
		this.each(function() {
			$(this).appendTo(inner);
			$(this).bind('click', function() { // Required to cancel out the bubbling click event on overlay
				return false;
			});
		});
		
		$(inner).bind('click', function() { // Required to cancel out the bubbling click event on overlay
			return false;
		});
		
		$(overlay).bind('click', function() {
			$('.overlay').hide();
		});
		
		return overlay; // Return the element to maintain some sort of chainability.
	};
	
})(jQuery);

function lightboxImage(id, linkTarget, imagePath, width, title, closeButton, animation) {
	if (window.jQuery) { // Will only equate to true if jQuery has been included.
		
		if (animation == null || !animation.length) {
			animation = 'swing';
		}
		
		$(linkTarget).click(function() {
			if ($('#overlay_' + id).length) { // Overlay already exists, no need to create images again, just show it.
				$('#overlay_' + id).show();
			}
			else { // Overlay doesn't exist, create a new one.
				$(document.createElement('div'))  // Create wrapper, append img with preloader, lightbox it, append it to body, show.
					.addClass('overlayImageWrap')
					.append(
						$(document.createElement('img'))
						.attr({ 
							src: 'images/loader.gif', 
							id: 'overlay_' + id + '_Image' 
						}))
					.lightbox(id, width, title, closeButton)
					.appendTo('body')
					.show();
	
				$(document.createElement('img')).attr('src', imagePath).load(function() { // This function triggers once the image is done loading, then switches the preloader for it.
					$(this).hide().insertAfter($('#overlay_' + id + '_Image'));
					$('#overlay_' + id + '_Image').hide().remove();
					$(this).attr('id', 'overlay_' + id + '_Image').show();
					$('#overlay_' + id).find('.overlayInner').css('height', '100px').animate({ height: $(this).height() + 18, width: $(this).width() }, 500, animation);
				});	
			}
		});		
	}
	else {
		// console.log("Cannot use lightboxImage Loader. jQuery has not been included.");
	}
}

function lightboxGallery(id, linkTarget, dataSource, startIndex, closeButton, animation) {
	var preloader = $(document.createElement('img')).addClass('gallery_image').attr({ src: 'images/gallery_loader.gif', className: 'gallery_loader' });
	var overlay = $(preloader).lightbox(id, '200px', '', true).hide().appendTo('body');

	if (typeof(dataSource) == 'string') {
	  // URL to JSON data
	  var load = function() {
	  jQuery.getJSON(dataSource, function(data, status) {
      $(overlay).data('imageData', data);
      if ($(overlay).css('display') != 'none') {
        $($(overlay).data('last_clicked')).click();
      }
    });
	  };
	  
    //setTimeout(load, 5000);
    load();
	} else {
	  // JS array of data
  	$(overlay).data('imageData', dataSource);
	}
	
	if (animation == null || !animation.length) {
		animation = 'swing';
	}
	
	$(linkTarget).data('overlay', $(overlay)[0]);
	$(overlay).data('animation', animation);
	
	$(linkTarget).bind('click.gallery', lightboxGalleryClick);
}

/* KNOWN BUGS:
  - Scrollbar width detection doesn't work in Webkit-based browsers
	- Wobbles a bit when scaling to an almost the same size image
*/

function resizeLightbox(adjustTo) {
  if (!$(document).data('scrollbarWidth')) {
    $(document).data('scrollbarWidth', scrollbarWidth());
  }
  
  var overlay = $(adjustTo).parents('.overlay');
	var width = $(adjustTo).find('.gallery_image').width();
	if (width < 300)
	{
		width = 300;
	}
	$(overlay).find('.overlayImageWrap').width(width);

	var height = $(adjustTo).height();
	var maxHeight = $(overlay).height() - 100;
	if (height > maxHeight)
	{
		height = maxHeight;
		width += $(document).data('scrollbarWidth');
  	$(overlay).find('.overlayImageWrap').width(width);
    $(overlay).find('.overlayImageWrap').css({ overflow: 'auto', height: height });
	}
	else {
		height = $(adjustTo).height();
    $(overlay).find('.overlayImageWrap').css({ overflow: 'hidden', height: height });
	}
	var controlHeight = $(overlay).find('.controlBox').height();
	$(overlay).find('.overlayInner').stop().animate({ height: height + controlHeight, width: width }, 500, $(overlay).data('animation'));
}

function lightboxGalleryClick () {
  var overlay = $(this).data('overlay');
  $(overlay).data('last_clicked', this);
  
  if (typeof($(this).data('gallery_slide')) != 'undefined') { // gallery already initialized, make sure it starts at the right image and show it.
		var goingTo = $(this).data('gallery_slide');

		// Need to find the one we're looking for, then reshuffle the whole thing!
		// Worst case scenario: We want to show the last one in the system, and need to reshuffle all other elements, how slow would that be compared to using indexes?
		$(goingTo).prevAll().appendTo($(overlay).find('.overlayImageWrap')); // Get all the siblings before this one, and move them to the end.
		$(overlay).find('.active').removeClass('active').addClass('inactive'); // Set the previous active slide to inactive
		$(goingTo).removeClass('inactive').addClass('active'); // Give our new slide the active class.
		$(overlay).find('.overlayInner').css({width: '200px', height: '200px'});
		$(overlay).show();
		
		var active = $(overlay).find('.active');
    updateCounter(active);
    resizeLightbox(active);
	}	else if (typeof ($(overlay).data('imageData')) != 'undefined') { // gallery not initialized
		var wrapper = $(document.createElement('div')).addClass('overlayImageWrap');
		
		var overlayIndex = ($(overlay).attr('id').split('_'))[1];
		
		var next = function() {
		  var overlay = $(this).parents('.overlay');
			var active = $(overlay).find('.active');
			$(active).appendTo($(overlay).find('.overlayImageWrap'));
			$(active).removeClass('active').addClass('inactive');
			newActive = $(overlay).find('.inactive:first').removeClass('inactive').addClass('active');
			$(overlay).find('counter').text(newActive.data('galleryIndex'));
			
			updateCounter(newActive);
      resizeLightbox(newActive);
		};

		var imageLoad = function() {
		  var replace = $(this).data('replace');
			replace.replaceWith(this);
			$(this).attr('id', replace.attr('id'));
			$(this).data('replace', null);

			var active = $(this).parents('.overlay .active');
			if (active.length) {
        resizeLightbox(active);
			}
		};
		
		var imageArray = $(overlay).data('imageData');
		for (var i = 0; i < imageArray.length; i++) {
			var cssClass = "";
			(this.id == imageArray[i].ThumbnailID) ? cssClass = "active" : cssClass = "inactive";
			
      var container = $(document.createElement('div')).addClass(cssClass).attr('id', 'gallery_' + overlayIndex + '_' + i);
      if (imageArray[i].Title) {
			  var title = $(document.createElement('div')).addClass('gallery_title').attr('id', 'gallery_' + overlayIndex + '_' + i + '_title').append(imageArray[i].Title);
      } else {
        var title = '';
      }
			var extra = $(document.createElement('div')).addClass('gallery_text').attr('id', 'gallery_' + overlayIndex + '_' + i + '_extra').append(imageArray[i].Extra);
			
			$(jq('#' + imageArray[i].ThumbnailID)).data('gallery_slide', $(container)[0]);
			
			$(container).append(title, extra);
			$(container).data('galleryIndex', i+1);
			
      var image = $(document.createElement('img')).addClass('gallery_image').attr('src', imageArray[i].ImageUrl).click(next);
			if (image.attr('complete')) {
			  container.append(image);
			  resizeLightbox(container);
			} else {
        var preloader = $(document.createElement('img')).addClass('gallery_image').attr({ src: '/images/gallery_loader.gif', id: 'gallery_' + overlayIndex + '_' + i + '_image' });			  image.data('replace', preloader)
			  image.load(imageLoad);
			  container.append(preloader);
			}
			
			$(wrapper).append(container);
		}
		
		$(overlay).find('.gallery_loader').replaceWith(wrapper);
		var active = $(overlay).find('.active');

		// Generate "control box"
		$(overlay).find('.overlayClose').after('<div class="controlBox"><img class="prevArrow" src="/images/gallery_back.png" alt="«" /><span> <span class="counter">' + active.data('galleryIndex') + '</span> / ' + imageArray.length + ' </span><img class="nextArrow" src="/images/gallery_fwd.png" alt="»" /></div>')
		var nextArrow = $('.nextArrow');
		var prevArrow = $('.prevArrow');
		
		$(nextArrow).click(next);
		
		$(prevArrow).click(function() {
		  var overlay = $(this).parents('.overlay');
			var active = $(overlay).find('.active');
			$(active).removeClass('active').addClass('inactive');
			active = $(overlay).find('.inactive:last').removeClass('inactive').addClass('active').prependTo($(overlay).find('.overlayImageWrap'));

			updateCounter(active);
      resizeLightbox(active);
		});
		
		$(active).prevAll().appendTo($(overlay).find('.overlayImageWrap')); // reshuffle elements
		$(overlay).show();

		if (active.length) {
      resizeLightbox(active);
		}
	} else { // gallery data not loaded
		$(overlay).show();
	}
	
	return false;
}

function updateCounter(active) {
  var overlay = $(active).parents('.overlay');
	$(overlay).find('.counter').text(active.data('galleryIndex'));
}

function scrollbarWidth() {
  var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
  // Append our div, do our calculation and then remove it
  $('body').append(div);
  var w1 = $('div', div).innerWidth();
  div.css('overflow-y', 'scroll');
  var w2 = $('div', div).innerWidth();
  $(div).remove();
  if (w1 == w2) {
    return 16;
  }
  return (w1 - w2);
}

function lightboxYT(id, videoId, title) {
  if (window.jQuery) { // Will only equate to true if jQuery has been included.
    $(document.createElement('div'))  // Create wrapper, append img with preloader, lightbox it, append it to body, show.
      .attr('id', 'video_'+videoId)
      .addClass('playerWrapper')
      .lightbox(id, 640, title, true)
      .appendTo('body')
      .show()
      .click( function() {
        $(this).remove();
      })
      .find('.overlayClose').click( function() {
        $(this).parents('.overlay').remove();
      });

    swfobject.embedSWF("http://www.youtube.com/v/"+videoId+"?rel=0&autoplay=1", "video_"+videoId,
      "640", "385", "8");
	}
}
