if (typeof Yuku != 'object')
  throw 'Required objects missing';

yut.Flipper = function(el_id, template, timeout) {
  if (!timeout)
    timeout = 20000;
  var with_next_item = null;
  (function(){
    var items = [];
    var items_len = 0;
    var cur_item = -1;
    function preload_img(src) {
      var m = (new Image);
      m.src = src;
      if (!m.loaded)
	m.onload = m.onerror = function(){
	  m = null;
	};
    };

    function get_more_items(fn){
      $j.post('/flipper/get/format/json', function(res){
	items = eval('('+res + ')');
	items_len = items.length;
	cur_item = -1;
	/* set avatars to items, and preload them */
	for (var l = items_len; l--; ) {
	  var item = items[l];
	  var m = item.user.link.match(/\w+\.\w+\./);
	  if (m)
	    item.user.avatar = 'http://'+ m[0] + 'avatar.yuku.com';
	}
	fn();
      });
    };

    with_next_item = function(fn){
      cur_item++;
      if (cur_item == items_len){
	get_more_items(function(){
	  with_next_item(fn);
	});
      }
      else {
	fn(items[cur_item]);
	if ((cur_item + 1) < items_len)
	  preload_img(items[cur_item + 1].user.avatar);
      }
    };
  })();

  var $el = $j('#'+el_id);

  function show_item(item){
    var data = item.user;
    var post = item.post.description;
    if (post.length > 163)
      data.post = post.slice(0, 163) +'...';
    else
      data.post = post;
    data.post_title = item.post.title;
    data.post_link = item.post.link;

    $el.html('');
    var $item = $j(yut.String.replaceFromDict(template, data));
    $item.hide().appendTo($el).fadeIn();
  };

  (function show_next_item(){
    with_next_item(function(item){
	var $c = $el.children();
	if ($c.length)
	  $c.fadeOut(function(){show_item(item)});
	else
	  show_item(item);
	setTimeout(show_next_item, timeout);
      });
  })();
};

