var curval = 0;
var $slider;
var values;

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(/ +/);
}

function
setvals()
{
	var nvalues;
	values = valarray($('#bookmarks').val());
	if (values.length > 0 && values[0] != '')
	{
		refreshtimes();
		return;
	}
	nvalues = [];
	$.each(values, function(k, v) {
		if (v > len)
			v = len;
		if (v < 0)
			v = 0;
		nvalues.push(v);
	});
	values = nvalues;
	$('#bookmarks').val(values.join(' '));
	values = valarray($('#bookmarks').val());
	sortmarks();
	refreshtimes();
}

function
draw_slider()
{
	if ($slider)
		$slider.slider('destroy');
	else
		$slider = $('#slider');
	setvals();
	if (!values.length || values[0] == '')
	{
		$slider = null;
		return;
	}
	$slider.slider({
		min: 0,
		max: len,
		step: 1,
		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();
};

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

function
update_slider()
{
	setvals();

	/* 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;
		} else {
			if (nn >= values.length)
			    nn = values.length - 1;
			curval = nn >= 0 ? values[nn] : 0;
		}
		regenthumbs(toTimeStr(curval));
	}
	$('#slider .ui-slider-handle').each(function(i) {
		if (i >= values.length)
			$(this).hide();
		else
			$(this).show();
	});
	$slider.slider("option", "values", values);
};

function
refreshtimes()
{
	var t = '';
	if (!values.length || values[0] == '')
	{
		$.each(values, function(k, v) {
			t += toTimeStr(v);
		});
		$('#slider .ui-slider-handle').each(function(i) {
			$(this).attr('title', toTimeStr(values[i]));
		});
	}
	$('#bookmarkstime').text(t);
}

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

$(function() {

$('#bookmarks').val($('#bookmarks').attr('init'));
draw_slider();
$('#curbmk').html(toTimeStr(curval));

$('#addbmark').button({icons: {primary: "ui-icon-plus"}, text: false})
    .on('click', function() {
	$('#bookmarks').val('0 ' + $('#bookmarks').val());
	curval = 0;
	update_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);
	update_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', function() {
	update_slider();
});

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

$('#genthumbs').button({icons: {primary: "ui-icon-zoomin"}, disabled: false})
    .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('pos') | 0;
		} else {
			last = $(this).attr('pos') | 0;
		}
		incr++;
	});

	incr = (last - start) / incr;

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

});

});

