(function($) {
	$(document).ready(function() {
		$(".mixtape-post-image", this).hover(function() {
			$(".mixtape-front", this).hide();
			$(".mixtape-back", this).show();
		}, function() {
			$(".mixtape-back", this).hide();
			$(".mixtape-front", this).show();
		});
		
		new Rotator(ROTATOR_MIXTAPES_FEED_URL, '#mixtapes-widget', 260, 260, 10000);
		new Rotator(ROTATOR_FEATURES_FEED_URL, '#features-widget', 865, 343, 10000);
	});
})(jQuery);

function Rotator(xml_url, div, width, height, delay) {
	// set default properties
	var filenames = new Array();
	var links = new Array();
	var length = 0;
	var obj = this;
	$ = jQuery;
	
	// get filenames and links
	$.ajax({
		type: "GET",
		url: xml_url,
		dataType: "xml",
		success: function(xml) {
			$(xml).find("image").each(function() {
				filenames[length] = $(this).find("filename").text();
		   		links[length] = $(this).find("link").text();
				length++;
			});
			obj.div = $(div);
			obj.filenames = filenames;
			obj.links = links;
			obj.ubound = length - 1;
			obj.name = div;
			obj.delay = delay;
			obj.timeout = null;
			obj.current = 0;
			
			// add navigation buttons
			var prev_arrow = $("<a />").click(function() {
				obj.prev();
			}).attr('class','arrow-left rotator-arrow').append($("<img />").attr({
				src: ROTATOR_INSTALL_DIR + '/images/left.gif',
				alt: 'Previous'
			}));
			var next_arrow = $("<a />").click(function() {
				obj.next();
			}).attr('class','arrow-right rotator-arrow').append($("<img />").attr({
				src: ROTATOR_INSTALL_DIR + '/images/right.gif',
				alt: 'Next'
			}));
			var nav = $("<div />").attr('class','rotator-nav').append(prev_arrow).append(next_arrow);
			var rotator_img = $("<img />").addClass('rotator-image').attr({
				src : '',
				height : height,
				width : width
			});
			var rotator_img_a = $("<a />").addClass('rotator-image-link').attr({
				href : '#',
				target : '_blank'
			});
			rotator_img_a.append(rotator_img);
			obj.div.append(nav).append(rotator_img_a).css('position','relative');
			
			// preload pictures
			preloadImages(obj.filenames);
			
			// show the picture
			obj.update();
			
			//start automatic rotate
			obj.reset_time();
		}
	});
}

Rotator.prototype.reset_time = function() {
	if (this.delay > 0) {
		clearTimeout(this.timeout);
		this.timeout = setTimeout(this.name + '.next()', this.delay);
	}
}

Rotator.prototype.next = function() {
	this.reset_time();
	this.current++;
	if (this.current > this.ubound) {
		this.current = 0;
	}
	this.update();
}

Rotator.prototype.prev = function() {
	this.reset_time();
	this.current--;
	if (this.current < 0) {
		this.current = this.ubound;
	}
	this.update();	
}

Rotator.prototype.update = function() {
	$(".rotator-image", this.div).attr('src',this.filenames[this.current]);
	$(".rotator-image-link", this.div).attr('href', this.links[this.current]);
}

function preloadImages(filenames) {
	for (var i=1; i<filenames.length; i++) {
		img = new Image();
		img.src = filenames[i];
	}
}
