function FlickrStream (opts) {
  this.apiKey = 'd464f6ddfa03f326d7e364684cb50f70';
  this.containerId = 'flickr_container';
  this.statusId = 'flickr_status';
  this.page = 1;
  this.perPage = 20;
  this.queue = [];

  opts = opts || {};

  if (typeof opts.method == 'undefined') {
    opts.method = 'flickr.photos.getRecent';
  }

  var params = $.extend(opts, {
    api_key: this.apiKey,
    format: 'json',
    page: this.page,
    per_page: this.perPge
  });

  this.url = 'http://api.flickr.com/services/rest/?' + $.param(params) + '&jsoncallback=?';

  $('<div />')
    .attr('id', this.statusId)
    .hide()
    .appendTo('#' + this.containerId);
};

FlickrStream.prototype = {
  fetch: function (callback) {
    var self = this;

    $.getJSON(this.url, function (obj) {
      if (!obj.photos || !obj.photos.photo) return false;
      $(obj.photos.photo).each(function (i, p) {
        self.queue.push(p);
      });
      if ($.isFunction(callback)) callback.apply(self, arguments);
    });
    this.page++;
    return this;
  },
  show: function () {
    var
      self = this,
      p = this.queue.shift(),
      link = 'http://www.flickr.com/photos/' + p.owner + '/' + p.id + '/',
      photo = 'http://farm' + p.farm + '.static.flickr.com/' + p.server + '/' + p.id + '_' + p.secret + '_m.jpg',
      html = '<div class="photo" style="display:none;"><a href="' + link + '" title="flickr" target="_blank">' +
        '<img src="' + photo + '" title="' + p.title + '" /></a></div>';
    $('#' + this.containerId)
      .prepend(html)
      .find('img:first')
        .load(function () {
          $('#loading').remove();
          $(this).closest('div').fadeIn(350);
        })
        .hover(function () { self.stop(); }, function () { self.start(); });
    if (this.queue.length < this.perPage/3)
      this.fetch();
    return this;
  },
  top: function () {
    //console.log(this.queue);
    return this;
  },
  start: function () {
    $('#' + this.statusId).fadeOut(200).empty();
    var self = this;
    this.intervalId = setInterval(function () { self.show(); }, 2500);
    return this;
  },
  stop: function () {
    var $s = $('#' + this.statusId)
      .css({backgroundColor: '#000', color: '#fff', opacity: 0.8})
      .html('STOP')
      .fadeIn(200);
    clearInterval(this.intervalId);
    return this;
  }
};
