 /** http://docs.jquery.com/Cookbook/wait **/
 $.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

		
		/**
 * Phototour Plugin
 * Copyright (c) 2010 Lu Chen
 * Dependencies: 
 *   jQuery History (http://www.mikage.to/jquery/jquery_history.html) -- below
 *   Scrollable (http://flowplayer.org/tools/) with mousewheel and navigator
 *   Minimalistic Drag'n'Resize
 *
 * This code is dual licensed under MIT and GPL
 * http://www.opensource.org/licenses
 * Provided as-is. Good luck :)
 */
 
 (function($){

$.fn.phototour = function($options) {
	
	/**
	 * Options:
	 * container -- Selector for the container that holds the large image. Must exist.
	 * counter -- Selector for container to place counter string in.
	 * cntString -- String with CUR and TOTAL to be placed within $(counter) object.
	 * wraparound -- whether to wrap around the items or not.
	 * size -- number of items to show in the thumbnails.
	 * history -- whether history is enabled or not.
	 * clickNext -- whether to allow large image to be clickable to next.
	 * scroller -- selector for the container to pass to Scrollable
	 * vertical -- if scrollable is vertical or not
	 * keyboard -- whether to enable keyboard shortcuts or not
	 * hop -- whether next/prev links use "smart hopping" or not
	 * showCount -- show numeric counts in thumbnails
	 * caption -- id of caption element. If exists, will use, else will create.
	 * draggable -- whether caption div is draggable or not
	 * inactiveOpacity -- opacity of inactive thumbnails
	 * hoverOpacity -- opacity of thumbnails hovered over 
	 */
	 
	var $defaults = {
		container   : '.photo',
		counter     : '.counter',
		cntString   : 'CUR / TOTAL',
		wraparound  : true,
		size        : 5,
		history     : true,
		clickNext   : true,
		scroller    : '.thumbnails',
		vertical    : true,
		keyboard    : true,
		hop         : true,
		showCount   : false,
		caption     : 'display-caption',
		draggable   : true,
		inactiveOpacity    : 0.3,
		hoverOpacity       : 0.5
	};
	

	var $opts = $.extend($defaults, $options);
	
	$.phototour.opts = [];
	for (var i in $opts) {
		if (i) {
			$.phototour.opts[i]  = $opts[i];
		}
	}
	
	// Private variables.
	$.phototour.currentIndex = -1;
	$.phototour.parent = $(this);
	$.phototour.itemCount = $(this).children().length;
	
	var _photoWrapper = $(document.createElement("div")).addClass("phototour-wrapper");
	
	// If it doesn't exist, create the caption container and add after photo wrapper.
	var _exists = $('#' + $opts.caption).is('#' + $opts.caption);	
	$($opts.container).append(_photoWrapper);
	if (!_exists) {
		$($opts.container).append(
			$(document.createElement("span")).attr("id", $opts.caption).addClass("current-caption")
		);
	}
	
	if ($opts.draggable) {
		$('#'+$opts.caption).jqDrag();
	}

	// Create the scrollable.
	$.phototour.scrollable = $($opts.scroller).scrollable({
		activeClass: "no-clash-active",
		vertical: $opts.vertical,
		clickable: false,
		keyboard: $opts.keyboard,
		size: $opts.size,
		next: "no-clash-next",
		prev: "no-clash-prev",
		nextPage: "no-clash-nextpage",
		prevPage: "no-clash-prevpage"
	}).mousewheel().navigator({api: true});
	
	// Bind history object.
	$.historyInit($.phototour.load);
	
	// Bind keyboard, if necessary.
	if ($opts.keyboard) {
		var nextKey = ($opts.vertical) ? 39 : 40;
		var prevKey = ($opts.vertical) ? 37 : 38;
		$(document).keyup(function(event){
			if (event.keyCode == nextKey) { 
				$.phototour.keyNext();
			} else if (event.keyCode == prevKey) { 
				$.phototour.keyPrev();
			} 
		});
	}
	
	$.phototour.captions = true;
	
	// Bind the text links
	$(".prev").click(function() {	$.phototour.prev(); return false; });
	$(".next").click(function() {	$.phototour.next(); return false; });
	$(".prevPage").click(function() {	$.phototour.scrollable.prevPage(); return false; });
	$(".nextPage").click(function() {	$.phototour.scrollable.nextPage(); return false; });
	$(".caption-on").click(function() {
		$(this).addClass("captionSelect");
		$(".caption-off").removeClass("captionSelect");
		$.phototour.captions = true;
		$('#' + $.phototour.opts.caption).fadeIn();
		return false;
	});
	$(".caption-off").click(function() {
		$(this).addClass("captionSelect");
		$(".caption-on").removeClass("captionSelect");
		$.phototour.captions = false;
		$('#' + $.phototour.opts.caption).fadeOut();
		return false;
	});

	var ret = this.eq(0).each(function(){		
		// loop through list
		$(this).children('li').each(function(i) {
		
			var _container = $(this); // the LI
			
			_container.data("index", i);
			
			// Add number ordinals
			if ($opts.showCount) {
				_container.append("<p class=\"indice\">" + (i+1) + "</p>");
			}
			
			// Fade the image within.
			if ( _container.is('.active')) {
				$.phototour.currentIndex = i;
			}
			
			var _src = _container.find("a").attr("href");
			
			if ($opts.history && (window.location.hash && window.location.hash.replace(/\#/,'') == _src)) {
				_container.siblings('.active').removeClass('active');
				_container.addClass('active');
				$.phototour.currentIndex = i;
			}
		}); // close each LI
		
		// Set starting opacities
		$(this).children("li").not('.active').find("img").fadeTo(500, $opts.inactiveOpacity);
		
		// globally add click and hover handlers
		$(this).children("li").find("a").click(function() {
			$.phototour.seek($(this).parent().data("index"));
			return false;
		});
	
		// add hovers
		$(this).children("li").find("a").hover(function() {
			$(this).parent().not(".active").find("img").fadeTo('fast', $opts.hoverOpacity);
			}, function() {
			$(this).parent().not(".active").find("img").fadeTo('fast', $opts.inactiveOpacity);
		});
		
	}); // close each selected
	
	
	$.phototour.seek($.phototour.currentIndex);
	return ret;
};

$.extend({phototour : {
	jump : function(dir) {
		var min = Math.max($.phototour.scrollable.getIndex(), 0);
		var max = Math.min(min+$.phototour.opts.size-1, $.phototour.itemCount);
		var target = $.phototour.currentIndex+dir;
		if (target >= (min-1) && target <= (max+1)) {
			(dir > 0) ? $.phototour.next() : $.phototour.prev(); return;
		}
		(dir > 0) ? $.phototour.seek(min) : $.phototour.seek(max);
	},
	
	keyNext : function() {
		($.phototour.opts.hop) ?	$.phototour.jump(1) : $.phototour.next();
	},
	
	keyPrev : function() {
		($.phototour.opts.hop) ?	$.phototour.jump(-1) : $.phototour.prev();
	},
	
	next : function() {
		$.phototour.seek($.phototour.currentIndex+1);
	},
	
	prev : function() {
		$.phototour.seek($.phototour.currentIndex-1);
	},
	
	load : function(_src) {
		var index = '';
		var items = $($.phototour.parent).children("li");
		for (var i = 0; i < items.length; i++) {
			if (_src == $(items[i]).find("a").attr("href")) {
				index = i;
				break;
			}
		}
		
		if (index === '') {
			return;
		}

		var _container = $($.phototour.parent);
		var _caption = $('#'+$.phototour.opts.caption);
		
		var _li = _container.children().eq(index);
		
		// Load caption.
		var cont = _li.find("div");
		
		// Load image.
		var _src = _li.find("a").attr("href");
		
		if ($.phototour.opts.history) {
			window.location = window.location.href.replace(/\#.*/,'') + '#' + _src;
		}
				
		$(".phototour-wrapper").children().fadeTo("slow", 0.5);
		_caption.fadeTo("slow", 0.5);
		
		$(".phototour-wrapper").addClass("loading");
		var _img = new Image();
		$(_img).load(function(ev) {
			$(".phototour-wrapper").removeClass("loading").empty().append($(_img));
			$(_img).addClass( $(_img).width() > $(_img).height() ? "horizontal" : "vertical");
			if (cont.is("div")) {
			_caption.html(cont.html());
			
			if ($.phototour.captions) {
			_caption.fadeTo("normal", 1).show();
			} else {
				_caption.hide();
			}
		}	else {
			// If no contents, always hide.
			_caption.hide();
		}
			if ($.phototour.opts.clickNext) {
				$(_img).css("cursor", "pointer").click(function() {
					$.phototour.next();
				});
			}
		}).attr("src", _src).addClass("replaced");
		
		// Toggle classes on thumbnail.
		if (!_li.is('.active')) {
		_container.find(".active").removeClass('active').find("img").fadeTo(500, $.phototour.opts.inactiveOpacity);
		_li.addClass('active').find("img").fadeTo(0, 1);
		}
		
		// Scroll to it.
		if ($.phototour.scrollable) {
			var ind = index-Math.floor($.phototour.opts.size/2);
			$.phototour.scrollable.seekTo(ind);
		}
		
		// Write counter.		
		var replaceString = $.phototour.opts.cntString;
		replaceString = replaceString.replace("CUR", (index+1)+"");
		replaceString = replaceString.replace("TOTAL", $.phototour.itemCount+"");
		$($.phototour.opts.counter).html(replaceString);
		
		$.phototour.currentIndex = index;
	},
	seek : function(index) {
		if ($.phototour.opts.wraparound) {
			index = (index < 0) ? index+$.phototour.itemCount : index%$.phototour.itemCount;
		}
		if (index < 0 || index >= $.phototour.itemCount) { return; }
		var _src = $($.phototour.parent).children("li").eq(index).find("a").attr("href");
		if ($.phototour.opts.history) {
			$.historyLoad(_src);
		} else {
			$.phototour.load(_src);
		}
	}
}
});

})(jQuery);
