(function ($) {
  $.fn.snapshots = function (options) {
    options = $.extend({}, { format: "l", host: "http://preview.exvo.com", retry_count: 20, retry_delay: 3000 }, options);
    
    var params = { u: [], s: options.format }, els = this;

    this.each(function () {
      params.u.push($(this).attr("data-url"));
    });

    var count = 0, default_image_url;

    (function request(params) {
      count += 1;
      $.getJSON(options.host + "/snapshots.json?_callback=?", params, function (data) {
        if(data.status == 200) {
          params.u = [];
          
          $.each(data.snapshots, function() {
            if(this.image_present) {
              els.filter("[data-url=" + this.url + "]").attr("src", this.image_url);
            } else {
              if(!default_image_url) {  // Set once
                default_image_url = this.image_url;
              }
              params.u.push(this.url);
            }
          });
          
          if(params.u.length > 0) {
            if (count < options.retry_count) {
              setTimeout(function () {request(params)}, options.retry_delay);
            } else {
              $.each(params.u, function () {
                els.filter("[data-url=" + this + "]").attr("src", options.default_image_url || default_image_url);
              });
            }
          }
        };
      });
    })(params);

    return this;
  };
  
  $.queue_snapshot = function (url, options) {
    options = $.extend({}, { format: "l", host: "http://preview.exvo.com" }, options);
    $.getJSON(options.host + "/snapshot.json?_callback=?", { s: options.format, u: url });
  }
})(jQuery);
