/*
	Copyright (c) 2007-2008 JB Interactive Pty. Ltd.
	All Rights Reserved
	http://www.jbinteractive.com.au/
*/

(function($) {
	
var animators = {};
var timer;

$.fn.pngimate = function (o) {

	o = $.extend({}, $.fn.pngimate.defaults, o);

	var id = $.data(this[0]);

	animators[id] = {
			running: false,
			element: this[0],
			frame: 0,
			frames: o.frames,
			step: [-1 * o.tileWidth, -1 * o.tileHeight],
			tiles: [o.imageWidth / o.tileWidth, o.imageHeight / o.tileHeight]
		};

	return $(this);
};

$.fn.pngstart = function () {
	var id = $.data(this[0]);
	animators[id].running = true;
};

$.fn.pngstop = function () {
	var id = $.data(this[0]);
	animators[id].running = false;
};

$.fn.pngimate.tick = function () {

	$.each(animators, function () {
		if (!this.running) return;		
		var pos = $.fn.pngimate.nextTile (this);
		$(this.element).css('backgroundPosition', pos[0] + 'px ' + pos[1] + 'px');
	});
};

$.fn.pngimate.nextTile = function (a) {
	a.frame++;
	if (a.frame >= a.frames) a.frame = 0;
	var col = a.frame % a.tiles[0];
	var row = Math.floor(a.frame / a.tiles[0]);
	return [col * a.step[0], row * a.step[1]];
};

$.fn.pngimate.defaults = {
	tileWidth:   16,
	tileHeight:  16,
	imageWidth:  96,
	imageHeight: 16,
	frames:       6,
	frameRate:   15
};

var FADE_TIME = 100;
var ANIM_TIME = 500;
var WAIT_TIME = 800;

var over  = function () { $('#captcha_refresh').animate({'opacity': '1.0'}, FADE_TIME); };
var out   = function () { $('#captcha_refresh').animate({'opacity': '0.2'}, FADE_TIME); };
var click = function () {
	var $c  = $('#captcha_img_area');
	var $cr = $('#captcha_refresh', $c);
	var $ci = $('#captcha_img', $c);
	var src = $ci.attr('src');

	$c.unbind('mouseover').unbind('mouseout').unbind('click').css('cursor', 'wait');
	$ci.fadeOut(ANIM_TIME);
	$cr
		.animate({top: (($c.height() - 16) / 2) + 'px', left: (($c.width() - 16) / 2) + 'px'}, ANIM_TIME, function () {
			$cr.pngstart();
			$ci.attr('src', src + '?' + Math.random()).load(function () {
				setTimeout (function () {
					$ci.fadeIn(ANIM_TIME);
					$cr.animate({top: '2px', left: '2px'}, ANIM_TIME, function () {
						$c.css('cursor', 'pointer').click(click).mouseover(over).mouseout(out);
					}).pngstop();
				}, WAIT_TIME);
			});
		});
};
	
$(document).ready(function() {
	if ($('#captcha_img_area').is('*')) {
		timer = setInterval($.fn.pngimate.tick, 1000 / 24);
		$('#captcha_img_area').hover(over, out).click(click);
		$('#captcha_refresh').css('opacity', '0.2').pngimate();
	}	
});

})(jQuery);