/**
 * Slider tool for the Meteotest homepage
 *
 * @author Christian Studer <christian.studer@meteotest.ch>
 */
var defaultOptions = {
	autoplay : false,
	startindex : 0,
	preloads : 3,
	direction : "right",
	width : null,
	height : null,
	lightbox : false,
	secondloop : false,
	interval : 6
};
var options = {};

var playStatus = 0;
var secondloop = false;
var imageList = {};
var numberOfImages = null;
var buttons = {
	play : "/meteotest-extras/slider/images/play.png",
	playActive : "/meteotest-extras/slider/images/play_active.png",
	pause : "/meteotest-extras/slider/images/pause.png",
	pauseActive : "/meteotest-extras/slider/images/pause_active.png"
};
var tooltip;
// Set up slider once the document is ready
$(document).ready(
		function() {
			// Get JSON for current project
			$.getJSON(
					'/meteotest-extras/slider/service.php?project=' + project,
					installProject);
		});

/**
 * Install project
 *
 * @param object
 *            data
 */
function installProject(data) {
	// Hide JavaScript warning
	$("#sliderwarning").hide();

	// Check for error
	if (data["error"]) {
		alert("Slidertool error: " + data["error"]);
		return;
	}

	// Load optional options
	if (data["jsconfig"]) {
		options = $.extend({}, defaultOptions);
		$.extend(options, data["jsconfig"]);
	}

	imageList = data["imagelist"];
	imageKeys = data["imagekeys"];
	numberOfImages = imageList.length;
	var singleImage = (numberOfImages == 1);
	var startIndex = options.startindex;

	if (startIndex < 0) {
		startIndex = numberOfImages + startIndex;
	}

	// Check if any images are in the list
	if(imageList.length == 0) {
		return;
	}

	// Set up slider
	$("#sliderslider").slider("enable").slider("destroy").empty();
	if (options.secondloop === false) {
		$("#sliderslider").slider({
			min : 0,
			max : numberOfImages - 1,
			value : startIndex,
			change : displayImage,
			disabled : false,
			slide : displayImage
		});
		secondloop = false;
	} else {
		var rangeIndex = options.secondloop;

		if (rangeIndex < 0) {
			rangeIndex = numberOfImages + rangeIndex;
		}

		$("#sliderslider").slider({
			min : 0,
			max : numberOfImages - 1,
			range : true,
			values : [ rangeIndex, startIndex ],
			change : displayImage,
			disabled : false,
			slide : displayImage
		});
		secondloop = true;

		$("#sliderslider a:first").addClass("rangeslider");
	}

	if (imageKeys.length > 0) {
		// Setup Tooltips. But check if there are any Tooltip-texts available
		var tooltipContainer = $('#sliderslider').append('<span class="ui-slider-tooltip ui-widget-content ui-corner-all"></span>');
		tooltipContainer = $('#sliderslider span').hide();
		tooltipContainer.append('<span class="tooltip_content"></span>');
		tooltipContainer.append('<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner" style="border-top-width: 7px; border-top-style: solid; border-top-color: rgb(252, 253, 253); "></span></span>');

		if (options.secondloop === false) {
			var tooltipText = imageKeys[$('#sliderslider').slider('value')];
			tooltip = $("span.tooltip_content").text(tooltipText);
			$('#sliderslider').find(".ui-slider-handle").append(tooltipContainer).hover(function() {
				tooltipContainer.show();
			}, function() {
				tooltipContainer.hide();
			});
		} else {
			var tooltipIndexes = $('#sliderslider').slider('values');

			tooltip = [];
			var tt1 = tooltipContainer.clone();
			var tt2 = tooltipContainer.clone();
			tooltip[0] = $('span.tooltip_content', tt1);
			tooltip[1] = $('span.tooltip_content', tt2);

			tooltip[0].text(tooltipIndexes[0]);
			tooltip[1].text(tooltipIndexes[1]);

			$('#sliderslider').find(".ui-slider-handle").eq(0).append(
					tt1).hover(function() {
				tt1.show();
			}, function() {
				tt1.hide();
			});
			$('#sliderslider').slider().find(".ui-slider-handle").eq(1).append(
					tt2).hover(function() {
				tt2.show();
			}, function() {
				tt2.hide();
			});
		}
	}

	// Add buttons
	if (!singleImage) {
		if (options.autoplay) {
			// Show pause image
			$("#sliderbutton").html(
					"<img src='" + buttons.pause
							+ "' alt='Start/Stop' title='Start/Stop' />");

			// Start playing
			startPlay();
		} else {
			// Show play image
			$("#sliderbutton").html(
					"<img src='" + buttons.play
							+ "' alt='Start/Stop' title='Start/Stop' />");
			stopPlay();
		}

		$("#sliderbutton img").click(togglePlay).hover(toggleHover,
				toggleHoverOut);
	} else {
		$("#sliderbutton").html('');
		$("#sliderslider").slider('disable');
		stopPlay();
	}

	makeScale();

	// Show initial image
	displayImage();

	// Get width and height
	options.width = (options.width) ? options.width : $("#slideroutput img")
			.width();
	options.height = (options.height) ? options.height : $("#slideroutput img")
			.height();
}

/**
 * Shows current image and preloads the next images
 */
function displayImage() {

	if (options.secondloop === false && imageKeys.length > 0) {
		tooltip.text(imageKeys[$('#sliderslider').slider('value')]);
	} else if (imageKeys.length > 0) {
		var tooltipIndexes = $('#sliderslider').slider('values');
		tooltip[0].text(imageKeys[tooltipIndexes[0]]);
		tooltip[1].text(imageKeys[tooltipIndexes[1]]);
	}

	var index = secondloop ? ($("#sliderslider").slider("values"))[1] : $(
			"#sliderslider").slider("value");
	if (options.width && options.height) {
		$("#slideroutput").html(
				"<img src='" + imageList[index] + "' width='" + options.width
						+ "' height='" + options.height + "' />");
	} else {
		$("#slideroutput").html("<img src='" + imageList[index] + "' />");
	}

	if (options.lightbox) {
		$("#slideroutput img").wrap(
				"<a href='" + imageList[index] + "' rel='lightbox' />");
	}

	// Preload the next couple of images
	var start = index;
	var preloadDirection = playStatus || 1;
	var stop = Math.max(0, Math.min(index
			+ (preloadDirection * options.preloads), numberOfImages - 1));
	for ( var i = start; i != stop; i += preloadDirection) {
		var image = new Image();
		image.src = imageList[i];
	}
}

/**
 * Toggle current play status
 */
function togglePlay() {
	if (playStatus == 0) {
		startPlay();
	} else {
		stopPlay();
	}
}

/**
 * Definitly start playing
 */
function startPlay() {
	// Turn play on
	switch (options.direction) {
	default:
	case "right":
		playStatus = 1;
		break;
	case "left":
		playStatus = -1;
		break;
	}
	$("#sliderslider").everyTime("1s", playNext);
}

/**
 * Definitly stop playing
 */
function stopPlay() {
	playStatus = 0;
	$("#sliderslider").stopTime();
}

/**
 * Show next image
 */
function playNext() {
	var currentIndex = secondloop ? ($("#sliderslider").slider("values"))[1]
			: $("#sliderslider").slider("value");
	var nextIndex = currentIndex + playStatus;

	if (secondloop) {
		var rangeIndex = ($("#sliderslider").slider("values"))[0];

		if (nextIndex < rangeIndex) {
			nextIndex = numberOfImages - 1;
		} else if (nextIndex >= numberOfImages) {
			nextIndex = rangeIndex;
		}

		$("#sliderslider").slider("values", [ rangeIndex, nextIndex ]);
	} else {
		if (nextIndex < 0) {
			nextIndex = numberOfImages - 1;
		} else if (nextIndex >= numberOfImages) {
			nextIndex = 0;
		}

		$("#sliderslider").slider("value", nextIndex);
	}

	displayImage();
}

/**
 * Image replacing for the button
 *
 */
function toggleHover() {
	var newButton;

	if (playStatus == 0) {
		newButton = buttons.playActive;
	} else {
		newButton = buttons.pauseActive;
	}

	$("#sliderbutton img").attr("src", newButton);
}

/**
 * Image replacing for the button
 *
 */
function toggleHoverOut() {
	var newButton;

	if (playStatus == 0) {
		newButton = buttons.play;
	} else {
		newButton = buttons.pause;
	}

	$("#sliderbutton img").attr("src", newButton);
}

// make scale
// inspired by:
// http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/
var makeScale = function() {
	var theSlider = $('#sliderslider');
	var scale = theSlider.append(
			'<ol class="ui-slider-scale ui-helper-reset"></ol>').find(
			'.ui-slider-scale:eq(0)');
	var i = 0;
	for (i = 0; i < imageKeys.length; i++) {
		var style = (i == imageKeys.length - 1 || i == 0) ? 'style="display: none;"'
				: '';
		var text = imageKeys[i];
		text = text.replace(/ /g, '&nbsp;');
		scale.append('<li style="left:' + leftVal(i)
				+ '"><span class="ui-slider-label">' + text
				+ '</span><span class="ui-slider-tic ui-widget-content"'
				+ style + '></span></li>');
	}

	function leftVal(i) {
		return (i / (imageKeys.length - 1) * 100).toFixed(2) + '%';
	}

	// TEST: Set 6h interval
	if(options.interval !== undefined) {
		var allTicks = $('#sliderslider .ui-slider-tic');
		// First: set last and first legend
		var theLast = theSlider.find('.ui-slider-scale li:last span.ui-slider-label');
		var theFirst = theSlider.find('.ui-slider-scale li:first span.ui-slider-label');
		var legendWidth = theLast.width() === 0 ? 90 : theLast.width() ;

		theLast.addClass('ui-slider-label-show').css('left', -( legendWidth/2 ));
		theFirst.addClass('ui-slider-label-show').css('left', -( legendWidth/2 ));
		theSlider.removeAttr('style'); // remove styling from other tab (mutlislider)
		var theMarginRight = parseInt(theSlider.css('margin-right'));
		theSlider.css('margin-right',( theMarginRight + legendWidth/2 ));
		theSlider.css('margin-left',  legendWidth/2);
		var marginTicks = options.width / imageKeys.length;
		var sliderWidth = options.width - legendWidth; // One Legend width is used by first and last

		var interval = 0;
		var progress = 0;
		for (i = 0; i < imageKeys.length; i++ ) {
			var thisTime = imageKeys[i].match(/\d+\:\d+/g)[0].match(/\d+/g);

			if (thisTime[0] % options.interval === 0 && thisTime[1] === '00') {
				allTicks.eq(i).addClass('tic_interval');
				interval += i * marginTicks - progress;
				progress = i * marginTicks;
				if ( (interval > legendWidth + 15) && (sliderWidth - progress > legendWidth / 2) ) {

					interval = 0;
					allTicks.eq(i).addClass('tic_legend');
					allTicks.eq(i).prev('span').addClass('ui-slider-label-show').css('marginLeft', -( legendWidth / 2));
				}
			}
		}
	}

/*
	// set visible labels (there are either 0 or >1 labels)
	if (options.labels > 0) {
		// set last one visible
		var theObject = theSlider.find('.ui-slider-scale li:last span.ui-slider-label');
		theObject.addClass('ui-slider-label-show');
		var objectWidth = theObject.width();
		theObject.css('marginLeft', - (objectWidth==0 ? 78 : objectWidth)); // Hack for Webcam
		options.labels -= 1;

		// set increment
		var increm = Math.max(1, Math.round((imageKeys.length - 1)
				/ Math.max(1, options.labels))); // subtract 1, because last label is already set at this point. mathmax to assure no division by zero
		for (i = 0; i < imageKeys.length; i += increm) {
			if ((imageKeys.length - i) >= increm) {
				var theLabel = theSlider.find(
						'.ui-slider-scale li:eq(' + i
								+ ') span.ui-slider-label').addClass(
						'ui-slider-label-show');
				if (i>0) {
					theLabel.css('marginLeft', - (theLabel.width() /2));
				}
			}
		}
	} */
};
