/* using var len defined in inline script, index.jim */
/* using var file defined in inline script, index.jim */
/* using var dir defined in inline script, index.jim */
function
toTimeStr(tval)
{
	return new Date(null, null, null, null, null, tval)
	    .toTimeString().match(/\d{2}:\d{2}:\d{2}/)[0];
}

function
valarray(valstr)
{
	return valstr.trim().split(/\s+/);
}

$(function() {
	var curval = 0;
	var $slider;
	var values;

	function
	sortmarks()
	{
		values.sort(function(a, b){return a - b});
		$('#bookmarks').val(values.join(" "));
	}

	function
	refreshtimes()
	{
		var t = '';
		if (values.length > 0 && values[0] != '')
		{
			$.each(values, function(k, v) {
				if (t != '') t += ', ';
				t += toTimeStr(v);
			});
			$('#slider .ui-slider-handle').each(function(i) {
				if (values[i]|0 > 0)
				$(this).attr('title', toTimeStr(values[i]))
				else $(this).attr('title', '');
			});
			$('#curbmk').html(toTimeStr(curval));
			$('#genthumbs').button('enable');
		}
		else
		{
			$('#genthumbs').button('disable');
			$('#curbmk').html('');
		}
		$('#bookmarkstime').text(t);
	}

	function
	setvals()
	{
		var nvalues;
		values = valarray($('#bookmarks').val());
		nvalues = new Set();
		$.each(values, function(k, v) {
			if (v > len)
				v = len;
			if (v < 0)
				v = 0;
			nvalues.add(v);
		});
		values = Array.from(nvalues);
		sortmarks();
	}

	function
	regenthumbs(curbmkstr)
	{
		$('#curbmk').html(curbmkstr);
		$('#thumbs').hide();
		$('#genthumbs')
		    .button(curbmkstr ? 'enable': 'disable')
		    .button('option', 'icon', 'ui-icon-zoomin');
	}

	function
	draw_slider()
	{
		if ($slider)
			$slider.slider('destroy');
		else
			$slider = $('#slider');
		setvals();
		$slider.slider({
			min: 0,
			max: len,
			step: 1,
			disabled: values.length <= 0 || values[0] == '',
			values: values,
			start: function(event, ui) {
				curval = ui.value;
			},
			stop: function(event, ui) {
				curval = ui.value;
				sortmarks();
				refreshtimes();
			},
			slide: function(event, ui) {
				var marks = '';
				for (var i = 0; i < ui.values.length; ++i)
					marks += ui.values[i] + ' ';
				$('#bookmarks').val(marks.trim());
				setvals();
			}
		});
		refreshtimes();
		
		/* slider values are strings */
		var curvalstr = "" + curval;
		if (!values.includes(curvalstr)) {
			/* try to map current selected bmk to new bmk */
			var ovalues = $slider.slider("option", "values");
			var nn = ovalues.indexOf(curvalstr);
			if (nn < 0) {
				curval = 0;
				regenthumbs('');
			} else {
				if (nn >= values.length)
				    nn = values.length - 1;
				if (nn >= 0) {
					regenthumbs(toTimeStr(curval = values[nn]));
				} else {
					curval = 0;
					regenthumbs('');
				}
			}
		}
	};

	$('#genthumbs').button({icons: {primary: "ui-icon-zoomin"}, disabled: true})
	    .on('click', function() {
		var start;
		var incr = -1;
		var last;
		$(this)
		    .button('disable')
		    .button('option', 'icon', 'ui-icon-refresh');
		$('img.bmp').each(function(i) {
			if (start === undefined) {
				start = $(this).attr('data-pos') | 0;
			} else {
				last = $(this).attr('data-pos') | 0;
			}
			incr++;
			$(this).attr('src', '/img/generating.png');
		});
		$('#thumbs').show();

		incr = (last - start) / incr;

		$.get('/browse/thumbnail/mkrange.jim', {
			'file': file,
			's':    start+curval,
			'e':    last+curval,
			'i':    incr
		}, function() {
			$('img.bmp').each(function(i) {
				/* cast to "int" */
				var pos = $(this).attr('data-pos')|0;
				$(this).attr('src',
				    '/browse/thumbnail/fetch.jim?' +
				    'file=' + encodeURIComponent(file) +
				    '&pos=' + (curval+pos).toFixed(1));
			});
			$('#genthumbs').button('option', 'icon', 'ui-icon-zoomin');
		});

	});

	draw_slider();

	$('#addbmark').button({icons: {primary: "ui-icon-plus"}, text: false})
	    .on('click', function() {
		$('#bookmarks').val('0 ' + $('#bookmarks').val());
		curval = 0;
		draw_slider();
	});

	$('#delbmark').button({icons: {primary: "ui-icon-minus"}, text: false})
	    .on('click', function() {
		var cur = $('#bookmarks').val();
		cur = cur.replace(
		    new RegExp('(^| )' + curval + '( |$)', ''), ' ').trim();
		$('#bookmarks').val(cur);
		draw_slider();
	});

	$('#save').button({icons: {primary: "ui-icon-disk"}})
	    .on('click', function() {
			$.post('save.jim', {
				file: file,
				bookmarks: $('#bookmarks').val()
			}, function(data) {
				$('#results').html(data)
					.slideDown('slow').delay(5000).slideUp('slow');
			});
	});

	$('#back').button({icons: {primary: "ui-icon-arrowreturnthick-1-w"}})
	    .on('click', function() {
			window.location = '/go/browse?dir=' + encodeURIComponent(dir);
	});

	$('#crop').button({icons: {primary: "ui-icon-arrowreturnthick-1-e"}})
	    .on('click', function() {
			window.location = 
				window.location.href.replace('/bookmarks/?','/crop/crop.jim?');
	});

	$('#update').button()
	    .on('click', draw_slider);

	$('#slider')
	    .on('slidechange', function(evt, ui) {
		var tstr = toTimeStr(curval);
		if (tstr != $('#curbmk').html())
			regenthumbs(tstr);
	});
});
