(function($) {
var _cache = [];
var _count=0;
var debug=false;
$.fn.slideshow = function(options) {	
var defaults = { showFirst: true, valign: 0.5, halign: 0.5, transition: null, beforeLoad: null };
options = $.extend(defaults, options);
var selector = this.selector;
return this.each(function() {
var $this = $(this);
var slideshowId = ++_count;
var placeholders = $this.children('a'),
imgs=[],
busy = false,
currentIdx = -1,
nextIdx = -1, 
currentImg = 0;
var eventScope = 'slideshow_'+slideshowId;	
this.slideshowId = slideshowId;
placeholders.each(function(i) {
var img,src,
placeholder=$(this);			
if (this.tagName != 'A') {
var newPlaceholder = $('<a rel="image" href="'+this.src+'"></a>');
placeholder.replaceWith(newPlaceholder);
placeholders[i] = placeholder = newPlaceholder; };
switch(placeholder.attr('rel')) {
default:
case 'image':
var img = document.createElement('img');
img.original = this.href;
$(img).css({display: 'none'});
placeholder.data('media', img);
img.id = placeholder.attr('id');
placeholder.after(img).attr('id', null);
img.className = placeholder.attr('className');
img.title = placeholder.attr('title');
imgs[i] = img; break; } });
$this.bind('nextImage.slideshow', next);
$this.bind('prevImage.slideshow', prev);
$this.bind('setImage.slideshow', function(ev, idx) {
showImage(idx); });
$this.bind('reload.slideshow', function(ev) { nextIdx = -1;
showImage(currentIdx); });
if (options.showFirst) { showImage(0); }
$this.addClass('slideshow');
function showImage(idx) { if (!imgs.length) { return; }
if (busy) {	} if (idx !== false) { if (idx >= imgs.length) {idx = 0;}
if (idx < 0) idx = imgs.length -1;
if (nextIdx === idx) return; nextIdx = idx;
var img = imgs[idx], $img = $(img), src = img.original, size = {width: $this.width(), height: $this.height()};	
if (options.beforeLoad) src = options.beforeLoad(src);function onLoaded() { _cache[img.src]=true;
$img.css({ top: size.height / 2 - $img.height() / 2 + 'px', left: size.width / 2 - $img.width() / 2 + 'px' });
if (options.transition) { busy = true; options.transition.apply($this, [currentImg, img, function(ignore) {
if (!ignore) { busy = false; currentIdx = idx; currentImg = img; } }]); } else {
if (currentImg) currentImg.hide(); $img.show(); currentIdx = idx; currentImg = $img; } }
if (_cache[src] && img.src == src) { onLoaded(); } else { img.onload = onLoaded; img.src = src; }} else { nextIdx = idx;
if (options.transition) { busy=true; options.transition.apply($this, [currentImg, null, function(ignore) {
if (!ignore) { busy = false; currentIdx = -1; currentImg = null; } }]); } else {
if (currentImg) currentImg.hide(); currentIdx = -1; currentImg = null; } } }
function next(ev) { showImage(currentIdx+1); } function prev(ev) { showImage(currentIdx-1); } }); }; })(jQuery);
