(function($){
 
  $.fn.photoReel = function(images, options){
    
    options = $.extend({
      zIndex: 1,
      delay: 6000
    }, options);
    
    var container = this;
    var initImage = this.children('img:first');
    initImage.css({'opacity': 1, 'z-index': options.zIndex+3});
    
    var width = initImage.width();
    var height = initImage.height();
    var ratio = width/height;
    
    $(images).each(function(){
      if (this == initImage.attr('src')){
        return;
      }
      var img = new Image();
      $(img).load(function(){
        container.append(this);
        $(this).css({'opacity': 0, 'z-index': options.zIndex});
        /* Resize image */
        var imgRatio = $(this).width()/$(this).height();
        if (imgRatio < ratio && $(this).width() !== width){
          $(this).width(width);
        }
        else if (imgRatio > ratio && $(this).height() !== height){
          $(this).height(height);
        }
        else if ($(this).width() !== width && $(this).height() !== height){
          $(this).width(width);
        }
        /* Reposition image */
        var offset;
        if ($(this).width() > width){
          offset = ($(this).width()-width)/2;
          $(this).css({'left': '-'+offset+'px'});
        }
        if ($(this).height() > height){
          offset = ($(this).height()-height)/2;
          $(this).css({'top': '-'+offset+'px'});
        }
      }).attr({
        src: this
      });
    });
    
    var photoRotate = function(){      
      var active = container.children('img.active');
      if (active.length === 0) {active = container.children('img:first');}
      var next = active.next('img').length ? active.next('img') : container.children('img:first');
      active.css({'z-index': options.zIndex+2}).addClass('last-active');
      next.css({'opacity': 0, 'z-index':options.zIndex+3}).addClass('active').animate({'opacity': 1}, 2500, function(){
        active.css({'opacity': 0, 'z-index': options.zIndex}).removeClass('active last-active');
      });
    };
    var photoReel = setInterval(photoRotate, options.delay);

  };

})(jQuery);