$.fn.slideshow = function(options) {
	// easily accessible name for this
  var plugin = this;

	// default options
  plugin.options = {
    clipMode: false,
    fxSpeed: "slow",
    height: 500,
    width: 500,
    background: 'black',
    buttons: {
      back: '/sites/default/themes/digett/gallery/images/back.png',
      next: '/sites/default/themes/digett/gallery/images/next.png',
      play: '/sites/default/themes/digett/gallery/images/play.png',
      pause: '/sites/default/themes/digett/gallery/images/pause.png',
      slow: '/sites/default/themes/digett/gallery/images/slow.png',
      medium: '/sites/default/themes/digett/gallery/images/medium.png',
      fast: '/sites/default/themes/digett/gallery/images/fast.png',
    },
    controls: {
    	background: 'black',
    	height: 30,
    },
    thumbnails: {
    	background: 'black',
    	height: 28,
    	margin: 3,
    	hoverColor: 'white',
    	activeColor: 'red',
    },
    caption: {
      background: 'black',
      height: 30,
    },
    speed: {
    	slow: 7000,
    	medium: 5000,
    	fast: 1000,
    },
  };

  // merge passed options with defaults
  if(options) {
    $.extend(plugin.options, options);
  }
  
	// start the real work
  this.each(function() {
  	// e is the current element
    var e = this;
    
    // init some variables
    e.imageCount = $(e).find("li a").length;
    e.imageIndex = 0;
    e.imageCache = [];
    e.speed = plugin.options.speed.medium;

		// load image specified by e.imageIndex
		// clears interval before loading so avoid timing problems
    e.loadImage = function(i){
      if(i == undefined){
        i=e.imageIndex;
      }
      window.clearInterval(e.interval);
      e.imageIndex = i;
      
      // load image into cache if not already
      if(e.imageCache[i] == undefined){
        e.imageCache[i] = new Image;
        e.imageCache[i].onload = function(){
          e.loadImage(i);
        };
        e.imageCache[i].title = $(e).find("li a img").get(i).title;
        e.imageCache[i].src = $(e).find("li a").get(i).href;
      }else{
        e.displayImage(e.imageCache[i]);
      }
      
      // increment imageIndex and wrap to 0 if necessary
      e.imageIndex = i+1;
      if(e.imageIndex >= e.imageCount){
        e.imageIndex = 0;
      }
    };   
    
    // resize and display image and start interval for next image
    e.displayImage = function(img){
    	// convenience variable
    	var o = plugin.options;
    	// get h and w ratios and figure out which to use
      var wRatio = o.width / img.width;
      var hRatio = o.height / img.height;
      var ratio = o.clipMode ? Math.max(hRatio,wRatio) : Math.min(hRatio,wRatio);
      
      // figure new h,w,t,l values
      var w = img.width * ratio;
      var h = img.height * ratio;
      var l = (o.width - w)/2;
      var t = (o.height - h)/2;
      
      // load image into .viewport img tag
      $(e).find(".viewport img")
      	.css('display','none')
        .width(w+'px').left(l+'px')
        .height(h+'px').top(t+'px')
        .src(img.src).fadeIn(o.fxSpeed);
      // set caption
      $(e).find(".caption").html(img.title);
      
      $(e).find("li.active").removeClass('active')
      	.css('border-color',plugin.options.thumbnails.background);
      $($(e).find("li").get(e.imageIndex)).addClass('active')
      	.css('border-color',plugin.options.thumbnails.activeColor);
      
      // start interval for next image load
      e.interval = window.setInterval(e.nextImage,e.speed);
    };
    
    // load next image
    e.nextImage = function(){
      $(e).find(".viewport img").queue['fx'] = [];
	    $(e).find(".viewport img").fadeOut(plugin.options.fxSpeed, function(){
	      e.loadImage();
	    });
    };

    // load previous image
    e.previousImage = function(){
      i = e.imageIndex - 2;
      if(i < 0) i = e.imageCount + i;
      e.imageIndex = i;
      e.nextImage(i);
    };

		// dom modifications
    $(e).prepend('<div class="viewport"><img /></div>');
    $(e).prepend('<div class="controls-hover">' +
    	'<div class="controls">' +
        '<span class="play-status" style="margin-left:40px;">now playing</span>' +
        '<a href="#" class="pause" title="pause">'+
            '<img src="'+plugin.options.buttons.pause+'" alt="pause" /></a>' +
    	'<a href="#" class="back">'+
          '<img src="'+plugin.options.buttons.back+'" alt="back" /></a>' +
        '<span>|</span>' +
        '<a href="#" class="next">'+
            '<img src="'+plugin.options.buttons.next+'" alt="next" /></a>' +
        '<span style="margin-left:50px;">speed</span>' +
        '<a href="#" class="speed" rel="'+plugin.options.speed.slow+'">'+
            '<img src="'+plugin.options.buttons.slow+'" alt="slow" /></a>' +
        '<a href="#" class="speed" rel="'+plugin.options.speed.slow+'">'+
            '<img src="'+plugin.options.buttons.medium+'" alt="medium" /></a>' +
        '<a href="#" class="speed" rel="'+plugin.options.speed.slow+'">'+
            '<img src="'+plugin.options.buttons.fast+'" alt="fast" /></a>' +
    	'</div>' +
    	'</div>');
    $(e).find('.item-list')
    	.wrap('<div class="thumbs-hover"><div class="thumbs"></div></div>');
    $(e).find('.thumbs').prepend('<div class="caption">Caption</div>');

		// styling
    $(e).position('relative')
      .overflow('hidden')
      .width(plugin.options.width+'px')
      .height(plugin.options.height+30+'px')
      .background(plugin.options.background);
    $(e).find(".viewport")
      .width(plugin.options.width+'px')
      .height(plugin.options.height+'px')
      .overflow('hidden')
      .find('img').position('absolute');

		// thumbnails
    $(e).find('.thumbs')
    	.background(plugin.options.background)
    	.width(plugin.options.width+'px')
    	.position('absolute')
    	.css('bottom','0')
    	.find('ul').hide();
    $(e).find('li')
    	.height(parseInt(plugin.options.thumbnails.height * .75)+'px')
    	.width(parseInt(plugin.options.thumbnails.height * .75)+'px')
    	.overflow('hidden')
    	.float('left')
    	.css('padding','0')
    	.css('margin',plugin.options.thumbnails.margin+'px')
    	.css('border','solid 1px '+plugin.options.thumbnails.background)
    	.css('list-style','none')
    	.hover(function(){
	      if(!$(this).is('.active')){
	      	$(this).css('border-color',plugin.options.thumbnails.hoverColor);
	      }
	 		},function(){
	      if(!$(this).is('.active')){
	      	$(this).css('border-color',plugin.options.thumbnails.background);	      
	      }
	  	});
    	
    $(e).find('.caption')
    	.color('#e0e0e0')
    	.height('30px');
    $(e).find('.thumbs-hover')
      .position('absolute')
      .css('bottom','0')
      .width(plugin.options.width+'px')
      .hover(function(){
        $(e).find("ul").animate({height:'show'},'slow');
      },function(){
      	jQuery.dequeue($(this), "fx");
        $(e).find("ul").animate({height:'hide'},'slow');
      });
    
    // controls
    $(e).find(".controls")
    	.background(plugin.options.background)
      .height('30px')
      .width(plugin.options.width+'px')
    	.position('absolute')
    	.top('-30px')
    	.css('display','none');
    $(e).find('.controls-hover')
      .position('absolute')
      .top('0px')
      .height('25%')
      .width(plugin.options.width+'px')
      .hover(function(){
      	$.dequeue($(e).find(".controls"),'fx');
        $(e).find(".controls").animate({top:0},'slow');
      },function(){
      	$.dequeue($(e).find(".controls"),'fx');
        $(e).find(".controls").animate({top:-30},'slow');
      });
   	$(e).find(".controls a")
        .float('left')
   		.css('padding','0 5px')
   		.css('line-height','30px')
        .css('vertical-align','baseline')
   		.fadeTo('fast',0.5)
   		.hover(function(){
          if(!$(this).is('.active')){
            $(this).fadeTo('fast',1.0);
          }
   		},function(){
          if(!$(this).is('.active')){
   			$(this).fadeTo('slow',0.5);
          }
   		});
    $(e).find(".controls img").css('padding-top','8px');
    $(e).find(".controls span")
      .float('left')
      .color('#e0e0e0')
      .css('padding','0 10px')
      .css('line-height','30px')
      .css('font-size','10px');
    $(e).find('.controls a.back').click(function(){
      this.blur();
      e.previousImage();
      return false;
    });
    $(e).find('.controls a.next').click(function(){
      this.blur();
      e.nextImage();
      return false;
    });
    $(e).find('.controls a.pause').click(function(){
      this.blur();
    	if($(this).title() == 'pause'){
    		window.clearInterval(e.interval);
    		$(this).title('play').find('img')
              .src(plugin.options.buttons.play)
              .attr('alt','play');
            $(e).find('span.play-status').html('now paused');
    	}else{
    		e.nextImage();
    		$(this).title('pause').find('img')
              .src(plugin.options.buttons.pause)
              .attr('alt','pause');
            $(e).find('span.play-status').html('now playing');
    	}
    	return false;
    });
    $(e).find('.controls a.speed').click(function(){
      this.blur();
      e.speed = parseInt(this.rel);
      $(e).find('.controls a.speed.active')
      	.removeClass('active').fadeTo('fast',0.5);
      $(this).addClass('active');
      return false;
   	});

    // hook up thumbnail clicks
    $(e).find("li a").click(function(){
      this.blur();
      e.loadImage($(e).find("li a").index(this));
      return false;
    });
    
    // start slideshow
    e.loadImage();
  });
};

$(document).ready(function(){
  $('.gallery').slideshow({
    clipMode:false,
    width: 500,
    height: 500,
  });
});