// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var timeout = 6000;

function jtImageurl(size, index) {
	var jt_url;
	if(size == 'medium') {
		jt_url = artists[index].image_medium;
	} else {
		jt_url = artists[index].image_full;
	}
	return jt_url;
}

function jtInfo(index) {
	var i = parseInt(index);
	return '<a href="'+ artists[index].url + '">' + artists[index].name + ' &rsaquo;</a>';
}

function rotateJumbotron(artists, size) {
	var opacity = 0;
	var $div = $('#jt-image');
	var $old = $div.find('img:visible');
	var next_id;
	var $next = [];
	
	if($old.length != 0) {
		next_id = parseInt($old.attr('data-position')) + 1;	
		
	} else {
		opacity = 1;
		next_id = 0;
	}
	
	if (next_id > artists.length - 1) {
		next_id = 0;
	}
	
	$next = $div.find('img[data-position='+ next_id +']');
	
	//console.log("VISIBLE: " + $old.length + " NEXT IS: " + next_id + ' LENGTH: ' + artists.length + ' SRC: ' + jtImageurl(size, next_id));
	
	if($next.length != 0) {
		// image is in the dom
		jtSwap($old, $next);
	} else {
		// pre-load
		var img = new Image();
		$(img).load(function () {
			var $next = $(this);
			$div.append($next);
			jtSwap($old, $next);
		}).attr({'src': jtImageurl(size, next_id), 'data-position': next_id}).css({'opacity': opacity, 'z-index': 1});	
	}
}

function jtSwap(old, next) {
	var $div = $('#jt-image');
	
	// Rotate the artist name that is superimposed on the artist image.	
	$div.find('#jt-info').fadeOut(600, function(){
		$div.find('#jt-info').html(jtInfo($(next).attr('data-position')) ).fadeIn(1500);
	});
	
	$(next).css({'display':'block', 'z-index': 1}).animate({ opacity: 1 }, 3000, function() {
		$(old).css({opacity: 0, 'display': 'none'});
		$(this).css('z-index', 0);
	});
	
	setTimeout("rotateJumbotron(artists, size)", timeout);
}


