var height = 0;
var story_title = "";
var current_chapter = parseInt(get_cookie("current_chapter"+document.location.pathname));
var scrollx = parseInt(get_cookie("scrollx"+document.location.pathname+current_chapter));
var column_width = parseInt(get_cookie("column_width"));
var font_size = parseInt(get_cookie("font_size"));
var forward_key = parseInt(get_cookie("forward_key"));
var back_key = parseInt(get_cookie("back_key"));
var previous_chapter_key = parseInt(get_cookie("previous_chapter_key"));
var next_chapter_key = parseInt(get_cookie("next_chapter_key"));
var reader_disabled = get_cookie("reader_disabled");
var total_columns = 0;
var resized = 0;
var chapter_text = null;

var key_table = Array("", "", "", "", "", "", "", "", "Backspace", "Tab", "", "", "", "Enter", "", "", "Shift", "Control", "Alt", "", "Caps Lock", "", "", "", "", "", "", "Esc", "", "", "", "", "Space", "Page Up", "Page Down", "End", "Home", "Left", "Up", "Right", "Down", "", "", "", "", "Insert", "Delete", "", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "", "", "", "", "", "", "", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

var progress_bar = new Image();
progress_bar.src = "stories/ajax-loader.gif";

function write_sidebar() {
	$("#sidebar").html('<ul><li id="next" class="hidden-nav"><a><div>Forward</div></a></li><li id="previous" class="hidden-nav"><a><div>Back</div></a></li><li id="next_chapter"><a href="javascript:change_chapter(1);"><div>Next chapter</div></a></li><li id="previous_chapter"><a href="javascript:change_chapter(-1);"><div>Previous chapter</div></a></li><li id="toc"><a href="javascript:change_chapter(\'toc\');"><div>Table of contents</div></a></li><li><a href="javascript:settings();"><div>Settings</div></a></li><li><a href="javascript:disablereader();"><div>Disable reader</div></a></li><li><a href="javascript:show_comments();"><div>Comments</div></a></li><li><a href="/"><div>Main page</div></a></li></ul>');
	if (current_chapter >= max_chapters) $("#next_chapter").addClass("hidden-nav");
	if (current_chapter == 1) $("#previous_chapter").addClass("hidden-nav");
	if (max_chapters == 1) $("#toc").addClass("hidden-nav");
	
	$("#next").click(function() {
		if (!$(this).hasClass("hidden-nav")) scroll(1);
	});
	
	$("#previous").click(function() {
		if (!$(this).hasClass("hidden-nav")) scroll(-1);
	});
	
	$("li").click(function() {
		$(this).fadeOut(50).fadeIn(50);
	});
}

function write_change_column(direction, colWidth, colHeight, colSpace, position) {
	real_width = colWidth;
	
	if (direction > 0) phrase = "Next";
	else phrase = "Previous";
	
	column = '<a href="javascript:change_chapter(' + direction + ');">';
	column += '<div id="divColumn' + position + '" style="position: absolute; top: 0px; left: ' + (position*(colWidth + colSpace) + colSpace) + 'px; width: ' + colWidth + 'px; height: ' + colHeight + 'px; text-align:center;" class="nav_column">';
	column += '<div style="padding-top: ' + ((height/2)-17) + 'px;">' + phrase + ' chapter</div>';
	column += '</div></a>';
	
	return column;
}

function convertColumns(settings){
	var colWidth = column_width;
	var colHeight = height;
	var colSpace = 20;
	var vSplit = "";
	var vText = chapter_text;
	current_url = document.location.href.replace(document.location.hash, "");
	current_url = current_url.substring(0, current_url.lastIndexOf("/")+1);
	
	$(vText).find(".resize").each(function(i) {
		$(this).attr("src", url + $(this).attr("src").replace(current_url, ""));
		$(this).height(height);
	});
	
	var vColumns = Columns.splitText(vText.html(), colWidth, colHeight);
		
	if (current_chapter > 1 && !settings) {
		 vSplit += write_change_column(-1, colWidth, colHeight, colSpace, 0);
		 mod = 1;
	} else mod = 0;
	
	if (!settings) temp_columns = vColumns.length+mod;
	else temp_columns = 2;
	
	for (var i = 0+mod; i < temp_columns; i ++){
		vSplit += '<div id="divColumn' + i + '" style="position: absolute; top: 0px; left: ' + (i*(colWidth + colSpace) + colSpace) + 'px; width: ' + colWidth + 'px; height: ' + colHeight + 'px; text-align:left">';
		vSplit += vColumns[i-mod];
		vSplit += '</div>';
	}
	
	if (current_chapter < max_chapters && !settings) {
		vSplit += write_change_column(1, colWidth, colHeight, colSpace, vColumns.length+mod);
		mod++;
	}

	$("#columns").html(vSplit);
	total_columns = vColumns.length+mod;
	
	if (scrollx) {
		page = Math.floor(scrollx/height);
		$("#columns").css({ "right": 20+page*(column_width+20)+"px" });
	}
	else $("#columns").css({ "right": "20px" });
	
	check_navigation();
	
	if (current_chapter == "toc") {
		$("#columns a").each(function(i) {
			href = $(this).attr("href");
			href = href.replace(current_url, "").replace(".html", "");
			$(this).attr("href","javascript:open_chapter(" + href + ");");
		});
	} else {
		chapter_title = "";
		if ($("#columns h3").length > 0) chapter_title = $("#columns h3").html();
		else if ($("#columns h2").length > 0) chapter_title = $("#columns h2").html();
		
		if (chapter_title && chapter_title != story_title) document.title = story_title + " | " + chapter_title;
		else document.title = story_title;
	}
	
	$(".resize").each(function(i) {
		if ($(this).width() > colWidth) {
			$(this).width(column_width);
			$(this).css({ "io": "auto" });
		}
	});
}

function get_height() {
	var height = Math.max($(window).height()-100, 100);
	$("#columns").height(height);
	return height;
}

function can_scroll(direction) {
	if (direction < 0) {
		if (scrollx < height) return false;
		else return true;
	} else {
		if (Math.floor(scrollx/height)*column_width+document.getElementById("columns").offsetWidth > total_columns*column_width) return false;
		else return true;
	}
}

function check_navigation() {
	scrollx = parseInt(document.location.hash.slice(1).split(",")[1]);
	if (isNaN(scrollx)) scrollx = 0;
	
	$("#previous").toggleClass("hidden-nav", !can_scroll(-1));
	$("#next").toggleClass("hidden-nav", !can_scroll(1));
}

function scroll(direction) {
	scrollx = parseInt(document.location.hash.slice(1).split(",")[1]);
	if (isNaN(scrollx)) scrollx = 0;
	
	set_cookie("scrollx"+document.location.pathname+current_chapter,scrollx+direction*height,365);
	document.location.hash = current_chapter + "," + (scrollx+direction*height);
	
	page = Math.floor(scrollx/height);
	for (var i=0;i<total_columns;i++) {
		col = document.getElementById("divColumn" + i);
		if (i > page+20 || i < page-5) col.style.display = "none";
		else col.style.display = "block";
	}
	
	$("#columns").stop().animate({ "right": 20+((page+direction)*(column_width+20))+"px" });
	check_navigation();
}

$(document).ready(function() {
	if (window.location.search == "?=refresh") window.location.search = "";
	
	story_title = document.title;
	
	if (!current_chapter) current_chapter = "toc";
	if (!column_width) column_width = 240;
	if (!font_size) font_size = 16;
	else document.getElementById("container").style.fontSize = font_size;
	if (!forward_key) forward_key = 39;
	if (!back_key) back_key = 37;
	if (!previous_chapter_key) previous_chapter_key = 38;
	if (!next_chapter_key) next_chapter_key = 40; 
	
	if (document.location.hash) {
		chapter = parseInt(document.location.hash.slice(1).split(",")[0]);
		if (isNaN(chapter)) chapter = "toc";
	}
	else chapter = current_chapter;
	if (chapter == "toc" && max_chapters == 1) chapter = 1;
	
	height = get_height();
	$("#disqus_thread").css({display:"none", right:"-350px"});
	
	if (reader_disabled) show_primitive();
	else {
		$(window).bind("resize", function() {
			resized += Math.abs(height-get_height());
			if (resized > 50) window.location.search = "?=refresh";
		});
		$(document).bind("keydown", keyhandler);
		$("#wrapper").click(function() {
			$("#disqus_thread").animate({ "right": "-350px" }, "fast").hide();;
			$("#wrapper").animate({ "opacity": 1 });
		});
		open_chapter(chapter);
	}
});
	
function open_chapter(chapter) {
	$("#columns").html("<div style='padding-top:" + document.getElementById("columns").offsetHeight/2 +  "px; text-align: center; font-size: 200%;'><img src='/stories/ajax-loader.gif' /><br />Loading...</div>");
	
	$.get(url+chapter+".html", function(data) {
		chapter_text = $("#columns").clone();
		chapter_text.html(data);
		setTimeout(function() { convertColumns(false); }, 1000);
		if (document.location.hash) {
			scrollx = parseInt(document.location.hash.slice(1).split(",")[1]);
			document.location.hash = chapter + "," + scrollx;
		}
		else {
			scrollx = parseInt(get_cookie("scrollx"+document.location.pathname+current_chapter));
			if (!scrollx) scrollx = 0;
			document.location.hash = chapter + "," + scrollx;
		}
		
		write_sidebar();
		set_cookie("current_chapter"+document.location.pathname,current_chapter,365);
	});
	
	current_chapter = chapter;
}
	

function change_chapter(chapter) {
	if (chapter == "toc") open_chapter("toc");
	else open_chapter(current_chapter+chapter);
	document.location.hash = current_chapter + "," + 0;
	$("#columns").css({ "right": "20px" });
}

function set_forward_key() { document.settings.forward_key.value = key_table[document.settings.forward_key_value.value]; }
function set_back_key() { document.settings.back_key.value = key_table[document.settings.back_key_value.value]; }
function set_next_chapter_key() { document.settings.next_chapter_key.value = key_table[document.settings.next_chapter_key_value.value]; }
function set_previous_chapter_key() { document.settings.previous_chapter_key.value = key_table[document.settings.previous_chapter_key_value.value]; }

function get_key(e, form_value, func) {
	key = get_keycode(e);
	
	form_value.value = key;
	func();
	return false;
}

function settings() {
	chapter_text.html(lorem);
	convertColumns(true);
	$(document).unbind("keydown");
	
	page = '<div id="divColumnx" style="position: absolute; top: 0px; left: ' + (2*(column_width + 20) + 20) + 'px; width: ' + 150 + 'px; height: ' + height + 'px; text-align:left">';
	page = '<div id="divColumnx" style="position: absolute; top: 1em; right: 0px; width: ' + 150 + 'px; height: ' + height + 'px; text-align:left">';
	page += '<form name="settings">';
	page += 'Column width<br /><div id="slider"></div><input name="width" id="width" value="' + column_width + '" onchange="resize_columns();" /><div style="clear: both;"></div><br />';
	page += '<div class="input"><a href="javascript:embiggen(-2);" style="font-size: 200%;">-</a> ' + font_size + ' <a href="javascript:embiggen(2);" style="font-size: 200%;">+</a></div><div class="label">Font size</div><br />';
	
	page += '<br /><br /><br /><br />Remap keys:<br /><br />';
	page += '<div class="input"><input name="forward_key_value" type="hidden" value="' + forward_key + '" /><input name="forward_key" class="key_catcher" onkeydown="return get_key(event, document.settings.forward_key_value, set_forward_key);" /></div><div class="label">Forward</div><br />';
	page += '<div class="input"><input name="back_key_value" type="hidden" value="' + back_key + '" /><input name="back_key" class="key_catcher" onkeydown="return get_key(event, document.settings.back_key_value, set_back_key);" /></div><div class="label">Back</div><br />';
	page += '<div class="input"><input name="next_chapter_key_value" type="hidden" value="' + next_chapter_key + '" /><input name="next_chapter_key" class="key_catcher" onkeydown="return get_key(event, document.settings.next_chapter_key_value, set_next_chapter_key);" /></div><div class="label">Next chapter</div><br />';
	page += '<div class="input"><input name="previous_chapter_key_value" type="hidden" value="' + previous_chapter_key + '" /><input name="previous_chapter_key" class="key_catcher" onkeydown="return get_key(event, document.settings.previous_chapter_key_value, set_previous_chapter_key);" /></div><div class="label">Previous chapter</div><br /><br />';
	page += '<div class="input"><a href="javascript:save_settings();"><div class="save">Save</div></a></div>';
	page += '</form>';
	page += '</div>';
	
	$("#columns").css({ "right": "20px" });
	$("#columns").append(page);
	$("#slider").slider({ min: 100, max: 600, step: 20, value:column_width });
	$("#slider").bind('slidechange', function(event, ui) {
		column_width = ui.value;
		document.settings.width.value = column_width;
		settings();
	});
	
	set_forward_key();
	set_back_key();
	set_next_chapter_key();
	set_previous_chapter_key();
	
	$(".sidebar").hide();
}

function resize_columns() {
	column_width = parseInt(document.settings.width.value);
	settings();
}

function embiggen(size) {
	font_size += size;
	$("#container").css({ "font-size": font_size});
	settings();
}

function save_settings() {
	$(document).bind("keydown", keyhandler);
	
	forward_key = document.settings.forward_key_value.value;
	back_key = document.settings.back_key_value.value;
	next_chapter_key = document.settings.next_chapter_key_value.value;
	previous_chapter_key = document.settings.previous_chapter_key_value.value;
	column_width = parseInt(document.settings.width.value);
	
	set_cookie("column_width", column_width, 365);
	set_cookie("font_size", font_size, 365);
	set_cookie("forward_key", forward_key, 365);
	set_cookie("back_key", back_key, 365);
	set_cookie("next_chapter_key", next_chapter_key, 365);
	set_cookie("previous_chapter_key", previous_chapter_key, 365);
	
	open_chapter(current_chapter);
	$(".sidebar").show();
}

function get_keycode(e) {
	if(window.event) { // IE
    	return key = e.keyCode;
	} else if(e.which) { // Netscape/Firefox/Opera
		return key = e.which;
	} else return 0;
}

function keyhandler(e) {
    key = get_keycode(e);
	
	if (key == forward_key) if (can_scroll(1)) { 
		scroll(1); 
		$("#next").fadeOut(50).fadeIn(50); 
	}
	if (key == back_key) if (can_scroll(-1)) {
		 scroll(-1);
		 $("#previous").fadeOut(50).fadeIn(50);
	}
	
	if (key == previous_chapter_key) if (current_chapter > 1) change_chapter(-1);
	if (key == next_chapter_key) if (current_chapter < max_chapters) change_chapter(1);
	
	if (key == forward_key || key == back_key || key == previous_chapter_key || key == next_chapter_key) {
		if (e.preventDefault) e.preventDefault();
		e.returnValue = false;
	}
}

function disablereader() {
	set_cookie("reader_disabled", "open", 365);
	window.location.search = "?=refresh";
}

function enablereader() {
	set_cookie("reader_disabled", "", 365);
	window.location.search = "?=refresh";
}

function show_primitive() {
	$("#wrapper").hide();
	$("body").append('<iframe src="' + url + 'toc.html" name="frame"></iframe>');
	$("body").append('<div style="position: absolute; top: 0; right: 0;"><a href="' + url + 'toc.html" target="frame">Table of contents</a> | <a href="javascript:enablereader();">Re-enable reader</a></div>');
}

function show_comments() {
	$("#wrapper").animate({ "opacity": 0.3 }, "fast");
	$("#disqus_thread").show().animate({ "right": 0 }, "fast");
}
