(function($) {

  $.fn.slideshow = function(options) {
    var settings = $.extend({}, $.fn.slideshow.defaults, options);

    if (settings.image_path) {
      var image_prefix = settings.image_path + '/';
    } else {
      var image_prefix = '';
    }

    for (sk in settings.slides) {
      (new Image()).src = image_prefix + settings.slides[sk].image;
    }

    return this.each(function() {
      var self = $(this);
      self.addClass('slideshow');
      var current_slide = 0;
      var change_interval = null;
      $('<a class="frame frame-top"></a>').appendTo(self);

      function set_slide(slide_number, fast)
      {
        current_slide = slide_number;
        change_slide(fast);
        set_auto_change();
      }

      function next_slide(fast)
      {
        if (current_slide == settings.slides.length - 1) {
          current_slide = 0;
        } else {
          current_slide++;
        }
        change_slide(fast);
        set_auto_change();
      }

      function change_slide(fast)
      {
        var slide = settings.slides[current_slide];
        var frame = $('<a class="frame"></a>')
          .css('background-image', 'url(' + image_prefix + slide.image + ')')
          .attr({'href': slide.link, 'title': slide.title});
        frame.appendTo(self).show();
        if (!fast) {
          $('a.frame-top', self).animate({opacity: 0}, 'slow', 'swing',
            function () { $(this).remove(); frame.addClass('frame-top'); });
        } else {
          $('a.frame-top', self).remove();
          frame.addClass('frame-top');
        }
      }

      function set_auto_change()
      {
        clearInterval(change_interval);
        change_interval = window.setInterval(function() {
          next_slide();
        }, settings.delay);
      }

      change_slide();
      set_auto_change();
    });
  };

  $.fn.slideshow.defaults = {
    slides: [],
    image_path: '',
    delay: 3000
  };

})(jQuery);
