// update this when you make edits!
var version_scripts_story = 7

var isAutoSave = false;
var autosaveCounterId = 0;
var timeToSaveId = 0;
var autosavetime = 3000*60;
var saveAlertTime = 1000*60;
var critcountstarted = false;
var saving = false;
var issaved = true;


function ToggleAuthorNotes(isCheck) 
{
	if (isCheck && ($.cookie("hideauthornotes") == null || $.cookie("hideauthornotes")  == "") ) return;
	var o = $('.authornoteshead');
	if ($('.authornotes').is(":visible")) {
		$('.authornotes').hide();
		o.addClass("link");
		o.html(o.html().replace("Author Notes", "Click to view Author Notes"));
		$.cookie("hideauthornotes", "1", {expires: 365})
	} else {
		$('.authornotes').show();
		o.removeClass("link");
		o.html(o.html().replace("Click to view ", ""));
		$.cookie("hideauthornotes", null)
	}
}

function hoverStory(e, id, isit)
{
	var t = document.getElementById('g_tt');
	if (t == null) return;
	if (!isit) {
		ttHideTimer = setTimeout('HideGlobalTooltip()', 1000);
		clearTimeout(hoverTimer);
		hoverTimer = 0;
	} else {
		SetTooltipPosition(e);
		hoverWhat = e;
		clearTimeout(ttHideTimer);
		ttHideTimer = 0;

		if (e != null) {
			hoverUrl = 'worker_queue.asp?action=info&id='+id;
			hoverTimer = setTimeout("DoFetchStory()", 300);
		}
	}
}

function DoFetchStory()
{
	var t = document.getElementById('g_tt');
	if (t == null) return;
	//alert(hoverUrl);
	pollServer(hoverUrl, 'StoryInfoResponse');
}

function StoryInfoResponse()
{
	//alert(servResponse);
	if (hoverTimer == 0)
		return;
	if (servResponse == '-1') {
		alert("Unable to get a sane response from server...");
		return;
	} else {
		var t = document.getElementById('g_tt');
		t.style.display = "block";
		t.style.width = "400px";
		t.innerHTML = unescape(servResponse);
	}
}
	
function ToggleAutoSave()
{
	var v = document.getElementById('autosaveicon');
	critcountstarted = false;
	if (isAutoSave) {
		v.src = 'images/autosave_up.gif';
		clearTimeout(autosaveCounterId);
		timeToSaveId = setTimeout("TimeToSave()", saveAlertTime);
		setMultipleCookie("flags", "autosaveoff", "1");
		document.getElementById('saved').innerHTML = '<b><font color=red>Autosaving is disabled&nbsp;&nbsp;</font></b>';
	} else {
		v.src = 'images/autosave_down.gif';
		clearTimeout(timeToSaveId);
		StartAutoSaveCounter();
		setMultipleCookie("flags", "autosaveoff", "");
		alertAutoSave();
	}
	isAutoSave = !isAutoSave;
}


/* inline crits */

function ChangeCritType(url)
{
	if (document.themessage == null)
		document.location.href = url;
	else {
		if ($("#critid").val() > 0) {
			alert(schemeChangeTextNo);
		} else {
			var agree = confirm(schemeChangeText);
			if (agree)
				document.location.href = url;
		}
	}
}

function ToggleInlineComments(doit)
{
	for (var i = 0; i < 100; i++) {
		var v = document.getElementById('c_'+i);
		if (v == null) continue;
		if (doit)
			v.style.display = "block";
		else
			v.style.display = "none";			
	}
	var fl = "1";
	if (doit) fl = "";
	setMultipleCookie("flags", "inlineclosed", fl);
	story = "";
	pages = [];
}
function ToggleInlineUncommented(doit)
{
	var tags = document.getElementsByTagName("P");
//	alert($(".sti").is(":visible"));
//	$("p.sti").toggle();
//	return;
	var fl = "";
	for (i = 0; i < tags.length; i++) {
		if (tags[i].className == 'sti') {
			if (tags[i].style.display == "none") {
				tags[i].style.display = "block";
				fl = ""
			} else {
				tags[i].style.display = "none";
				fl = "1"
			}
		}
	}
	setMultipleCookie("flags", "inlineuncommented", fl);
	story = "";
	pages = [];
}

function ToggleComment(what, id)
{
	var v = document.getElementById('c_'+id);
	if (v.style.display == 'block')
		v.style.display = 'none'
	else
		v.style.display = 'block'
}

var count = 0;

function SubmitCrit()
{
 	dontbugme = true;
	SubmitText();
	var storyFld = document.getElementById('storyText');
	document.themessage.submit();
}

function SubmitInlineCrit()
{
	WriteNotify('<img src="images/loader.gif" width=24 align=absmiddle> Saving critique...');
	SubmitText();
	setTimeout("TrySubmitInlineCrit(0)", 100);
}

function TrySubmitInlineCrit(n)
{
	var gotPending = false;
	var numPending = 0;
	for (id in pendingSaves) {
		gotPending = true;
		numPending += 1;
	}
	var gotProgress = false;
	var numProgress = 0;
	for (id in progressSaves) {
		gotProgress = true;
		numProgress += 1
	}
	if (gotPending || gotProgress) {
		if (n > 0)
			$("#saved").html("Busy saving crit. Retrying "+n)
		if (gotPending) ProcessPendingSaves();
		if (n < 10)
			setTimeout("TrySubmitInlineCrit("+(n+1)+")", (n+1)*1000);
		else
			WriteNotify("Unable to save crit. Please try again in a bit");
	} else {
		var storyID = $("#storyid").val();
		var anon = ""
		var noob = ""
		if ($("#nl").is(":checked")) anon = "&anon=1"
		if ($("#noob").is(":checked")) noob = "&noob=1"
		
		
		Goto("critstory.asp?action=confirm&storyid="+storyID+anon+noob);
	}
}

var currentParagraph = null;
var inlineComments = [];
function im(what, doit)
{
	if (IsEmptyParagraph($(what).html())) return;
	if (doit) {
		$(what).addClass("pinnedComment")
	} else {
		$(what).removeClass("pinnedComment")
	}
}

function FocusInlineEditBox()
{
	var v = document.getElementById('comm')
	v.focus();
}

// opens the inline crit window for paragraphs
function OpenTextWindow(what)
{
	StopSpellCheck();

	currentParagraph = what;

	var id = currentParagraph.id
	var txt = inlineComments[id.replace("pp_", "p_")];
	if (txt == undefined) txt = "";
	$("#comm").val(txt);

	var v = document.getElementById('comm');
	var vpar = document.getElementById('commParent');
	var txtwnd = document.getElementById('txtwnd');
	spellAreaName = v.id;
		
	if ($("#readingviewcontainer").is(":visible")) {
		var c = $("#txtwnd");
		c.css("position", "absolute");
		c.css("width", $(what).width()+4);
		c.css("left", $(what).position().left);
		c.css("top", $(what).position().top+$(what).height()+4);

		c.insertAfter("#"+id);
		c.show();
		$("#comm").show();

		$(what).removeClass("sti");
		$(what).addClass("sti_sel");
	} else {
		var c = $("#txtwnd");
		c.css("position", "relative");
		c.css("width", "100%");
		c.css("left", 0);
		c.css("top", 0);

		if (what.nextSibling) {
			nextSib = what.nextSibling;
			var par = what.parentNode;
			while (par.tagName != "DIV" && par != null)
				par = par.parentNode;
			if (par == null) par = what.parentNode;
			// don't know why this sometimes doesn't work :-|
			try {
				par.insertBefore(txtwnd, what.nextSibling);
			} catch (a) {
				what.appendChild(txtwnd);
			}
			if (nextSib.className == "comment") {
				what.parentNode.removeChild(nextSib)
			}
		}
	}
	$('#commParent').show();
	$('#txtwnd').show();
	setTimeout('FocusInlineEditBox()', 100);
}

function RemoveSection(id)
{
	var c = document.themessage.crit.value;
	var mrk = '--BEGIN_'+id;
	var idx = c.indexOf(mrk);
	if (idx >= 0) {
		var idx2 = c.indexOf('--END', idx) + 5;
		c = c.substr(0, idx) + c.substr(idx2, c.length-idx2);
		document.themessage.crit.value = c;
	}
}

function IsEmptyParagraph(txt)
{
	txt = txt.replace(new RegExp(" ", "g"), "");
	txt = txt.replace(new RegExp("\n", "g"), "");
	txt = txt.replace(new RegExp("\r", "g"), "");
	txt = txt.replace(new RegExp("\t", "g"), "");
	return (txt == "")
}

var currPos = null;
function icc(what)
{
	if (IsEmptyParagraph($(what).html())) return;

	if (isSpellChecking) {
		StopSpellCheck();
		return;
	}
	if (currentParagraph != null) {
		var c = currentParagraph.id;
		if (c == what.id) {
			return;
		}
		SubmitText();

	}
	OpenTextWindow(what);
	$(what).addClass("sti_sel");
	DoShowInProgressComments();
	var cls = "inlinekeyboardpos";
	if (!IsReadingView()) cls += "_classic"
	var clsb = cls+"back";
	$("."+cls).removeClass(cls);
	$("."+clsb).removeClass(clsb);
	
	var c = what.id.split('_')[1];
	currPos = parseInt(c, 10)
	var currPosFormatted = CurrPosFormatted();
	var id = "p_"+currPosFormatted;
	if (IsReadingView()) id = "p" + id;
	obj = $("#"+id);
	obj.addClass(cls);
	obj.addClass(clsb);
	//alert("I am here: "+what.id+" ("+currPos+")and here"+id);
}

function IsKeyboardNavigateLegal(e)
{
	var element;
	if(e.target) element=e.target;
	else if(e.srcElement) element=e.srcElement;
	if(element.nodeType==3) element=element.parentNode;
	if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') 
		return false;
	return true;
}

function CurrPosFormatted()
{
	currPosFormatted = ""
	if (currPos < 10) currPosFormatted = "00"+currPos;
	else if (currPos < 100) currPosFormatted = "0"+currPos;
	else if (currPos < 1000) currPosFormatted = currPos;
	return currPosFormatted; 
}
function KeyboardNavigateInline(e, d)
{
	if (!IsKeyboardNavigateLegal(e)) return;
	var origCurrPos = currPos;
	if (currPos == null) {
		var c = $(".stic").attr("id");
		var c = c.split('_')[1];
		currPos = parseInt(c, 10)
	} else
		currPos = currPos + d;
	var obj = null;
	if (currPos < 1) currPos = 1;

	while (1) {
		var currPosFormatted = CurrPosFormatted();

		var id = "p_"+currPosFormatted;
		if (IsReadingView()) id = "p" + id;
		obj = $("#"+id);
		if (obj.attr("id") != undefined && IsEmptyParagraph(obj.html()))
			currPos += d;
		else
			break
	}

	if (obj.attr("id") == undefined) {
		currPos = origCurrPos;
		return;
	}
	var cls = "inlinekeyboardpos";
	if (!IsReadingView()) cls += "_classic"
	var clsb = cls+"back";

	$("."+cls).removeClass(cls);
	$("."+clsb).removeClass(clsb);
	obj.addClass(cls);
	obj.addClass(clsb);

	if (!IsReadingView() || isReadingScroll) {
		var docViewTop = $(window).scrollTop();
		var docViewBottom = docViewTop + $(window).height();
		var elemTop = obj.offset().top;
		if (elemTop + 100 > docViewBottom || elemTop - 20 < docViewTop)
			$(window).scrollTop(elemTop-50);
	}
	
}

function KeyboardNavigateInlineDown(e)
{
	KeyboardNavigateInline(e, 1);
}

function KeyboardNavigateInlineUp(e)
{
	KeyboardNavigateInline(e, -1);
}

function KeyboardNavigateReadingViewLeft(e)
{
	if (!IsKeyboardNavigateLegal(e)) return;
	NavigatePage(-1);
}

function KeyboardNavigateReadingViewRight(e)
{
	if (!IsKeyboardNavigateLegal(e)) return;
	NavigatePage(1);
}

function KeyboardNavigateInlineSelect(e)
{
	if (!IsKeyboardNavigateLegal(e)) return;
	var p = CurrPosFormatted();
	var id = 'p_'+p;
	if (IsReadingView())
		id = "p"+id
	icc(document.getElementById(id));
}
function SubmitKeyboard(textarea, form)
{
	if (textarea.id == "comm") {
		SubmitText();
		ProcessPendingSaves();
	}
}

var pendingSaves = [];
var progressSaves = [];

function PostInlineComment(id)
{
	pendingSaves[id] = 1;
}

function AbandonCritInProgress()
{
	var critID = $("#critid").val();
	if (critID == 0) {
		 alert('You do not have a saved crit')
		 return;
	}
	if (confirm('Are you sure you want to permanently delete this critique in progress?')) {
		Goto('mycrits.asp?deleteCrit='+critID);
	}
}

function ProcessPendingSaves()
{
	var localPendingSaves = pendingSaves;
	var err = null;
	var storyID = $("#storyid").val();
	var critID = $("#critid").val();
	var n = "";
	var paragraphs = [];
	var ids = [];
	for (id in localPendingSaves) {
		progressSaves[id] = 1;
		paragraphs[paragraphs.length] = encodeURIComponent(inlineComments[id.replace("pp_", "p_")]);
		ids[ids.length] = id
		delete pendingSaves[id];
	}
	if (ids.length > 0) {
		var savestring = 'Saving '+ids.length+' paragraphs...'
		if (ids.length == 1)
			savestring = 'Saving paragraph...'
		$("#saved").html('<img src="images/loader2.gif" height=10 align=absmiddle> '+savestring);
		n += id + ", ";
		var txt = encodeURIComponent(inlineComments[id.replace("pp_", "p_")]);
		var ident = $("#ident").val();
		var dict = {};
		dict["storyid"] = storyID;
		dict["critid"] = critID;
		dict["ident"] = ident;
		dict["num"] = ids.length;
		dict["action"] = "savepara";
		for (var i = 0; i < ids.length; i++) {
			dict["txt_"+i] = paragraphs[i];
			dict["paragraph_"+i] = ids[i];
		}
		$.ajax({
		  type: 'POST',
		  data: dict,
		  contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
		  url: "worker_saveinline.asp",
		  success: function(data){
		     if (data == "loggedout") {
			HandleExpiredSession('');
		     } else {
		     	var isOk = (data.substr(0, 2) == "ok");
		     	//var ids = this.context;
			for (var i = 0; i < ids.length; i++) {
				var thisID = ids[i];
				delete progressSaves[ids[i]];
				if (thisID == "p_000") thisID = "comment";
				if (thisID == "p_999") thisID = "comment2";
				if (isOk) {
					$("#"+thisID).removeClass("sti_pending");
					$("#p"+thisID).removeClass("sti_pending");
					SetPendingSaveIcon();
				} else {
					pendingSaves[ids[i]] = 1;
				}					
			}
		     	if (isOk) {

		     		var lst = data.split("\\n")
		     		var t = lst[2];
		     		
		     		var critID = lst[1];
		     		$("#critid").val(critID);
		     		if (critID == "0")
		     			t = "";
		     		t = "<nobr>" + t + "</nobr>"
		     		$("#saved").html(t);
		     		$("#comminfo").html(t);
		     		WriteNotify("");
			} else {
				var t = "<font color=red><b>"+data+"</b></font>";
				$("#saved").html(t);
				WriteNotify(t);
			}
		     }
		   },
		  error: function(data, s, e){
		     err = s + ' ' + e;
		     //alert(err);
		     	var ids = this.context;
			for (var i = 0; i < ids.length; i++) {	
			     var thisID = ids[i];
			     delete progressSaves[thisID];
			     pendingSaves[thisID] = 1;
		        }
		     WriteNotify("<font color=red><b>Error saving critique!</b></font>");
		    }
		});
	}
	setTimeout('DoShowInProgressComments()', 1000);
}


function SubmitText()
{
	$("#txtwnd").hide();

	$("#txtwnd").insertAfter("#readingviewcontainer");
	
	$(".submitcomment").removeClass('butt2_over');
	$(".submitcomment").addClass('butt2');
	if (currentParagraph == null) {
		return;
	}
	var id = currentParagraph.id
	oldComment = inlineComments[id.replace("pp_", "p_")];
	if (oldComment == undefined)
		oldComment = "";
	var txt = $("#comm").val()
	if (txt == oldComment) {
		//alert('no change');
	} else {
		inlineComments[id.replace("pp_", "p_")] = txt;
		// submit to server
		$(currentParagraph).addClass("sti_pending");
		PostInlineComment(id);
	}
	if (txt == "") {
		$(currentParagraph).removeClass("sti_sel");
	}
	$("#comm").val("")
	$("#commParent").hide();
	currentParagraph = null;
	DoShowInProgressComments();
}

function ToggleShowInProgressComments()
{
	var v = $.cookie("showprogressinlinecomments");
	if (v == '1')
		v = '';
	else
		v = '1';
	$.cookie("showprogressinlinecomments", v, {expires: 365})
	DoShowInProgressComments();
}

function DoShowInProgressComments()
{
	$('.allcomments').remove();
	var c = $.cookie("showprogressinlinecomments");
	if (c != '' && c != null) {
		for (id in inlineComments) {
			curr = null;
			if (currentParagraph != null) {
				curr = currentParagraph.id;
			}
			if (id == curr) continue;
			var c = $('<div id="allcomment_'+id+'" class="comment allcomments"></div>');
			c.insertAfter("#"+id);
			c.html(inlineComments[id].replace(new RegExp("\n", "g"), "<br>"));
			c.bind("click",function(e){
				var id = $(this).attr("id");
				l = 11
				id = id.substring(l, id.length)
			      icc(document.getElementById(id));
			      e.stopPropagation();
			});
		}
	}

}

function AddInProgressComment(para, val)
{
	if (getCookie('showprogressinlinecomments') != '1')
		return;
	// put the text underneath the paragraph
	var td = document.createElement("DIV");
	td.className = "comment";
	//td.onClick = function(what) {icc(what.previousSibling);};

	td.colSpan = 5
	td.innerHTML = '<div style="color:gray; cursor:pointer;" onClick="icc(this.parentNode.previousSibling);">' + val.replace(new RegExp("\n", "g"), "<br>")  + '</div>';
	para.parentNode.insertBefore(td, para.nextSibling);
}

var theTop = 100;
var old = theTop;

var isReady = false; 

// story bookmarks
function moveBookIcon() {
	var v = document.getElementById('bookselalt');
	if (v == null) return;
	var py;
	var px = 0;
	var w = 200;
	if (window.innerHeight) {
		py = window.pageYOffset
		w = window.innerWidth;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		py = document.documentElement.scrollTop
		w = document.documentElement.clientWidth;
	} else if (document.body) {
		py = document.body.scrollTop
		w = document.body.clientWidth;
	}
	py += 100;
	if (py < theTop) py = theTop;
	else py += theTop;
	if (py == old && v != null) {
		v.style.top = py;
		px = 140;
		v.style.left = px;
		var vpreview = document.getElementById('senda');
		if (isIexplore && vpreview != null) {
			d = vpreview.getBoundingClientRect().top;
			if (d < 200)
				v.style.display = "none";
			else
				v.style.display = "inline";
		}
	}
	old = py;
	setTimeout('moveBookIcon()', 500);
}

function CloseDisclaimerTable()
{
	var now = new Date();
	now.setTime(now.getTime() + 4 * 24 * 60 * 60 * 1000);
	var element = document.getElementById('disclaimer');
	element.style.display = "none";
	setMultipleCookie("flags", "discClose", "1", now);
}
				
function OpenThisLayer(name)
{
	var element = document.getElementById(name)
	element.style.display = "";
}

function CloseThisLayer(name)
{
	var element = document.getElementById(name)
	element.style.display = "none";
}

function ToggleStory()
{
	var num = 50
	for (i=1; i<num+1; i+=1) {
	  var name = "t"+i
	  var element = document.getElementById(name)
	  if (element == null)
	  	break;
	  if (element.style.display != "")
		  OpenThisLayer(name);
	  else
	      CloseThisLayer(name);
	}
}
var colchange = false
function ToggleStoryColor()
{
	var num = 50
	for (i=1; i<num+1; i+=1) {
	  var name = "t"+i
	  var element = document.getElementById(name)
	  if (element == null)
	  	break;
	  if (colchange)
		  element.style.color = "#888888";
	  else
	      element.style.color = "#009900";
	}
	colchange = !colchange;
}
var size = ""
if (document.getElementById("t1") != null) {
	size = element.style.fontSize
}
function ToggleStorySize()
{
	var num = 50
	for (i=1; i<num+1; i+=1) {
	  var name = "t"+i
	  var element = document.getElementById(name)
	  if (element == null)
	  	break;
	  if (element.style.fontSize == size)
		  element.style.fontSize = "9px";
	  else
	      element.style.fontSize = size;
	}
}

function OverCred(e, id)
{

  clearTimeout(ttHideTimer);
  ttHideTimer = 0;
  SetTooltipPosition(e);
  s = 'worker_info.asp?action=storycredits&id='+id;

  if (e != null) {
    hoverUrl = s;
    hoverTimer = setTimeout("DoFetchInfo()", 500);
    hoverWidth = 100;
  }
}

function TimeToSave()
{
	timeToSaveId = 0;
//	var v = document.getElementById('Vista');
//	v.src = "images/skilabod_vistud_red.gif";

	SaveCritique('Saving...', true);
}

function StartCounter()
{
	issaved = false;
	isCritTextAdded = true;
	if (timeToSaveId == 0 && isAutoSave)
		timeToSaveId = setTimeout("TimeToSave()", saveAlertTime);
}

function OnCommentBlur(what)
{	
	var txt = $(what).val();
	if (id in inlineComments && inlineComments[id] == txt) {
	} else {
		CommentKeyUp(what);
	}
		
	ProcessPendingSaves();
}

function CommentKeyUp(what)
{
	if (!isReady) {
		alert("Still fetching crit. Please wait");
		return;
	}

	var which = $(what).attr("id");
	var txt = $(what).val();
	var id = null;
	if (which == "comm") {
		id = currentParagraph.id
		$(currentParagraph).addClass("sti_pending");
	} else if (which == "comment") {
		id = "p_000"
		$(what).addClass("sti_pending");
	} else if (which == "comment2") {
		id = "p_999"
		$(what).addClass("sti_pending");
	} else {
		alert("unknown textarea "+which);
	}
	id = id.replace("pp_", "p_");
	inlineComments[id] = txt;
	pendingSaves[id] = 1;
	SetPendingSaveIcon();
}

function SetPendingSaveIcon()
{
	var isit = false;
	for (id in pendingSaves) {
		isit = true;
		break
	}
	for (id in progressSaves) {
		isit = true;
		break
	}
	$("#pendingsave").show();
	if (isit) {
		src = "images/step_12.png"
		title = "Save pending..."
	} else {
		src = "images/check2_12.png"
		title = "Critique is up to date"
	}
	$("#pendingsave").attr("src", src);
	$("#pendingsave").attr("title", title);

}

function StartAutoSaveCounter()
{
	if (!critcountstarted) {
		// the first save is 10 seconds from now, then every 60
		setTimeout("SaveCritique('', true)", 5000);
		autosaveCounterId = setTimeout("AutoSaveCritique()", 10000);
		document.themessage.timeoutid.value = autosaveCounterId;
		critcountstarted = true;
	}
}

function MakeCritWndBigger()
{
	var c = document.getElementById('critwndcontainer');
	if (c != null) 
		c.style.width = "300";
	document.themessage.Text.style.width = "";
	
	var cols = document.themessage.Text.cols;
	var rows = document.themessage.Text.rows;
	if (cols < 130)
	document.themessage.Text.cols = cols + 10;
	if (rows < 40)
	document.themessage.Text.rows = rows + 5;
	SetSizeCookie('sz_c', document.themessage.Text.cols, document.themessage.Text.rows);
}

function MakeCritWndSmaller()
{
	var c = document.getElementById('critwndcontainer');
	if (c != null) 
		c.style.width = "300";
	document.themessage.Text.style.width = "";
	
	var cols = document.themessage.Text.cols;
	var rows = document.themessage.Text.rows;
	if (cols > 90)
		document.themessage.Text.cols = cols - 10;
	if (rows > 20)
		document.themessage.Text.rows = rows - 5;
	SetSizeCookie('sz_c', document.themessage.Text.cols, document.themessage.Text.rows);
}

function MakeCritWndReallyBig()
{
	var c = document.getElementById('critwndcontainer');
	if (c.style.width == "80%") {
		c.style.width = "600px";
		SetSizeCookie('sz_c', "", "");
	} else {
		c.style.width = "80%";
		SetSizeCookie('sz_c', "BIG", "BIG");
	}
	
}

function MoveToolbar(what, smallrows, largerows) {
	if (smallrows == null) {
		smallrows = 5;
	}
	if (largerows == null) {
		largerows = 16;
	}
	if (lostForm != null) {
		lostForm.rows = smallrows;
		lostForm.style.backgroundColor = "#F3F3F3";

	}
	what.rows = largerows;
	what.style.backgroundColor = "#FFFFFF";
	StopSpellCheck();
	spellAreaName = what.id;

	return
	
	var element = document.getElementById("toolbar");
	//formName.insertAdjacentElement( "afterEnd" , element );
	if (what.nextSibling)
		what.parentNode.insertBefore(element, what.nextSibling);
	else
		what.parentNode.appendChild(element);
	
	element.style.display = "block";
}

var b = false;
function MoveToolbarNoSize(what, smallrows, largerows) {
	var element = document.getElementById("toolbar");
	if (what.nextSibling)
		what.parentNode.insertBefore(element, what.nextSibling);
	else
		what.parentNode.appendChild(element);
	StopSpellCheck();
	spellAreaName = what.id;
	element.style.display = "block";
}

var novelLast = null;
function ToggleNovelSynopsis(id, chapter, isprev)
{
	var inf = document.getElementById('novelinfo');
	if (novelLast == 'synopsis'+isprev) {
		inf.innerHTML = '';
		inf.style.display = 'none';
		novelLast = null;
	} else {
		inf.innerHTML = 'Retrieving information...';
		novelLast = 'synopsis'+isprev;
		inf.style.display = 'block';
		url = 'worker_queue.asp?action=novelsynopsis&id='+id+'&num='+chapter+'&prev='+isprev;
		//alert(url);
		url = url.replace(" ", "%20")
		$("#novelinfo").load(url);

	}
}

function ToggleNovelDesc(id, ch, p)
{
	var inf = document.getElementById('novelinfo');
	if (novelLast == 'desc') {
		inf.innerHTML = '';
		inf.style.display = 'none';
		novelLast = null;
	} else {
		inf.innerHTML = 'Retrieving information...';
		novelLast = 'desc'
		inf.style.display = 'block';
		url = 'worker_queue.asp?action=noveldesc&id='+id+'&ch='+ch+'&p='+p;
		$("#novelinfo").load(url);
	}
}

function ToggleNovelCharacters(id, chapter)
{
	var inf = document.getElementById('novelinfo');
	if (novelLast == 'char') {
		inf.innerHTML = '';
		inf.style.display = 'none';
		novelLast = null;
	} else {
		inf.innerHTML = 'Retrieving information...';
		novelLast = 'char';
		inf.style.display = 'block';
		url = 'worker_queue.asp?action=novelcharacters&id='+id+'&num='+chapter;
		$("#novelinfo").load(url);
	}
}

// moves the "save" button so that it's always visible
var theTop = 100;
var old = theTop;
var savefailed = false;
var hidesavebuttonmoretimer = null;
// highlights the given element
function OverSaveIcon(what, doit)
{
	d = document.getElementById('saveicon_more');
	d2 = document.getElementById('saveicon2');
    if (doit) {
		d2.className = 'colbdr hdr_sel link'
		d.style.display = 'inline';
	} else {
		d2.className = 'colbdr or link'
		if (!savefailed)
			HideSaveButtonMore();
	}

}

function MoveSaveIcon() {
    // this assumes IE
    var v = document.getElementById('saveicon');
    if (v == null) return;
    var py;
    var px = 0;
    var w = 200;
    if (document.documentElement && document.documentElement.scrollTop) {
		py = document.documentElement.scrollTop;
		w = document.documentElement.clientWidth;
    } else if (document.body) {
		py = document.body.scrollTop;
		w = document.body.clientWidth;
    }

    py -= 100;
    if (py < theTop)
    	py = theTop;
    else
    	py += theTop;
    if (py == old && v != null) {
		v.style.top = py + 'px';
		px = 132;
		v.style.left = px + 'px';
		if (py > 500)
			v.style.display = "inline";
		else
			v.style.display = "none";
    }
    old = py;
    setTimeout('MoveSaveIcon()', 200);
}

function SaveCritique(txt, auto)
{
	try {
		if (saving) {
			txt = "<font color=red><b>SAVE FAILED! PLEASE TRY AGAIN!</b></font>"
			savefailed = true;
		}
		t = '<b>'+txt+'</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		document.getElementById('saved').innerHTML = t
		mr = document.getElementById('saveicon_more');
		if (mr != null) {
			mr.innerHTML = "<nobr><b>"+txt+"</b></nobr>"
			mr.style.display = 'inline';
		}
		saving = true;
		var oldAction = document.themessage.action;
		act = 'worker_savecrit.asp?'+document.themessage.qry.value+'&timeoutid='+document.themessage.timeoutid.value;
		if (auto)
			act += "&auto=1";
		document.themessage.action = act;
		document.themessage.target = 'worker';
		// for inline crits
		if (currentParagraph != null) {
			var v = document.getElementById('comm');
			if (v != null) {
				paraID = currentParagraph.id;
				//if (isNaN(paraID.replace("p_", ""))) {
				//	alert("Error in parsing paragraphID: " + paraID); 
				//}
				RemoveSection(paraID);
				if (v.value == '') {
				} else {
					var c = document.themessage.crit.value;
					c = c + '--BEGIN_'+paraID+':'+v.value+'--END';
					document.themessage.crit.value = c;
				}
			}
		}


		document.themessage.submit();

		document.themessage.action = oldAction;
		document.themessage.target = "_self";
	} catch (e) {
		alert('There was an unspecified error saving your critique. Please try again.\nThe error said: '+e);
	}
}

function HideSaveButtonMore()
{
	if (hidesavebuttonmoretimer == null)
		hidesavebuttonmoretimer = setTimeout('DoHideSaveButtonMore()', 3000);
}
function DoHideSaveButtonMore()
{
	mr = document.getElementById('saveicon_more')
	if (mr != null)
		mr.style.display = 'none';
	hidesavebuttonmoretimer = null;
}


function ToggleStoryBookmark(what, id, r)
{
	if (what.innerHTML.indexOf("<!--1-->") >= 0) {
		url = 'worker_queue.asp?action=deletebookmark&id='+id+'&isreminder='+r;
		$.get(url);
		txt = langStrings[4]
		if (r)
			txt = langStrings[5]
		what.innerHTML = '<!--0--><nobr><img src="images/bookmark_16.png" align=absmiddle> '+txt+'</nobr>';

	} else {
		url = 'worker_queue.asp?action=addbookmark&id='+id+'&location=0&isreminder='+r;
		$.get(url);
		txt = langStrings[3]
		if (r)
			txt = langStrings[6]
		what.innerHTML = '<!--1--><nobr><img src="images/bookmark_16.png" align=absmiddle> '+txt+'</nobr>';
	}
}

function GetStoryListEntry(arrID, arrTitleRaw, arrStatus, arrWhoCanCrit, arrIsHidden, arrIsAdult, arrDontWantCrits, arrNovelChapterNumber, arrNovelChapterPart, arrAuthor, status, hasCrit, userID, userLevel, arrStoryType)
{
	HasCritStyle = ' style="text-decoration: line-through;" title="You have critiqued this story"'
	StoryNotVisibleStyle = ' title="Story is not visible to you for some reason"'
	StoryHiddenStyle = ' title="Story has been hidden by the author"'
	StoryInQueueStyle = ' title="Story is still in the Queue and cannot be viewed until it comes up for review"'
	StoryArcStyle = ' title="Story has been archived. It may still be visible but you cannot crit it"'
	OnlyCrittersStyle = ' title="The writer only allows active participants to view his story"'
	OnlyCritsInMonthStyle = ' title="The writer only allows active participants to view his story"'
	OnlyExperiencedStyle = ' title="The writer only allows active participants to view his story"'
	OnlyActiveStyle = ' title="The writer only allows active participants to view his story"'

	var markers = getCookie('queuemarkers');
	markAdult = (markers.indexOf("adult") < 0);
	markProtect = (markers.indexOf("protect") < 0);
	markBookmarks = (markers.indexOf("bookmark") < 0);
	markNovels = (markers.indexOf("novels") < 0);

	storyIsHidden = true
	if ((arrStatus > 1 && !arrIsHidden) || (userLevel >= 8) || arrAuthor == userID)
		storyIsHidden = false

	bn = ""//MultipleCookieValue("StoryBookmark", ""&arrID)
	titleIcon = ''
	if (arrTitleRaw == "")
		arrTitleRaw = "(unnamed)"

	if (markProtect) {
		tt = "";
		switch (arrWhoCanCrit)
		{
		case 6:
			ic = "shield_green";
			tt = "Only members who have critiqued before can view this story"
			break;
		case 4:
			ic = "shield";
			tt = "Only members who have critiqued in the last month can view this story"
			break;
		case 8:
			ic = "shield_yellow";
			tt = "Only experienced members (who have critiqued at least 10 stories) can view this story"
			break;
		case 2:
			ic = "shield_red";
			tt = "Only very active members (who have critiqued 10 stories and in the last month) can view this story"
			break;
		}
		if (tt != "")
			titleIcon = '<img src="images/'+ic+'.png" hspace=1 height=12 align=absmiddle title="'+tt+'">'
	}

	if (arrStatus == 7 || arrStatus == 8)
		titleIcon += '<img src="images/data.png"" height=14 align=absmiddle title="Story has been archived">'

	extrastyle = ""

	theStyle = ""
	if (arrStatus == 2 && status != 2)
		theStyle = 'style="color:#0055AA; font-weight: bold;"'
	overStyle = ""
	if (hasCrit)
		overStyle = HasCritStyle

	storyWantsCrits = true
	myAge = 20

	//If me_nocrits AND Int(arrWhoCanCrit) = STORY_ACCESS_CRITTERS Then storyWantsCrits = False
	//If me_nocritsinmonth AND (Int(arrWhoCanCrit) = STORY_ACCESS_MONTHCRITTERS OR Int(arrWhoCanCrit) = STORY_ACCESS_ACTIVE) Then storyWantsCrits = False
	//If NOT me_overTenCrits AND (Int(arrWhoCanCrit) = STORY_ACCESS_ACTIVE OR Int(arrWhoCanCrit) = STORY_ACCESS_EXPERIENCED) Then storyWantsCrits = False
	//If GetUserLevel >= USR_SUPER Then storyWantsCrits = True
	//Dim txt : txt = ""
	txt = ''
	title = arrTitleRaw//GetStoryTitle(arrTitleRaw, arrNovelChapterNumber, arrNovelChapterPart, STORY_TITLE_LENGTH, False)

	ovr = ' onMouseOver="hoverStory(this, '+arrID+', true);" onMouseOut="hoverStory(this, '+arrID+', false);"'

	if (arrIsAdult > 1 && arrAuthor != userID) {
		txt += '<span title="Story contains adult content and is not visible to members below 18 years of age">' + title + '</span>'
		titleIcon += '<img hspace=1 height=12 src="images/forbidden_13.png" height=13 width=13 align=absmiddle>'
	} else if (!storyIsHidden) {
		if (arrIsAdult && markAdult)
			titleIcon += '<img src="images/sml_dvl_faint.gif" align=absmiddle title="Story contains material which might offend readers">'

		if (arrStatus == 7 || arrStatus == 8) {// archived
			txt += '<span'+StoryArcStyle+'>'+title+'</span>'
			txt = '<a '+StoryArcStyle+' style="color:#666688;" href="queue.asp?action=lookup&index='+arrID+'"> <span>'+title+'</span> </a>'
		} else if (storyWantsCrits)
			txt += '<a class=hoverlink '+theStyle+' href="queue.asp?action=lookup&index='+arrID+'"> <span'+ovr+' '+overStyle+'>'+title+'</span></a> '
		else
			txt += '"<span'+OnlyCrittersStyle+'>'+title+' </span>'
	} else if (arrIsHidden) {
		txt += '<span'+StoryHiddenStyle+'>'+title+' </span>'
	} else if (arrStatus == 1) { // in queue
		txt += '<span'+StoryInQueueStyle+'>'+title+' </span>'
	} else {
		txt += '<span'+StoryNotVisibleStyle+'>'+title+' </span>'
	}
	if (arrStatus == 0) { // rejects
		txt = '<del>' + txt + '<del>'
		titleIcon += '<img hspace=1 height=12 src="images/delstory.png" align=absmiddle title="This story is rejected">'
	}
	if (arrIsHidden) {
		if (arrStatus == 5) // deleted
			titleIcon += '<img hspace=1 height=12  src="images/delstory.png" align=absmiddle title="This story has been deleted by the author">'
		else if (arrStatus != 7 && arrStatus != 8) // archived
			titleIcon += '<img hspace=1 height=12  src="images/ghost_14.png" align=absmiddle title="This story has been hidden by the author">'
	}
	if (arrDontWantCrits)
		titleIcon += '<img hspace=1 height=12 src="images/lock2.png" align=absmiddle title="The author does not want any more critiques on this story">'
	if (arrNovelChapterNumber != '0' && markNovels)
		titleIcon += '<img hspace=1 height=12  src="images/novelicon.png" align=absmiddle title="This is a part of a novel">'
	if (arrStoryType == 2)
		titleIcon += '<img hspace=1 height=12  src="images/paperclip_16.png" align=absmiddle title="This is an Attachment story for a Full-Manuscript Crit">'
		
	c = getCookie('storybookmarks');
	if (markBookmarks && c.indexOf(';'+arrID+';') >= 0)
		txt = '<img class=link OnClick="RemoveBookmarkInQueue(this, '+arrID+');" hspace=1 height=12  src="images/bookmark_16.png" align=absmiddle title="'+langStrings[1]+'">' + txt
	if (titleIcon == "")
		titleIcon = '<img src="images/spc.gif" align=absmiddle width=1>'
	//txt += titleIcon
	//txt = '<table cellpadding=0 cellspacing=0 width="100%"><tr><td>' + txt + '</td><td align=right>' + titleIcon + '</td></tr></table>'
	txt += ' ' + titleIcon

	return txt
}

function RemoveBookmarkInQueue(what, id)
{
	if (confirm(langStrings[2])) {
		$.get('worker_queue.asp?action=deletebookmarkall&id='+id);
		what.style.display = 'none';
	}
}

function AddQueueDividerRow(qID, slotnum, numCrits)
{
	var tbl = document.getElementById('queue_'+qID);
	var tbody = tbl.getElementsByTagName("TBODY")[0];
	var row = document.createElement("TR");
	row.className = "er"
	if (tbl.childNodes[tbl.childNodes.length-1].className == "er")
		row.className = "or"

	//row.innerHTML = '<td colspan=5 height=10 style="border-bottom:1 px solid #000000;"><hr size=1></td><td colspan=1 class=tinytext align=center><a href="queue.asp?action=whocrit&slot='+slotnum+'"&queue='+qID+'"><b>'+numCrits+'</b></a></td>';
	var td = document.createElement("TD");
	td.className = "tdlst";
	td.colSpan = 5
	td.innerHTML = "<hr size=1>";
	row.appendChild(td);
	var td = document.createElement("TD");
	td.innerHTML = '<center><a href="queue.asp?action=whocrit&slot='+slotnum+'&queue='+qID+'"><b>'+numCrits+'</b></a></center>'
	row.appendChild(td);
	tbody.appendChild(row);
}

function AddQueueRow(qID, arrID, arrTitleRaw, arrStatus, arrWhoCanCrit, arrIsHidden, arrIsAdult, arrDontWantCrits, arrNovelChapterNumber, arrNovelChapterPart, arrAuthor, status, arrUserName, arrNumCrits, dt, arrNumWords, arrGenre, hasCrit, userID, userLevel, isStar, isOwe, isPeriod, arrAccess, arrStoryType, arrType)
{
	var tbl = document.getElementById('queue_'+qID);
	var tbody = tbl.getElementsByTagName("TBODY")[0];
	var row = document.createElement("TR");
	if (arrStoryType == 2)
		arrNumWords = "?"
	// Story link
	var tit = GetStoryListEntry(arrID, arrTitleRaw, arrStatus, arrWhoCanCrit, arrIsHidden, arrIsAdult, arrDontWantCrits, arrNovelChapterNumber, arrNovelChapterPart, arrAuthor, status, hasCrit, userID, 12, arrStoryType);

	// User link
	mr = ''
	if (parseInt(arrAccess) == 6)
		mr = ' class=usr_prem '
	else if (parseInt(arrAccess) == 7)
		mr = ' class=usr_gold '
	else if (parseInt(arrAccess) >= 8)
		mr = ' class=usr_sup '
	//alert(parseInt(arrAccess))
	var usr = '<a class=hoverlink OnMouseOver="HoverInfo(this, '+arrAuthor+', 1);" OnMouseOut="StopInfo(this);" href="members.asp?lookup='+arrAuthor+'"><span'+mr+'>'+arrUserName+'</span></a>'
	
	var markers = getCookie('queuemarkers');
	markBuddy = (markers.indexOf("buddy") < 0);
	markOwe = (markers.indexOf("owe") < 0);
	markStr = (markers.indexOf("starcritters") < 0);
	
	if (markOwe && isOwe)
		usr += ' <img src="images/handshake.png" title="Care to return the favor?" align=absmiddle>'
	if (markStr && isStar)
		usr += ' <img src="images/star.gif" title="This member is an outstanding critter" align=absmiddle>'
	c = getCookie('buddies');
	if (markBuddy && c.indexOf(';'+arrAuthor+';') >= 0)
		usr = usr + ' <img src="images/usr_buddy.gif" title="This member is your buddy" align=absmiddle>'

	var numCrits = arrNumCrits;
	if (numCrits == 0)
		numCrits = "<font color=red><b>0</b></font>"
	numCrits = "<center>" + numCrits + "</center>"
	
	var cols = getCookie('queuecolumns');
	var lst = [tit]
	if (cols.indexOf("Author") < 0) lst[lst.length] = usr
	if (status == 2 && isPeriod) {
		
	} else {
		if (cols.indexOf("Date") < 0) lst[lst.length] = dt
	}
	if (cols.indexOf("Words") < 0) lst[lst.length] = arrNumWords
	if (cols.indexOf("Genre") < 0) lst[lst.length] = arrGenre
	if (cols.indexOf("Type") < 0 && cols != "null") lst[lst.length] = arrType
	if (status != 1 || !isPeriod) {
		if (cols.indexOf("Crits") < 0) lst[lst.length] = numCrits
	}
	row.className = "er"
	if (tbody.childNodes[tbody.childNodes.length-1].className == "er")
		row.className = "or"
	for (i = 0 ; i < lst.length; i++) {
		var td = document.createElement("TD");
		td.className = "tdlst";
		td.innerHTML = "<nobr>" + lst[i] + "</nobr>";
		row.appendChild(td);
	}
	tbody.appendChild(row);
}

function CancelQueueSub(queueID, isPriv)
{
	if (confirm(langStrings[isPriv ? 8 : 7])) {
		Goto('customqueue.asp?action=cancelsubscription&id='+queueID);
	}
}

function BindInlineParagraphs()
{
    $(".stic").unbind();
    $(".stic").bind("mouseenter",function(){
      im(this, true);
    }).bind("mouseleave",function(){
      im(this, false);
    }).bind("click",function(e){
      icc(this);
      e.stopPropagation();
    });
    for (id in inlineComments) {
    	$("#p"+id).addClass("sti_sel");
    	$("#"+id).addClass("sti_sel");
    	
    	if (id == "p_000")
    		$("#comment").val(inlineComments[id]);
    	if (id == "p_999")
    		$("#comment2").val(inlineComments[id]);
    }

}

function WriteNotify(txt)
{
	if (txt != "")
		$('#notify').fadeIn();
	else
		$('#notify').hide();
	$('#notifyinner').html(txt);
}


function InlineCritReady()
{
	isReady = true;
	GetStoryTextForReadingView();
	BindInlineParagraphs();
	DoShowInProgressComments();
	
	if (parseInt($("#critid").val()) > 0)
		SetPendingSaveIcon();
}

// READING VIEW
var story = "";
var storyLength = 0;
var storyLower = "";
var endChar = null;
var startChar = 0;
var pages = []
var currPage = 0;
var isWorking = false;
var isReadingScroll = 0;
var readingFontSize = 12;
var readingFont = "Verdana";
var readingHeight = 660;
function ToggleReadingView(forceOn)
{
	if (forceOn) {
		$("#readingviewcontainer").show();
		$("#storytext").hide();

	} else {
		SubmitText();
		$("#readingviewcontainer").toggle();
		$("#storytext").toggle();
	}
	if (pages.length == 0) {
		var c = $.cookie("readingview");
		if (c != null && c != '') {
			c = c.split(",")
			readingHeight = parseInt(c[1]);
			isReadingScroll = parseInt(c[2]);
			readingFontSize = c[3];
			readingFont = c[4];
		}
		ResetReadingView();
		$(document).bind('keydown', 'h', KeyboardNavigateReadingViewLeft);
		$(document).bind('keydown', 'l', KeyboardNavigateReadingViewRight);
	}
	UpdateReadingViewCookie(forceOn);
	BindInlineParagraphs();
}

function ResetReadingViewConfig()
{
	$.cookie("readingview", null);
	readingHeight = 660;
	isReadingScroll = 0;
	ResetReadingView();
}

function IsReadingView()
{
	var ret = $('#readingviewcontainer').is(":visible");
	return ret;
}

function UpdateReadingViewCookie(forceOn)
{
	var isit = 0;
	if (forceOn || IsReadingView()) {
		isit = 1;
		$("#readingviewoptions").fadeIn();
		$("#readingviewoptstable").addClass("or colbdr");
		$("#readingviewoptstable").css("width", 680);
		$("#toggleallcomments").hide();
	} else {
		$("#readingviewoptions").fadeOut();
		$("#readingviewoptstable").removeClass("or colbdr");
		$("#readingviewoptstable").css("width", "100%");
		$("#toggleallcomments").show();
	}
	c = [isit, readingHeight, isReadingScroll, readingFontSize, readingFont];
	$.cookie("readingview", c, {expires: 365});
}

function ActivateReadingViewMaybe()
{
	if ($.cookie('readingview') != null && $.cookie('readingview') != '' && parseInt($.cookie('readingview').split(',')[0]) > 0) {
		ToggleReadingView(true)
	}
}

function countLines() {
    var divHeight = document.getElementById('content').offsetHeight;
    var lineHeight = parseInt(document.getElementById('content').style.lineHeight);
    var lines = divHeight / lineHeight;
    //alert("Lines: " + lines);
    return parseInt(lines);
}

function ParseText()
{
	UpdateReadingViewCookie();
	$('.page_nav').fadeOut();
	$('.page_num').fadeOut();
	isWorking = true;
	pages = [];
	startChar = 0;
	$('#loader').css("top", $('#content').offset().top);
	$('#loader').css("left", $('#content').offset().left);
	$('#loader').css("width", $('#content').width());
	$('#loader').css("height", $('.page_inner').css("height"));
	$('#loader').fadeIn();
	var c = document.getElementById('content');
	c.style.color = "white"
	$('#content').html("");
	l = readingHeight * 2 //number of characters to skip

	if (story == "") {
		GetStoryTextForReadingView();
	}
	if (story.length < l)
		l = story.length / 2;
	setTimeout('FillLines('+startChar+', '+l+')', 10);
}

function GetStoryTextForReadingView()
{
	var title = $("#storytitle").html();
	story = $("#story").html();
	if (title == null) 
		title = "";
	else
		title = "<center class=BigText>" + title + "</center>"
	story = title + story;
	// test
	//$("#story").hide()
	story = story.replace(new RegExp("(display: )block", "gi"), "$1none");
	story = story.replace(new RegExp("(display:)block", "gi"), "$1none");
	story = story.replace(new RegExp("class=comment", "g"), "class=comment_reading");
	story = story.replace(new RegExp("id=p_", "g"), "id=pp_"); // for IE
	story = story.replace(new RegExp("id=\"p_", "g"), "id=\"pp_"); // for the rest
	story = story.replace(new RegExp("c_", "g"), "cc_");
	story = story.replace(new RegExp('OnClick="ToggleComment(.*);"', 'gi'), 'OnClick="PinInlineComment$1;" OnMouseOver="OverInlineComment$1;" OnMouseOut="OutInlineComment$1;"');
	//story = story.replace(new RegExp('"inlinetoolbar"', 'g'), '"inlinetoolbar" style="display:none;"');
	storyLower = story.toLowerCase();
	storyLength = story.length;
	//alert(story);

}

function FillLines(i, jump) {

	var c = document.getElementById('content');
	numLines = countLines();
	if (numLines < readingHeight/20) {
		c.innerHTML = story.substring(startChar, i);
		i += jump;
		if (i < story.length) {
			j = 100
			if (j > story.length-i) j = story.length-i
			setTimeout('FillLines('+i+', '+j+')', 1);
			return;
		} 
	}
	if (i < story.length) {
		i -= jump;
		var isBackPara = true;
		var ii = i;
		while (ii > startChar) {
			ii -= 1;
			var gotIt = false;
			var lst = ["</div>", "</p>"]
			for (k = 0; k < lst.length; k++) {
				var l = lst[k].length
				if (storyLower.substring(ii, ii+l) == lst[k]) {
					ii += l;
					gotIt = true;
					break;
				}
			}
			if (gotIt)
				break;
		}
		//alert(i-ii);
		if (!isBackPara && i-ii > 400 ) { // backtrack lines instead if we lose more than 200 characters off the page

			numLines = countLines();
			var ii = i;
			while (ii > startChar) {
				ii -= 10; // 10 letters at a time
				$("#content").html(story.substring(startChar, ii))
				numLines = countLines();
				if (numLines < readingHeight/20) {
					// okay, now find the space
					while (ii > startChar) {
						ii -= 1
						if (storyLower.substring(ii, ii+1) == " ") {
							// find out if we're inside a tag
							var j = 0;
							while (j < 10) {
								var sb = storyLower.substring(ii-j, ii-j+1);
								if (sb == "<") {
									ii -= j
									break;
								} else if (sb == ">")
									break
								j += 1
							}
							break;
						}
					}
					break
				}
			}
		}
		// we only want to backtrack if we find some text (if there are no paragraph breaks we'll settle for what we got)
		if (ii > startChar)
			i = ii
	}
	var t = story.substring(startChar, i);
	if (i == startChar || t.length <= 1) {
		//alert('all done. Got '+pages.length+' pages (' + i + ') ' + story.length + ' ' + pages[pages.length-1]);
		//alert(pages[pages.length-2])
		if (pages.length == 0) {
			c.innerHTML = "Error parsing text";
		}
		BuildReadingView();
		return;
	}
	// this page is ready, let's add it
	pages[pages.length] = t;
	c.innerHTML = "";
	$("#loadertext").html(' Parsing text ('+parseInt(100*i/storyLength)+'%)')
	$('#loader').css("top", $('#content').offset().top);
	$('#loader').css("left", $('#content').offset().left);
	$('#loader').css("width", $('#content').width());

	//c.style.color = "black"
	//$('#content').animate({color:"black"});
	startChar = i;
	j = readingHeight * 2 //number of characters to skip
	if (j > story.length-i) j = story.length-i-1

	setTimeout('FillLines('+i+', '+j+')', 1);
}

function NavigatePage(offset)
{
	SubmitText();

	if (isWorking || !IsReadingView() || isReadingScroll)
		return;
	if (currPage + offset < 0 || currPage + offset > pages.length-1)
		return;
	currPage += offset;
	$('#pagenum').html((currPage+1) + " / " + pages.length);
	$('#content').html(pages[currPage]);
	$('#content').animate({color:"black"});
	BindInlineParagraphs();
	currPos = null;
	var i = "page_nav_left";
	if (offset != 0) {
		if (offset > 0) i = "page_nav_right";
		$("#"+i).addClass("page_nav_down");
		setTimeout('$(".page_nav_down").removeClass("page_nav_down");', 200);
	}
}

function BuildReadingView()
{
	isWorking = false;
	if (!isReadingScroll) {
		currPage = 0;
		$('#content').animate({color:"black"});
		$('#loader').fadeOut();
		NavigatePage(0)
		$('.page_nav').show();
	} else {
		$('#loader').fadeOut();
		$('#content').css("color", "black");
		for (i = 0; i < pages.length; i++) {
			obj = $('#readingview')
			if (i > 0) {
				obj = obj.clone();
				obj.attr("id", obj.attr("id") + i);
				cnt = obj.find('#content');
				cnt.attr("id", cnt.attr("id") + i);
			} else
				cnt = obj.find('#content');
			pgnum = obj.find('#pagenum');
			pgnum.html((i+1) + " / " + pages.length);
			cnt.html(pages[i]);
			obj.appendTo('#readingviewcontainer');
		}
		//cnt = $('#readingview').find('#content');
		//cnt.html(pages[0]);
		$('.page_nav').hide();
	}
	$('.page_num').fadeIn();
	setTimeout('BindInlineParagraphs()', 100);

}
function ResetReadingView()
{
	// rescue the inline editor
	SubmitText();

	// now delete all
	pages = [];
	obj = $('#readingview').clone();
	obj.find(".page_outer").css("height", readingHeight+80)
	obj.find(".page_inner").css("height", readingHeight)
	$('.readingview').remove();
	obj.appendTo('#readingviewcontainer');
	ParseText();
}

function SetReadingViewHeight(h)
{
	if (isWorking)
		return;
	readingHeight = h;
	ResetReadingView()
}
function ToggleScrollView()
{
	if (isWorking)
		return;
	if (isReadingScroll > 0)
		isReadingScroll = 0;
	else
		isReadingScroll = 1
	ResetReadingView()
}


var pinnedComment = null;
var pinnedPara = null;
// Called when you mouse over a comment in a submitted inline crit
function OverInlineComment(what, i)
{
	var c = $("#cc_"+i);
	c.css("position", "absolute");
	c.css("width", "600px");
	c.css("left", $(what).offset().left);
	c.show()
	$(what).addClass("pinnedComment");
}

function OutInlineComment(what, i)
{
	if (pinnedComment == i)
		return;
	var c = $("#cc_"+i);
	c.hide()
	$(what).removeClass("pinnedComment");
}

function PinInlineComment(what, i)
{
	if (pinnedComment == i) {
		pinnedComment = null;
		pinnedPara = null;
		$(what).removeClass("pinnedComment")
	} else {
		if (pinnedPara != null) {
			$(pinnedPara).removeClass("pinnedComment")
			$("#cc_"+pinnedComment).hide();
		}
		pinnedPara = what;
		pinnedComment = i;
		$(what).addClass("pinnedComment")
	}
}

// READING VIEW END
