/*
 * PhotoRandom 1.2
 * http://yungsang.com/tumblr/
 *
 * Copyright (c) 2008 YungSang
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */

$(function () {
	if (!photo_id)   photo_id   = 'photorandom';
	if (!photo_size) photo_size = 250;
	
	var interval = 5000;

	var $photo = $('#' + photo_id);
	if (!$photo.length) return;
	
	var $a   = $('a', $photo);
	var $img = $('img', $photo);

	var image = {};
	image['photo-url-' + photo_size] = $img.attr('src');
	image.width  = $img.get(0).width;
	image.height = image.width;
	if ($a.length) {
		image.url = $a.attr('href');
	}

	$img.parent().css({
		display   : 'block',
		overflow  : 'hidden',
		width     : image.width + 'px',
		height    : image.height + 'px',
		backgroundColor: '#000'
	});
	
	$.getJSON('http://' + user_name + '.tumblr.com/api/read/json?type=photo&callback=?', function (json) {
		if (!json || !json.posts || !json.posts.length) return;
		var posts = json.posts;
		posts.push(image);

		setTimeout(function () { replace(posts); }, interval);
	});

	function replace(posts) {
		shuffle(posts);
		var post = posts[0];

		var preload = new Image();
		preload.onload = function () {
			var height = Math.floor(image.width / preload.width * preload.height);
			$img.fadeOut(1000, function () {
				$img.attr({src: post['photo-url-' + photo_size]})
					.css({marginTop: -1 * Math.floor((height - image.height) / 2)});
				if ($a.length) {
					$a.attr({href: post.url});
				}
				$(this).fadeIn(2000, function () {
					delete preload;
				}).css({display: 'block'});
				setTimeout(function () { replace(posts); }, interval);
			});
		};
		preload.src = post['photo-url-' + photo_size];
	};

	function shuffle(o){
		for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
		return o;
	}
});
