$.fn.slideshow = function(){
  
  var $display = $('<div class="slideshow-display">');
  
  var $nav     = $('<div class="slideshow-nav">')
    var $back    = $('<div class="slideshow-back">').appendTo($nav);
    var $next    = $('<div class="slideshow-next">').appendTo($nav);
  
  var ulWidth = 1;
  var ulHeight = 100;
  
  var $holder = $('<div class="slideshow-holder">');
  
  var $ul = this;
  var $thumbs = this.find('li').css('position','absolute');
  
  var pageCount = Math.ceil($thumbs.size()/4);
  
  var currentPage = 0;
  
  var go = function(page){
    if(page >= 0 && page < pageCount){
      $ul.animate({marginLeft:page*-ulWidth});
      currentPage = page;
    }
  }
  
  $next.click(function(){
    go(currentPage + 1);
  });
  
  $back.click(function(){
    go(currentPage - 1);
  });
  
  
  // resize the image maintaining aspect ratio
  var resizeImage = function(){
    var $img = $display.find('img');
    
    // reset the image styles
    $img.attr('style','')
    
    var ratio = $img.height()/$img.width();
    
    var width = $display.width();
    $img.width(width);
    $img.height(width*ratio);
  }
  
  
  var resize = function(){
    var width = $display.width();
    ulWidth = width * 0.9;
    $ul.css({marginLeft:currentPage*-ulWidth});
    $thumbs.each(function(i){
      $(this).css({
        left:i*(ulWidth/4),
        width:(ulWidth/4 - 10)
      })
    });
    
    ulHeight = $thumbs.first().height();
    
    $ul.parent().height(ulHeight);
    $nav.children().height(ulHeight);
    
    // resize the main image too
    resizeImage();
    
  }
  
  $(window).bind('load resize', resize);
  
  this.before($display,$nav);
  
  this.wrap($holder);
  
  this.find('a').click(function(e){
    e.preventDefault();
    $display.find('img').css('position','absolute').fadeOut(function(){
      $(this).remove();
    });
    var $img = $('<img>', {src:$(this).attr('href')}).hide().appendTo($display).fadeIn();
    resizeImage();
    $img.bind('load', resizeImage);
    setTimeout(resizeImage,500);//sometimes load can't be relied on
  })
  .first().click()
};
