$(function() {
  $.fn.transit = function(options) {
    var defaults = {
      duration: 5000,
      transition: 1000,
      width: null,
      height: null,
      autostart: true,
      callback: null,
      maxCount: null
    };

    var opts = $.extend(defaults, options);
    var width = opts.width || $(this).outerWidth();
    var height = opts.height || $(this).outerHeight();
    var maxCount = opts.maxCount || 1;
    var timer = null;

    var next = function(elem) {
      var count = parseInt($(elem).css('background-image').split('/').pop().replace(/[^0-9]+/g, ''));
      if (count == maxCount)
        count = 1;
      else
        count += 1;

      var placeholder = $('<div></div>').css({left: 0, position: 'absolute', top: 0, zIndex: 1}).height(height).width(width).hide();
      var img = new Image();
      $(img).load(function () {
        placeholder.css('background', 'url("' + img.src + '")');
        $(elem).append(placeholder);
        placeholder.fadeIn(opts.transition, function() {
          $(elem).css('background-image', 'url("' + img.src + '")');
          placeholder.remove();
        });
      }).attr('src', '/images/dates/' + count + '.jpg');
    };

    var dotimer = function (elem) {
      if(timer != null) clearInterval(timer);

      timer = setInterval(function() {
        next(elem);
      }, opts.transition + opts.duration);
    };

    opts.autostart && dotimer(this);
  };
});
