var is_moving = false;
var move_start = 0;
var last_distance = 1;
var move_now = 0;
var distance = 1;
var loading = null;
var graph = null;
var img_array = new Array();
var start_index = 2;
var current_index = 2;
var THRESHOLD = 2;
var STEP = 4;

function setUp(){
	loading = document.getElementById('loading');
	graph = document.getElementById('graph');
	
	for (var i = 0; i < 360 / STEP; i++){
		loading.style.width = (i) + "px";
		var img = new Image(640, 480);
		img.src = make_image_name(i * STEP);
		img_array[i] = img;		
	}
	
	loading.style.width = "";

	graph.onmousedown = graph_mousedown;
	window.onmousemove = graph_mousemove;				
	window.onmouseup = window_mouseup;
	window.onkeypress = window_keypress;
	//window.setTimeout(auto_rotate, 10);
	
	graph.className = "";
}

function graph_mousedown(e){
	is_moving = true;
	move_start = e.pageX;
	last_distance = 0;
	return false;
}

function graph_mousemove(e){
	if (is_moving){
		last_distance = move_now - e.pageX;				
		move_now = e.pageX;
		distance = move_start - move_now;					
		current_index = move_start_by(distance);
		if (current_index < 0) current_index += (360 / STEP);

		update_graph(current_index);	
	}
}

function window_keypress(e){
	console.log(e.keyCode);
	if(!is_moving){
		if (e.keyCode == 37){
			last_distance = 0;			
			start_index = move_start_by(THRESHOLD);
			update_graph(start_index);											
		}
		else {
			last_distance = 0;
			start_index = move_start_by(-THRESHOLD);
			update_graph(start_index);											
		}
	}
}

function move_start_by(dist){
	return (start_index + Math.round(dist / THRESHOLD)) % (360 / STEP);				
}

function window_mouseup(e){
	start_index = current_index;
	//console.log(current_index);
	is_moving = false;
	window.setTimeout(auto_rotate, 10);					
}

function make_image_name(index){
	if (index < 0 || index > 358){
		window.alert('invalid index: ' + index);
		return "./images/Bookmark-all.txt-002.gif.bmp";
	}
	var padded_number = "" + index;
	while(padded_number.length < 3){
		padded_number = "0" + padded_number;
	}
	var image_name = "./images/" + gesture_name + "/" + gesture_name + "-all.txt-" + padded_number + ".gif.bmp";
	return image_name;
}

function update_graph(index){
	//console.log(index);
	index = index % img_array.length;
	if (index < 0){
		index += img_array.length;
	}
	graph.src = img_array[index].src;				
}

function auto_rotate(){
	if (! is_moving && last_distance != 0){
		start_index = move_start_by(last_distance);
		update_graph(start_index);					
		window.setTimeout(auto_rotate, 100);					
	}
}

window.onload = setUp;
