/*
 
 Awkward Showcase - jQuery plugin 
 http://www.jquery.com
 http://www.awkwardgroup.com/sandbox/awkward-showcase-a-jquery-plugin/
 http://demo.awkward.se/showcase
 Version: 0.2.4 (Beta)

 Copyright (C) 2010 Awkward (http://www.awkward.se)
 Licensed under Attribution-ShareAlike 3.0 Unported
 http://creativecommons.org/licenses/by-sa/3.0/

*/

(function(jQuery)
{
	jQuery.fn.awShowcase = function(options)
	{
		// Default configuration properties
		var defaults =
		{
			width:					700,
			height:					470,
			auto:					true,
			interval:				3000,
			continuous:				true,
			loading:				true,
			tooltip_width:			200,
			tooltip_icon_width:		32,
			tooltip_icon_height:	32,
			tooltip_offsetx:		18,
			tooltip_offsety:		0,
			arrows:					true,
			buttons:				true,
			btn_numbers:			false,
			keybord_keys:			false,
			mousetrace:				false,
			pauseonover:			true,
			transition:				'fade', /* vslide/hslide/fade */
			transition_speed:		500,
			show_caption:			'onload', /* onload/onhover/show */
			thumbnails:				false,
			thumbnails_position:	'outside-last', /* outside-last/outside-first/inside-last/inside-first */
			thumbnails_direction:	'vertical', /* vertical/horizontal */
			thumbnails_slidex:		0 /* 0 = auto / 1 = slide one thumbnail / 2 = slide two thumbnails / etc. */
		};
		
		// Declare and set up some important variables
		options = jQuery.extend(defaults, options);
		var current_id = 0;
		var previous_id = 0;
		var break_loop = false;
		var pause_loop = false;
		var myInterval = null;
		var showcase = jQuery(this);
		
		// Create the content and thumbnail array
		var contentArray = [];
		var thumbnailArray = [];
		var content_count = 0;
		showcase.children('div.slide').each(function()
		{
			// Add content to the array and remove from dom
			var object = jQuery(this);
			
			// If thumbnails are activated
			if (options.thumbnails)
			{
				// Get thumbnail and put in array
				var thumb = object.find('.showcase-thumbnail');
				thumbnailArray.push(thumb);
				thumb.remove();
			}
			
			// Add content html in array
			contentArray.push(object.html());
			object.remove();
			content_count++;
		});
		
		// Set up the content wrapper
		var content_wrapper = jQuery(document.createElement('div'))
			.css('width', options.width)
			.css('height', options.height)
			.css('overflow', 'hidden')
			.css('position', 'relative')
			.addClass('showcase-content-wrapper')
			.prependTo(showcase);

		// Returns the specified content (by array id)
		function getContent(id)
		{
			return jQuery(document.createElement('div'))
				.attr('id', 'showcase-content-' + id)
				.css('width', options.width + 'px')
				.css('height', options.height + 'px')
				.css('overflow', 'hidden')
				.css('position', 'absolute')
				.addClass('showcase-content')
				.html(contentArray[id]);
		}
		
		// Function that runs when content is set to change automatically
		function autoChange()
		{
			// Set next content id
			var nextID = parseInt(current_id)+1;
			// If the next id is outside the array and continuous is set to true set the id to 0
			if (nextID == content_count && options.continuous) { nextID = 0; }
			// If continuous is set to false break the auto change
			else if (nextID == content_count && !options.continuous) { break_loop = true; clearInterval(myInterval); }
			// Don't change the content if the auto change is broken
			if (!break_loop) { changeContent(nextID, 'next'); }
		}
		
		// Changes the content (no explanation/comments needed :)
		function changeContent(id, direction)
		{
			// If the next content isn't the current content
			if (current_id != id)
			{
				var obj;
				var obj2;
				
				// If we want to display the next content
				if (id > current_id && direction != 'previous' || direction == 'next')
				{
					// Get current content element
					obj = jQuery(showcase).find('#showcase-content-' + parseInt(current_id));
					if (options.transition == 'vslide')
					{
						displayAnchors(obj, true);
						displayCaption(obj, true);
						jQuery(obj).animate({
							left: -(options.width+100)
							}, options.transition_speed+300, function() {
								obj.remove();
							});
					}
					else if (options.transition == 'hslide')
					{
						displayAnchors(obj, true);
						displayCaption(obj, true);
						jQuery(obj).animate({
							top: -(options.height+100)
							}, options.transition_speed+300, function() {
								obj.remove();
							});
					}
					else
					{
						displayAnchors(obj, true);
						displayCaption(obj, true);
						jQuery(obj).fadeOut(options.transition_speed, function() {
							obj.remove();
						});
					}
					
					// Get next element
					obj2 = getContent(id);
					if (options.transition == 'vslide')
					{
						obj2.css('left', options.width + 'px');
						jQuery(obj2).animate({
							left: '0px'
							}, options.transition_speed, function() {
								displayAnchors(obj2);
								displayCaption(obj2);
							});
					}
					else if (options.transition == 'hslide')
					{
						obj2.css('top', options.height + 'px');
						jQuery(obj2).animate({
							top: '0px'
							}, options.transition_speed, function() {
								displayAnchors(obj2);
								displayCaption(obj2);
							});
					}
					else
					{
						obj2.css('left', '0px');
						obj2.css('display', 'none');
						jQuery(obj2).fadeIn(options.transition_speed, function() {
								displayAnchors(obj2);
								displayCaption(obj2);
								obj.remove();
							});
					}
					content_wrapper.append(obj2);
				}
				// If we want to display the previous content
				else if (id < current_id || direction == 'previous')
				{
					// Get current content element
					obj = jQuery(showcase).find('#showcase-content-' + parseInt(current_id));
					if (options.transition == 'vslide')
					{
						displayAnchors(obj, true);
						displayCaption(obj, true);
						jQuery(obj).animate({
							left: (options.width+100) + 'px'
							}, options.transition_speed+300, function() {
								obj.remove();
						});
					}
					else if (options.transition == 'hslide')
					{
						displayAnchors(obj, true);
						displayCaption(obj, true);
						jQuery(obj).animate({
							top: (options.height+100) + 'px'
							}, options.transition_speed+300, function() {
								obj.remove();
						});
					}
					else
					{
						displayAnchors(obj, true);
						displayCaption(obj, true);
						jQuery(obj).fadeOut(options.transition_speed, function() {
							obj.remove();
						});
					}
					
					// Get next element
					obj2 = getContent(id);
					if (options.transition == 'vslide')
					{
						obj2.css('left', '-' + options.width + 'px');
						content_wrapper.append(obj2);
						jQuery(obj2).animate({
							left: '0px'
							}, options.transition_speed, function() {
								displayAnchors(obj2);
								displayCaption(obj2);
						});
					}
					else if (options.transition == 'hslide')
					{
						obj2.css('top', '-' + options.height + 'px');
						content_wrapper.append(obj2);
						jQuery(obj2).animate({
							top: '0px'
							}, options.transition_speed, function() {
								displayAnchors(obj2);
								displayCaption(obj2);
						});
					}
					else 
					{
						obj2.css('left', '0px');
						obj2.css('display', 'none');
						jQuery(obj2).fadeIn(options.transition_speed, function() {
							displayAnchors(obj2);
							displayCaption(obj2);
							//obj.remove();
						});
					}
					content_wrapper.append(obj2);
				}
				
				// Change previous and current content id
				previous_id = current_id;
				current_id = id;
				
				// Slide thumbnail wrapper
				if (options.thumbnails)
				{
					if (current_id > previous_id && direction != 'previous' || direction == 'next')
					{
						slideThumbnailWrapper('forward', true);
					}
					else if (current_id < previous_id || direction == 'previous')
					{
						slideThumbnailWrapper('backward', true);
					}
				}
				
				// Change click handlers for arrows
				if (options.arrows)
				{
					jQuery(showcase).find('.showcase-arrow-previous')
						.unbind('click')
						.click(function() {
							if (myInterval) { pause_loop = true; clearInterval(myInterval); }
							changeContent((current_id === 0) ? content_count-1 : parseInt(current_id)-1, 'previous');
						});
						jQuery(showcase).find('.showcase-arrow-next')
						.unbind('click')
						.click(function() {
							if (myInterval) { pause_loop = true; clearInterval(myInterval); }
							changeContent((current_id == content_count-1) ? 0 : parseInt(current_id)+1, 'next');
						});
				}
				
				// Change active class for buttons and thumbnails
				var i;
				if (options.buttons)
				{
					i = 0;
					showcase.find('.showcase-button-wrapper div').each(function()
					{
						var object = jQuery(this);
						object.removeClass('blipon active');
						object.addClass('blipoff');
						if (i == current_id) { object.removeClass('blipoff'); object.addClass('blipon active'); }
						i++;
					});
				}
				if (options.thumbnails)
				{
					i = 0;
					showcase.find('.showcase-thumbnail').each(function()
					{
						var object = jQuery(this);
						object.removeClass('active');
						if (i == current_id) { object.addClass('active'); }
						i++;
					});
				}
				
				// If caption is set to 'show'
				if (options.show_caption == 'show') { jQuery(obj2).find('.showcase-caption').show(); }
			}
		}
		
		// Activating the keybord arrow keys
		if (options.keybord_keys)
		{
			jQuery(document).keydown(function(e)
			{
				// Left arrow
				if (e.keyCode == 37) { changeContent((current_id === 0) ? content_count-1 : parseInt(current_id)-1, 'previous'); }
				// Right arrow
				if (e.keyCode == 39) { changeContent((current_id == content_count-1) ? 0 : parseInt(current_id)+1, 'next'); }
			});
		}
		
		// Slide thumbnail wrapper
		var thumbnailSlidePosition = 0;
		function slideThumbnailWrapper(direction, check, backwardforward)
		{
			var doTheSlide = true;
			var thumbnailHeightOrWidth = getElementHeight(jQuery(thumb_wrapper).find('.showcase-thumbnail'));
			if (options.thumbnails_direction == 'horizontal')
			{
				thumbnailHeightOrWidth = getElementWidth(jQuery(thumb_wrapper).find('.showcase-thumbnail'));
			}
			var multiplySlidePosition = 1;
			
			// Set slide x
			if (options.thumbnails_slidex === 0) { options.thumbnails_slidex = thumbnailsPerPage; }
			
			// Check if we need to do the slide
			if (check)
			{
				var thumbnailSlidePositionCopy = thumbnailSlidePosition;
				var thumbnailsScrolled = 0;
				while (thumbnailSlidePositionCopy < 0)
				{
					if (options.thumbnails_direction == 'horizontal')
					{
						thumbnailSlidePositionCopy += getElementWidth(jQuery(thumbnailArray[0]));
					}
					else
					{
						thumbnailSlidePositionCopy += getElementHeight(jQuery(thumbnailArray[0]));
					}
					thumbnailsScrolled++;
				}
				
				var firstVisible = thumbnailsScrolled;
				var lastVisible = thumbnailsPerPage + thumbnailsScrolled -1;
				
				// Check if the next active thumbnail is outside the visible area
				if (current_id >= firstVisible && current_id <= lastVisible) { doTheSlide = false; }
				
				// If the next active thumbnail is far away..
				var distance;
				if ((current_id - lastVisible) > options.thumbnails_slidex)
				{
					distance = current_id - lastVisible;
					
					while (distance > options.thumbnails_slidex)
					{
						distance -= options.thumbnails_slidex;
						multiplySlidePosition++;
					}
				}
				else if ((firstVisible - current_id) > options.thumbnails_slidex)
				{
					distance =  firstVisible - current_id;
					
					while (distance > options.thumbnails_slidex)
					{
						distance -= options.thumbnails_slidex;
						multiplySlidePosition++;
					}
				}
				else { multiplySlidePosition = 1; }
			}
			
			if (direction == 'forward' && doTheSlide)
			{
				if (options.thumbnails_direction == 'vertical' && options.height < (thumbnailStretch + thumbnailSlidePosition))
				{
					thumbnailSlidePosition -= thumbnailHeightOrWidth * (options.thumbnails_slidex * multiplySlidePosition);
				}
				else if (options.thumbnails_direction == 'horizontal' && options.width < (thumbnailStretch + thumbnailSlidePosition))
				{
					thumbnailSlidePosition -= thumbnailHeightOrWidth * (options.thumbnails_slidex * multiplySlidePosition);
				}
				else if (current_id === 0)
				{
					if (!backwardforward) { thumbnailSlidePosition = 0; }
				}
				if (options.thumbnails_direction == 'horizontal') { thumb_wrapper.animate({ left: thumbnailSlidePosition }, 300); }
				else { thumb_wrapper.animate({ top: thumbnailSlidePosition }, 300); }
			}
			else if (doTheSlide)
			{
				if (thumbnailSlidePosition < 0)
				{
					thumbnailSlidePosition += thumbnailHeightOrWidth * (options.thumbnails_slidex * multiplySlidePosition);
				}
				else if (current_id == content_count-1)
				{
					if (!backwardforward)
					{
						thumbnailSlidePosition -= thumbnailHeightOrWidth * (options.thumbnails_slidex * multiplySlidePosition);
					}
				}
				else { thumbnailSlidePosition = 0; }
				if (options.thumbnails_direction == 'horizontal') { thumb_wrapper.animate({ left: thumbnailSlidePosition }, 300); }
				else { thumb_wrapper.animate({ top: thumbnailSlidePosition }, 300); }
			}
		}
		
		// Displays the caption
		function displayCaption(container, fadeOut)
		{
			var caption = container.find('.showcase-caption');
			if (!fadeOut)
			{
				if (options.show_caption == 'onload') { caption.fadeIn(300); }
				else if (options.show_caption == 'onhover')
				{
					jQuery(container).mouseenter(function()
					{
						caption.fadeIn(300);
					});
					
					jQuery(container).mouseleave(function()
					{
						caption.stop(true, true).fadeOut(100);
					});
				}
			}
			else { caption.stop(true, true).fadeOut(300); }
		}
		
		// Displays the anchors in the current slide
		function displayAnchors(container, fadeOut)
		{
			// Get each anchor tooltip
			container.children('a.showcase-tooltip').each(function()
			{
				if (!fadeOut)
				{
					// Get coordinates
					var coords = jQuery(this).attr('coords');
					coords = coords.split(',');
					// Style and position anchor
					jQuery(this).addClass('showcase-plus-anchor');
					jQuery(this).css('position', 'absolute');
					jQuery(this).css('display', 'none');
					jQuery(this).css('width', options.tooltip_icon_width);
					jQuery(this).css('height', options.tooltip_icon_height);
					jQuery(this).css('left', parseInt(coords[0]) - (parseInt(options.tooltip_icon_width)/2));
					jQuery(this).css('top', parseInt(coords[1]) - (parseInt(options.tooltip_icon_height)/2));
					var content = jQuery(this).html();
					jQuery(this).mouseenter(function()
					{
						animateTooltip(container, coords[0], coords[1], content);
					});
					jQuery(this).mouseleave(function()
					{
						animateTooltip(container, coords[0], coords[1], content);
					});
					jQuery(this).html('');
					jQuery(this).fadeIn(300);
				}
				else
				{
					jQuery(this).stop(true, true).fadeOut(300);
				}
			});
		}
		
		// Controls the animation for the tooltips
		var tooltip = null;
		function animateTooltip(container, x, y, content)
		{
			// if tooltip is null (doesn't exsist)
			if (tooltip === null)
			{
				// Create the tooltip
				tooltip = jQuery(document.createElement('div'))
					.addClass('showcase-tool-tip')
					.css('display', 'none')
					.css('position', 'absolute')
					.css('max-width', options.tooltip_width)
					.html(content);
				container.append(tooltip);
				
				// Position the tooltip (this is where we try not to display the tooltip outside the content wrapper)
				var tooltip_paddingx = parseInt(tooltip.css('padding-right'))*2 + parseInt(tooltip.css('border-right-width'))*2;
				var tooltip_paddingy = parseInt(tooltip.css('padding-bottom'))*2 + parseInt(tooltip.css('border-bottom-width'))*2;
				lastx = parseInt(x) + tooltip.width() + tooltip_paddingx;
				lasty = parseInt(y) + tooltip.height() + tooltip_paddingy;
				
				if (lastx < options.width)
				{
					tooltip.css('left', parseInt(x) + parseInt(options.tooltip_offsetx));
				}
				else
				{
					tooltip.css('left', (parseInt(x) - parseInt(options.tooltip_offsetx)) - (parseInt(tooltip.width()) + parseInt(options.tooltip_offsetx)));
				}
				
				if (lasty < options.height)
				{
					tooltip.css('top', parseInt(y) + parseInt(options.tooltip_offsety));
				}
				else
				{
					tooltip.css('top', (parseInt(y) - parseInt(options.tooltip_offsety)) - (parseInt(tooltip.height()) + parseInt(tooltip_paddingy)));
				}
				
				// Fade in the tooltip
				tooltip.fadeIn(400);
			}
			else
			{
				// Fade out the tooltip
				tooltip.fadeOut(400);
				// Remove it from the DOM
				tooltip.remove();
				// And set the variable to null
				tooltip = null;
			}
		}
		
		// Traces the mouse position (used fpr positioning anchors)
		if (options.mousetrace)
		{
			// Create the div tha displays the coordinates
			var mousetrace = jQuery(document.createElement('div'))
				.css('position', 'absolute')
				.css('top', '0')
				.css('background-color', '#fff')
				.css('color', '#000')
				.css('padding', '3px 5px')
				.css('x-index', '30')
				.html('X: 0 Y: 0');
			showcase.append(mousetrace);
			var offset = showcase.offset();
			// Print the coordinates
			content_wrapper.mousemove(function(e){ mousetrace.html('X: ' + (e.pageX - offset.left)  + ' Y: ' + (e.pageY - offset.top)); });
		}
		
		/* Returns the correct height for the element, including padding and borders. */
		function getElementHeight(el, incHeight, incMargin, incPadding, incBorders)
		{
			incHeight = typeof(incHeight) != 'undefined' ? incHeight : true;
			incMargin = typeof(incMargin) != 'undefined' ? incMargin : true;
			incPadding = typeof(incPadding) != 'undefined' ? incPadding : true;
			incBorders = typeof(incBorders) != 'undefined' ? incBorders : true;
			var elHeight = (incHeight) ? jQuery((el)).height() : 0;
			var elMargin = (incMargin) ? parseFloat(jQuery((el)).css('margin-top')) + parseFloat(jQuery(el).css('margin-bottom')) : 0;
			var elPadding = (incPadding) ? parseFloat(jQuery((el)).css('padding-top')) + parseFloat(jQuery(el).css('padding-bottom')) : 0;
			var elBorder = (incBorders) ? parseFloat(jQuery((el)).css('border-top-width')) + parseFloat(jQuery((el)).css('border-bottom-width')) : 0;
			elHeight += elMargin + elPadding + elBorder;
			return elHeight;
		}
		
		/* Returns the correct width for the element, including width, margin, padding and borders. */
		function getElementWidth(el, incWidth, incMargin, incPadding, incBorders)
		{
			incWidth = typeof(incWidth) != 'undefined' ? incWidth : true;
			incMargin = typeof(incMargin) != 'undefined' ? incMargin : true;
			incPadding = typeof(incPadding) != 'undefined' ? incPadding : true;
			incBorders = typeof(incBorders) != 'undefined' ? incBorders : true;
			var elWidth = (incWidth) ? jQuery((el)).width() : 0;
			var elMargin = (incMargin) ? parseFloat(jQuery((el)).css('margin-left')) + parseFloat(jQuery(el).css('margin-right')) : 0;
			var elPadding = (incPadding) ? parseFloat(jQuery((el)).css('padding-left')) + parseFloat(jQuery((el)).css('padding-right')) : 0;
			var elBorder = (incBorders) ? parseFloat(jQuery((el)).css('border-left-width')) + parseFloat(jQuery((el)).css('border-right-width')) : 0;
			elWidth += elMargin + elPadding + elBorder;
			return elWidth;
		}
		
		
		// SET UP THE PLUGIN
		// Declare the thumbnail wrapper
		var thumb_wrapper;
		var thumbnailStretch = 0;
		var thumbnailsPerPage = 0;
		
		if (options.thumbnails)
		{
			// Create wrapper
			thumb_container = jQuery('<div />');
			thumb_restriction = jQuery('<div />');
			thumb_wrapper = jQuery('<div />');
			
			// Add content to thumbnail wrapper
			for (var i = thumbnailArray.length-1; i >= 0; --i)
			{
				var thumbnail = jQuery(thumbnailArray[i]).css({'overflow' : 'hidden'});
				thumbnail.attr('id', 'showcase-thumbnail-' + i);
				thumbnail.addClass((i === 0) ? 'active' : '');
				thumbnail.click(function(a, b)
				{
					// This function is used to extract the correct i value on click
					return function()
					{
						// Disable auto change on click
						if (myInterval) { pause_loop = true; clearInterval(myInterval); }
						changeContent(a, b);
					};
				}(i, ''));	
				thumb_wrapper.prepend(thumbnail);
			}
			
			// Style an position thumbnail container and content wrapper
			// + insert thumbnail container
			if (options.thumbnails_position == 'outside-first' || options.thumbnails_position == 'outside-last')
			{
				if (options.thumbnails_direction != 'horizontal')
				{
					/* outside & vertical */
					content_wrapper.css('float', 'left');
					thumb_container.css('float', 'left');
					thumb_container.css('height', options.height);
				}
				else
				{
					/* outside & horizontal */
					jQuery(thumb_wrapper).find('.showcase-thumbnail').css('float', 'left');
					//jQuery(thumb_wrapper).append(jQuery('<div />').addClass('clear'));
				}
				
				if (options.thumbnails_position == 'outside-last')
				{
					/* outside-last */
					showcase.append(thumb_container);
					if (options.thumbnails_direction != 'horizontal') { showcase.append(jQuery('<div />').addClass('clear')); }
				}
				else
				{
					/* outside-first */
					showcase.prepend(thumb_container);
					if (options.thumbnails_direction != 'horizontal') { showcase.append(jQuery('<div />').addClass('clear')); }
				}
			}
			else
			{
				thumb_container.css({'position' : 'absolute', 'z-index' : 20});
				if (options.thumbnails_direction == 'horizontal') 
				{
					/* inside & horizontal */
					thumb_container.css({'left' : 0, 'right' : 0});
					jQuery(thumb_wrapper).find('.showcase-thumbnail').css('float', 'left');
					jQuery(thumb_wrapper).append(jQuery('<div />').addClass('clear'));
					
					/* inside first */
					if (options.thumbnails_position == 'inside-first') { thumb_container.css('top', 0); }
					/* inside last */
					else { thumb_container.css('bottom', 0); }
				}
				else 
				{
					/* inside & vertical */
					thumb_container.css({'top' : 0, 'bottom' : 0});
					/* inside first */
					if (options.thumbnails_position == 'inside-first') { thumb_container.css('left', 0); }
					/* inside last */
					else { thumb_container.css('right', 0); }
				}
				content_wrapper.prepend(thumb_container);
			}
			
			// Add class and style to thumbnail container
			thumb_container.addClass('showcase-thumbnail-container');
			thumb_container.css('overflow', 'hidden');
			
			// Add class and style to thumbnail restriction
			thumb_restriction.addClass('showcase-thumbnail-restriction');
			thumb_restriction.css({'overflow' : 'hidden', 'position' : 'relative'});
			if (options.thumbnails_direction == 'horizontal') { thumb_restriction.css({'float' : 'left'}); }
			
			// Add class and style to thumbnail wrapper 
			thumb_wrapper.addClass('showcase-thumbnail-wrapper');
			if (options.thumbnails_direction == 'horizontal') { thumb_wrapper.addClass('showcase-thumbnail-wrapper-horizontal'); }
			else { thumb_wrapper.addClass('showcase-thumbnail-wrapper-vertical'); }
			thumb_wrapper.css('position', 'relative');
			
			// Append wrapper and restriction
			thumb_restriction.append(thumb_wrapper);
			thumb_container.append(thumb_restriction);
			
			// Add backward button
			var buttonBackward = jQuery('<div class="showcase-thumbnail-button-backward" />');
			if (options.thumbnails_direction != 'horizontal')
			{
				buttonBackward.html('<span class="showcase-thumbnail-vertical"><span>Up</span></span>');
			}
			else
			{
				buttonBackward.css({'float' : 'left'});
				buttonBackward.html('<span class="showcase-thumbnail-horizontal"><span>Left</span></span>');
			}
			buttonBackward.click(function() { slideThumbnailWrapper('backward', false, true); });
			thumb_container.prepend(buttonBackward);
			
			// Add forward button
			var buttonForward = jQuery('<div class="showcase-thumbnail-button-forward" />');
			if (options.thumbnails_direction != 'horizontal')
			{
				buttonForward.html('<span class="showcase-thumbnail-vertical"><span>Down</span></span>');
			}
			else
			{
				buttonForward.css({'float' : 'left'});
				buttonForward.html('<span class="showcase-thumbnail-horizontal"><span>Right</span></span>');
			}
			buttonForward.click(function() { slideThumbnailWrapper('forward', false, true); });
			thumb_container.append(buttonForward);
			
			// Set the number of thumbnails per page.
			var thumbnailVisibleStretch = 0;
			if (options.thumbnails_direction != 'horizontal')
			{
				thumbnailVisibleStretch = getElementHeight(thumb_wrapper, false);
				thumbnailVisibleStretch += (getElementHeight(buttonBackward)) + (getElementHeight(buttonForward));
				while (thumbnailVisibleStretch < options.height)
				{
					thumbnailVisibleStretch += getElementHeight(jQuery(thumbnailArray[0]));
					thumbnailsPerPage++;
				}
			}
			else
			{
				thumbnailVisibleStretch = getElementWidth(thumb_wrapper, false);
				thumbnailVisibleStretch += (getElementWidth(buttonBackward)) + (getElementWidth(buttonForward));
				
				while (thumbnailVisibleStretch < options.width)
				{
					thumbnailVisibleStretch += getElementWidth(jQuery(thumbnailArray[0]));
					thumbnailsPerPage++;
				}
			}
			
			// Hide buttons if they're not necessary
			if (thumbnailsPerPage+1 > thumbnailArray.length)
			{
				if (options.thumbnails_direction != 'horizontal')
				{
					thumb_restriction.css('margin-top', getElementHeight(buttonBackward));
				}
				else
				{
					thumb_restriction.css('margin-left', getElementWidth(buttonBackward));
				}
				buttonBackward.hide();
				buttonForward.hide();
			}
			
			// Set thumbnail restriction height or width
			if (options.thumbnails_direction != 'horizontal')
			{
				var buttonsHeight = (getElementHeight(buttonBackward)) + (getElementHeight(buttonForward));
				thumb_restriction.css('height', options.height - buttonsHeight);
			}
			else
			{
				var buttonsWidth = (getElementWidth(buttonBackward)) + (getElementWidth(buttonForward));
				thumb_restriction.css('width', options.width-buttonsWidth);
			}
			
			// Set thumbnail wrapper width
			if (options.thumbnails_direction == 'horizontal')
			{
				jQuery('.showcase-thumbnail').each(function() { thumbnailStretch += getElementWidth(jQuery(this)); });
				thumb_wrapper.css('width', thumbnailStretch);
			}
			else { jQuery('.showcase-thumbnail').each(function() { thumbnailStretch += getElementHeight(jQuery(this)); }); }
		}
		
		// Set showcase width and height
		if (options.thumbnails && options.thumbnails_position.indexOf("outside") != -1 && options.thumbnails_direction != 'horizontal')
		{
			showcase.css('width', options.width + getElementWidth(thumb_wrapper, true, false));
		}
		else { showcase.css('width', options.width); }
		
		// Get the first content in the array and display it
		var first_content = getContent(0);
		content_wrapper.append(first_content);
		displayAnchors(first_content);
		displayCaption(first_content);
		if (options.show_caption == 'show')
		{
			jQuery(first_content).find('.showcase-caption').show(); // If caption is set to 'show'
		}
		
		// Turn on/off auto slide
		if (content_count > 1 && options.auto) { myInterval = window.setInterval(autoChange, options.interval); }
		
		// Pause auto on mouse over
		if (options.auto && options.pauseonover)
		{
			showcase.mouseenter(function() { break_loop = true; clearInterval(myInterval); });
			showcase.mouseleave(function()
			{
				if (!pause_loop)
				{
					break_loop = false; myInterval = window.setInterval(autoChange, options.interval);
				}
			});
		}
		
		// Adding navigation arrows
		if (options.arrows && content_count > 1)
		{
			// Left arrow
			jQuery(document.createElement('div'))
				.addClass('showcase-arrow-previous')
				.prependTo(showcase)
				.click(function() {
					// Disable auto change on click
					if (myInterval) { pause_loop = true; clearInterval(myInterval); }
					changeContent(content_count-1, 'previous');
				});
			// Right arrow
			jQuery(document.createElement('div'))
				.addClass('showcase-arrow-next')
				.prependTo(showcase)
				.click(function() {
					// Disable auto change on click
					if (myInterval) { pause_loop = true; clearInterval(myInterval); }
					changeContent(1, 'next');
				});
		}
		
		// Adding navigation buttons
		if (options.buttons && content_count > 1)
		{
			// Create button wrapper
			jQuery(document.createElement('div'))
				.css('clear', 'both')
				.addClass('showcase-button-wrapper')
				.appendTo(showcase);
			var i = 0;
			// Add button for each content
			while (i < content_count)
			{
				jQuery(document.createElement('div'))
					.attr('id', 'showcase-navigation-button-' + i)
					.addClass((i === 0) ? 'blipon active' : 'blipoff')
					// Add numbers or unicode
					.html((options.btn_numbers) ? parseInt(i)+1 : '&nbsp;')
					.click(function(a, b)
					{
						// This function is used to extract the correct i value on click
						return function()
						{
							// Disable auto change on click
							
							if (myInterval) { pause_loop = true; clearInterval(myInterval); }
							changeContent(a, b);
						};
					}(i, ''))
					.appendTo(jQuery(showcase).find('.showcase-button-wrapper'));
				i++;
			}
		}
		
		// Remove loading class
		showcase.removeClass('showcase-load');
	};

})(jQuery);

/*************************************************
**  jQuery Masonry version 1.3.2
**  Copyright David DeSandro, licensed MIT
**  http://desandro.com/resources/jquery-masonry
**************************************************/
(function(e){var n=e.event,o;n.special.smartresize={setup:function(){e(this).bind("resize",n.special.smartresize.handler)},teardown:function(){e(this).unbind("resize",n.special.smartresize.handler)},handler:function(j,l){var g=this,d=arguments;j.type="smartresize";o&&clearTimeout(o);o=setTimeout(function(){jQuery.event.handle.apply(g,d)},l==="execAsap"?0:100)}};e.fn.smartresize=function(j){return j?this.bind("smartresize",j):this.trigger("smartresize",["execAsap"])};e.fn.masonry=function(j,l){var g=
{getBricks:function(d,b,a){var c=a.itemSelector===undefined;b.$bricks=a.appendedContent===undefined?c?d.children():d.find(a.itemSelector):c?a.appendedContent:a.appendedContent.filter(a.itemSelector)},placeBrick:function(d,b,a,c,h){b=Math.min.apply(Math,a);for(var i=b+d.outerHeight(true),f=a.length,k=f,m=c.colCount+1-f;f--;)if(a[f]==b)k=f;d.applyStyle({left:c.colW*k+c.posLeft,top:b},e.extend(true,{},h.animationOptions));for(f=0;f<m;f++)c.colY[k+f]=i},setup:function(d,b,a){g.getBricks(d,a,b);if(a.masoned)a.previousData=
d.data("masonry");a.colW=b.columnWidth===undefined?a.masoned?a.previousData.colW:a.$bricks.outerWidth(true):b.columnWidth;a.colCount=Math.floor(d.width()/a.colW);a.colCount=Math.max(a.colCount,1)},arrange:function(d,b,a){var c;if(!a.masoned||b.appendedContent!==undefined)a.$bricks.css("position","absolute");if(a.masoned){a.posTop=a.previousData.posTop;a.posLeft=a.previousData.posLeft}else{d.css("position","relative");var h=e(document.createElement("div"));d.prepend(h);a.posTop=Math.round(h.position().top);
a.posLeft=Math.round(h.position().left);h.remove()}if(a.masoned&&b.appendedContent!==undefined){a.colY=a.previousData.colY;for(c=a.previousData.colCount;c<a.colCount;c++)a.colY[c]=a.posTop}else{a.colY=[];for(c=a.colCount;c--;)a.colY.push(a.posTop)}e.fn.applyStyle=a.masoned&&b.animate?e.fn.animate:e.fn.css;b.singleMode?a.$bricks.each(function(){var i=e(this);g.placeBrick(i,a.colCount,a.colY,a,b)}):a.$bricks.each(function(){var i=e(this),f=Math.ceil(i.outerWidth(true)/a.colW);f=Math.min(f,a.colCount);
if(f===1)g.placeBrick(i,a.colCount,a.colY,a,b);else{var k=a.colCount+1-f,m=[];for(c=0;c<k;c++){var p=a.colY.slice(c,c+f);m[c]=Math.max.apply(Math,p)}g.placeBrick(i,k,m,a,b)}});a.wallH=Math.max.apply(Math,a.colY);d.applyStyle({height:a.wallH-a.posTop},e.extend(true,[],b.animationOptions));a.masoned||setTimeout(function(){d.addClass("masoned")},1);l.call(a.$bricks);d.data("masonry",a)},resize:function(d,b,a){a.masoned=!!d.data("masonry");var c=d.data("masonry").colCount;g.setup(d,b,a);a.colCount!=c&&
g.arrange(d,b,a)}};return this.each(function(){var d=e(this),b={};b.masoned=!!d.data("masonry");var a=b.masoned?d.data("masonry").options:{},c=e.extend({},e.fn.masonry.defaults,a,j),h=a.resizeable;b.options=c.saveOptions?c:a;l=l||function(){};g.getBricks(d,b,c);if(!b.$bricks.length)return this;g.setup(d,c,b);g.arrange(d,c,b);!h&&c.resizeable&&e(window).bind("smartresize.masonry",function(){g.resize(d,c,b)});h&&!c.resizeable&&e(window).unbind("smartresize.masonry")})};e.fn.masonry.defaults={singleMode:false,
columnWidth:undefined,itemSelector:undefined,appendedContent:undefined,saveOptions:true,resizeable:true,animate:false,animationOptions:{}}})(jQuery);

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 0,
		animation	: {opacity:'show',height:'show'},
		speed		: 'fast',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

/*
 * Supersubs v0.2b - jQuery plugin
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 *
 * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of
 * their longest list item children. If you use this, please expect bugs and report them
 * to the jQuery Google Group with the word 'Superfish' in the subject line.
 *
 */

;(function($){ // $ will refer to jQuery within this closure

	$.fn.supersubs = function(options){
		var opts = $.extend({}, $.fn.supersubs.defaults, options);
		// return original object to support chaining
		return this.each(function() {
			// cache selections
			var $$ = $(this);
			// support metadata
			var o = $.meta ? $.extend({}, opts, $$.data()) : opts;
			// get the font size of menu.
			// .css('fontSize') returns various results cross-browser, so measure an em dash instead
			var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({
				'padding' : 0,
				'position' : 'absolute',
				'top' : '-999em',
				'width' : 'auto'
			}).appendTo($$).width(); //clientWidth is faster, but was incorrect here
			// remove em dash
			$('#menu-fontsize').remove();
			// cache all ul elements
			$ULs = $$.find('ul');
			// loop through each ul in menu
			$ULs.each(function(i) {	
				// cache this ul
				var $ul = $ULs.eq(i);
				// get all (li) children of this ul
				var $LIs = $ul.children();
				// get all anchor grand-children
				var $As = $LIs.children('a');
				// force content to one line and save current float property
				var liFloat = $LIs.css('white-space','nowrap').css('float');
				// remove width restrictions and floats so elements remain vertically stacked
				var emWidth = $ul.add($LIs).add($As).css({
					'float' : 'none',
					'width'	: 'auto'
				})
				// this ul will now be shrink-wrapped to longest li due to position:absolute
				// so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer
				.end().end()[0].clientWidth / fontsize;
				// add more width to ensure lines don't turn over at certain sizes in various browsers
				emWidth += o.extraWidth;
				// restrict to at least minWidth and at most maxWidth
				if (emWidth > o.maxWidth)		{ emWidth = o.maxWidth; }
				else if (emWidth < o.minWidth)	{ emWidth = o.minWidth; }
				emWidth += 'em';
				// set ul to width in ems
				$ul.css('width',emWidth);
				// restore li floats to avoid IE bugs
				// set li width to full width of this ul
				// revert white-space to normal
				$LIs.css({
					'float' : liFloat,
					'width' : '100%',
					'white-space' : 'normal'
				})
				// update offset position of descendant ul to reflect new width of parent
				.each(function(){
					var $childUl = $('>ul',this);
					var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right';
					$childUl.css(offsetDirection,emWidth);
				});
			});
			
		});
	};
	// expose defaults
	$.fn.supersubs.defaults = {
		minWidth		: 9,		// requires em unit.
		maxWidth		: 25,		// requires em unit.
		extraWidth		: 0			// extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values
	};
	
})(jQuery); // plugin code ends


(function($){
	/* hoverIntent by Brian Cherne */
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
	
})(jQuery);

// ColorBox v1.3.15 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
// Copyright (c) 2010 Jack Moore - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function(b,ib){var t="none",M="LoadedContent",c=false,v="resize.",o="y",q="auto",e=true,L="nofollow",m="x";function f(a,c){a=a?' id="'+i+a+'"':"";c=c?' style="'+c+'"':"";return b("<div"+a+c+"/>")}function p(a,b){b=b===m?n.width():n.height();return typeof a==="string"?Math.round(/%/.test(a)?b/100*parseInt(a,10):parseInt(a,10)):a}function U(b){return a.photo||/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(b)}function cb(a){for(var c in a)if(b.isFunction(a[c])&&c.substring(0,2)!=="on")a[c]=a[c].call(l);a.rel=a.rel||l.rel||L;a.href=a.href||b(l).attr("href");a.title=a.title||l.title;return a}function w(c,a){a&&a.call(l);b.event.trigger(c)}function jb(){var b,e=i+"Slideshow_",c="click."+i,f,k;if(a.slideshow&&h[1]){f=function(){F.text(a.slideshowStop).unbind(c).bind(V,function(){if(g<h.length-1||a.loop)b=setTimeout(d.next,a.slideshowSpeed)}).bind(W,function(){clearTimeout(b)}).one(c+" "+N,k);j.removeClass(e+"off").addClass(e+"on");b=setTimeout(d.next,a.slideshowSpeed)};k=function(){clearTimeout(b);F.text(a.slideshowStart).unbind([V,W,N,c].join(" ")).one(c,f);j.removeClass(e+"on").addClass(e+"off")};a.slideshowAuto?f():k()}}function db(c){if(!O){l=c;a=cb(b.extend({},b.data(l,r)));h=b(l);g=0;if(a.rel!==L){h=b("."+G).filter(function(){return (b.data(this,r).rel||this.rel)===a.rel});g=h.index(l);if(g===-1){h=h.add(l);g=h.length-1}}if(!u){u=D=e;j.show();if(a.returnFocus)try{l.blur();b(l).one(eb,function(){try{this.focus()}catch(a){}})}catch(f){}x.css({opacity:+a.opacity,cursor:a.overlayClose?"pointer":q}).show();a.w=p(a.initialWidth,m);a.h=p(a.initialHeight,o);d.position(0);X&&n.bind(v+P+" scroll."+P,function(){x.css({width:n.width(),height:n.height(),top:n.scrollTop(),left:n.scrollLeft()})}).trigger("scroll."+P);w(fb,a.onOpen);Y.add(H).add(I).add(F).add(Z).hide();ab.html(a.close).show()}d.load(e)}}var gb={transition:"elastic",speed:300,width:c,initialWidth:"600",innerWidth:c,maxWidth:c,height:c,initialHeight:"450",innerHeight:c,maxHeight:c,scalePhotos:e,scrolling:e,inline:c,html:c,iframe:c,photo:c,href:c,title:c,rel:c,opacity:.9,preloading:e,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:c,returnFocus:e,loop:e,slideshow:c,slideshowAuto:e,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:c,onLoad:c,onComplete:c,onCleanup:c,onClosed:c,overlayClose:e,escKey:e,arrowKey:e},r="colorbox",i="cbox",fb=i+"_open",W=i+"_load",V=i+"_complete",N=i+"_cleanup",eb=i+"_closed",Q=i+"_purge",hb=i+"_loaded",E=b.browser.msie&&!b.support.opacity,X=E&&b.browser.version<7,P=i+"_IE6",x,j,A,s,bb,T,R,S,h,n,k,J,K,Z,Y,F,I,H,ab,B,C,y,z,l,g,a,u,D,O=c,d,G=i+"Element";d=b.fn[r]=b[r]=function(c,f){var a=this,d;if(!a[0]&&a.selector)return a;c=c||{};if(f)c.onComplete=f;if(!a[0]||a.selector===undefined){a=b("<a/>");c.open=e}a.each(function(){b.data(this,r,b.extend({},b.data(this,r)||gb,c));b(this).addClass(G)});d=c.open;if(b.isFunction(d))d=d.call(a);d&&db(a[0]);return a};d.init=function(){var l="hover",m="clear:left";n=b(ib);j=f().attr({id:r,"class":E?i+"IE":""});x=f("Overlay",X?"position:absolute":"").hide();A=f("Wrapper");s=f("Content").append(k=f(M,"width:0; height:0; overflow:hidden"),K=f("LoadingOverlay").add(f("LoadingGraphic")),Z=f("Title"),Y=f("Current"),I=f("Next"),H=f("Previous"),F=f("Slideshow").bind(fb,jb),ab=f("Close"));A.append(f().append(f("TopLeft"),bb=f("TopCenter"),f("TopRight")),f(c,m).append(T=f("MiddleLeft"),s,R=f("MiddleRight")),f(c,m).append(f("BottomLeft"),S=f("BottomCenter"),f("BottomRight"))).children().children().css({"float":"left"});J=f(c,"position:absolute; width:9999px; visibility:hidden; display:none");b("body").prepend(x,j.append(A,J));s.children().hover(function(){b(this).addClass(l)},function(){b(this).removeClass(l)}).addClass(l);B=bb.height()+S.height()+s.outerHeight(e)-s.height();C=T.width()+R.width()+s.outerWidth(e)-s.width();y=k.outerHeight(e);z=k.outerWidth(e);j.css({"padding-bottom":B,"padding-right":C}).hide();I.click(d.next);H.click(d.prev);ab.click(d.close);s.children().removeClass(l);b("."+G).live("click",function(a){if(!(a.button!==0&&typeof a.button!=="undefined"||a.ctrlKey||a.shiftKey||a.altKey)){a.preventDefault();db(this)}});x.click(function(){a.overlayClose&&d.close()});b(document).bind("keydown",function(b){if(u&&a.escKey&&b.keyCode===27){b.preventDefault();d.close()}if(u&&a.arrowKey&&!D&&h[1])if(b.keyCode===37&&(g||a.loop)){b.preventDefault();H.click()}else if(b.keyCode===39&&(g<h.length-1||a.loop)){b.preventDefault();I.click()}})};d.remove=function(){j.add(x).remove();b("."+G).die("click").removeData(r).removeClass(G)};d.position=function(f,d){function b(a){bb[0].style.width=S[0].style.width=s[0].style.width=a.style.width;K[0].style.height=K[1].style.height=s[0].style.height=T[0].style.height=R[0].style.height=a.style.height}var e,h=Math.max(document.documentElement.clientHeight-a.h-y-B,0)/2+n.scrollTop(),g=Math.max(n.width()-a.w-z-C,0)/2+n.scrollLeft();e=j.width()===a.w+z&&j.height()===a.h+y?0:f;A[0].style.width=A[0].style.height="9999px";j.dequeue().animate({width:a.w+z,height:a.h+y,top:h,left:g},{duration:e,complete:function(){b(this);D=c;A[0].style.width=a.w+z+C+"px";A[0].style.height=a.h+y+B+"px";d&&d()},step:function(){b(this)}})};d.resize=function(b){if(u){b=b||{};if(b.width)a.w=p(b.width,m)-z-C;if(b.innerWidth)a.w=p(b.innerWidth,m);k.css({width:a.w});if(b.height)a.h=p(b.height,o)-y-B;if(b.innerHeight)a.h=p(b.innerHeight,o);if(!b.innerHeight&&!b.height){b=k.wrapInner("<div style='overflow:auto'></div>").children();a.h=b.height();b.replaceWith(b.children())}k.css({height:a.h});d.position(a.transition===t?0:a.speed)}};d.prep=function(m){var c="hidden";function l(s){var p,f,m,c,l=h.length,q=a.loop;d.position(s,function(){function s(){E&&j[0].style.removeAttribute("filter")}if(u){E&&o&&k.fadeIn(100);k.show();w(hb);Z.show().html(a.title);if(l>1){typeof a.current==="string"&&Y.html(a.current.replace(/\{current\}/,g+1).replace(/\{total\}/,l)).show();I[q||g<l-1?"show":"hide"]().html(a.next);H[q||g?"show":"hide"]().html(a.previous);p=g?h[g-1]:h[l-1];m=g<l-1?h[g+1]:h[0];a.slideshow&&F.show();if(a.preloading){c=b.data(m,r).href||m.href;f=b.data(p,r).href||p.href;c=b.isFunction(c)?c.call(m):c;f=b.isFunction(f)?f.call(p):f;if(U(c))b("<img/>")[0].src=c;if(U(f))b("<img/>")[0].src=f}}K.hide();a.transition==="fade"?j.fadeTo(e,1,function(){s()}):s();n.bind(v+i,function(){d.position(0)});w(V,a.onComplete)}})}if(u){var o,e=a.transition===t?0:a.speed;n.unbind(v+i);k.remove();k=f(M).html(m);k.hide().appendTo(J.show()).css({width:function(){a.w=a.w||k.width();a.w=a.mw&&a.mw<a.w?a.mw:a.w;return a.w}(),overflow:a.scrolling?q:c}).css({height:function(){a.h=a.h||k.height();a.h=a.mh&&a.mh<a.h?a.mh:a.h;return a.h}()}).prependTo(s);J.hide();b("#"+i+"Photo").css({cssFloat:t,marginLeft:q,marginRight:q});X&&b("select").not(j.find("select")).filter(function(){return this.style.visibility!==c}).css({visibility:c}).one(N,function(){this.style.visibility="inherit"});a.transition==="fade"?j.fadeTo(e,0,function(){l(0)}):l(e)}};d.load=function(u){var n,c,s,q=d.prep;D=e;l=h[g];u||(a=cb(b.extend({},b.data(l,r))));w(Q);w(W,a.onLoad);a.h=a.height?p(a.height,o)-y-B:a.innerHeight&&p(a.innerHeight,o);a.w=a.width?p(a.width,m)-z-C:a.innerWidth&&p(a.innerWidth,m);a.mw=a.w;a.mh=a.h;if(a.maxWidth){a.mw=p(a.maxWidth,m)-z-C;a.mw=a.w&&a.w<a.mw?a.w:a.mw}if(a.maxHeight){a.mh=p(a.maxHeight,o)-y-B;a.mh=a.h&&a.h<a.mh?a.h:a.mh}n=a.href;K.show();if(a.inline){f().hide().insertBefore(b(n)[0]).one(Q,function(){b(this).replaceWith(k.children())});q(b(n))}else if(a.iframe){j.one(hb,function(){var c=b("<iframe frameborder='0' style='width:100%; height:100%; border:0; display:block'/>")[0];c.name=i+ +new Date;c.src=a.href;if(!a.scrolling)c.scrolling="no";if(E)c.allowtransparency="true";b(c).appendTo(k).one(Q,function(){c.src="//about:blank"})});q(" ")}else if(a.html)q(a.html);else if(U(n)){c=new Image;c.onload=function(){var e;c.onload=null;c.id=i+"Photo";b(c).css({border:t,display:"block",cssFloat:"left"});if(a.scalePhotos){s=function(){c.height-=c.height*e;c.width-=c.width*e};if(a.mw&&c.width>a.mw){e=(c.width-a.mw)/c.width;s()}if(a.mh&&c.height>a.mh){e=(c.height-a.mh)/c.height;s()}}if(a.h)c.style.marginTop=Math.max(a.h-c.height,0)/2+"px";h[1]&&(g<h.length-1||a.loop)&&b(c).css({cursor:"pointer"}).click(d.next);if(E)c.style.msInterpolationMode="bicubic";setTimeout(function(){q(c)},1)};setTimeout(function(){c.src=n},1)}else n&&J.load(n,function(d,c,a){q(c==="error"?"Request unsuccessful: "+a.statusText:b(this).children())})};d.next=function(){if(!D){g=g<h.length-1?g+1:0;d.load()}};d.prev=function(){if(!D){g=g?g-1:h.length-1;d.load()}};d.close=function(){if(u&&!O){O=e;u=c;w(N,a.onCleanup);n.unbind("."+i+" ."+P);x.fadeTo("fast",0);j.stop().fadeTo("fast",0,function(){w(Q);k.remove();j.add(x).css({opacity:1,cursor:q}).hide();setTimeout(function(){O=c;w(eb,a.onClosed)},1)})}};d.element=function(){return b(l)};d.settings=gb;b(d.init)})(jQuery,this);
