/**
 * Regenanimation
 *
 * @author Christian Studer <christian.studer@meteotest.ch>
 */

var play = 0;
var currentValue = 1;
var filename = 'rain_wrf_?.jpg';
var timer;

$(document).ready(function () {
	// Setup slider and click events
	$('#mtslider').slider({
		value: currentValue,
		min: 1,
		max: 64,
		step: 1,
		slide: sliderMoved
	});
	$('#mtbutton').click(togglePlay);
	
	togglePlay();
});

/**
 * Toggle the play functionality
 * 
 */
function togglePlay() {
	play = 1 - play;
	
	if(play) {
		$('#mtbuttonimg').attr('src', 'images/pause.png');
		timer = setInterval('showNextImage()', 1500);
	} else {
		$('#mtbuttonimg').attr('src', 'images/play.png');
		clearInterval(timer);
	}
}

/**
 * Treat slider changes
 * 
 * @param event
 * @param ui
 */
function sliderMoved(event, ui) {
	if(play) {
		togglePlay();
	}
	
	showImage(ui.value);
}

/**
 * Show image with number
 * 
 * @param int number
 */
function showImage(number) {
	$('#mtrainimg').attr('src', filename.replace(/\?/, number));
	currentValue = number;
	$('#mtslider').slider('value', number);
}
 
 /**
  * Show next image and preload over-next
  */
function showNextImage() {
	var nextValue = calcNextValue(currentValue);	
	showImage(nextValue);
	
	// Preload next image
	nextValue = calcNextValue(nextValue);
	var preloadedImage = new Image();
	preloadedImage.src = filename.replace(/\?/, nextValue); 
}

/**
 * Calculate next value
 * 
 * @param int value
 * @return int nextValue
 */
function calcNextValue(value) {
	var nextValue = value + 1;
	if(nextValue == 65) {
		nextValue = 1;
	}
	
	return nextValue;
}
