(function($) {

	$.fn.imageRotate = function (xmlFile, speed, left, top) {
		var rotator = this,
			index = 1,
			numImages = 0;

		var rotate = function() {
			var delay = speed * 1000;

			rotator.find('a:nth-child(' + index + ')')
				.fadeOut('slow', function() {
					$(this).css({
						'position':'absolute',
						'z-index':0
					});
				});

			index += 1;
			if (index > numImages) {
				index = 1;
			}

			rotator.find('a:nth-child(' + index + ')')
				.fadeIn('slow', function() {
					$(this).css({
						'position':'relative',
						'z-index':5
					});
					setTimeout(rotate, delay);
				});
		};

		$.get(xmlFile, function(data) {
			// clear element
			rotator.html('')
				.css('position', 'relative');
			
			$(data).find("image").each(function () {
				var a = $('<a />')
					.attr('href', $(this).attr("link"))
					.css({
						'position' : 'absolute',
						'left': left,
						'top': top,
						'display':'none'
					})
					.click(function () {
						_gaq.push(['_trackEvent', $(this).attr("ga"), 'clicked']);
					})
					.appendTo(rotator);
				$('<img />')
					.attr('src', $(this).attr("src"))
					.appendTo(a);
				
				if (numImages === 0)
					a.css('display','block');
				numImages += 1;
			});

			setTimeout(rotate, speed * 1000);
		});
	};

})(jQuery);
