var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);

$.fn.fade_unless_ios = function(fade, callback) {
  if(ios) {
    callback.call(this.hide());
  } else {
    this.fadeOut(fade, callback);
  }
  return this;
}

$.fn.grace_carousel = function(images) {
  var carousel = this;

  if(images.length > 0) { // no slides? no show!

    var delay = 3000; // delay between fades: 1 second
    var fade = 550; // fade time: 300 milliseconds

    // insert images
    for(var i in images) {
      $('<li>').hide().html(images[i]).appendTo(carousel);
    }

    // insert loading indicator
    $('<li>').addClass('loading').appendTo(carousel);

    // remove loading indicator after images load
    carousel.imagesLoaded(function() {
      carousel.find('.loading').fade_unless_ios(fade, function() {
        $(this).remove();
      });
      setTimeout(function() {
        slides.first().grace_next_slide(fade, delay);
      }, delay);
    });

    var slides = carousel.children('li');

    slides.each(function(index) {
      var next = $(slides[index + 1]);
      if((next.length <= 0) || (next.hasClass('loading'))) {
        next = $(slides[0]);
      }
      $(this).data('next', next);
    });
  }
};

$.fn.grace_next_slide = function(fade, delay) {
  var next = this.data('next');
  next.show();
  this.addClass('current').fade_unless_ios(fade, function() {
    $(this).hide().removeClass('current');
  });
  setTimeout(function() {
    next.grace_next_slide(fade, delay);
  }, delay);
};

