﻿var g_browser = "";

function detectBrowser()
{
	//Detect IE5.5+
	version=0;
	if (navigator.appVersion.indexOf("MSIE")!=-1)
	{
		temp=navigator.appVersion.split("MSIE");
		version=parseFloat(temp[1]);
	}

	if (version >= 5.5) //NON IE browser will return 0
	{
		g_browser = "IE";
		return;
	}
	
	if (navigator.userAgent.indexOf("Firefox")!=-1)
	{
		var versionindex = navigator.userAgent.indexOf("Firefox")+8;
		if (parseInt(navigator.userAgent.charAt(versionindex))>=1)
			g_browser = "FF";
	}
	
}

detectBrowser();

function $(i)
{
	return document.getElementById(i)
}

function hov(loc,cls)
{
	if(loc.className)
		loc.className=cls;
}

function findById(list, id)
{
	for (var i=0; i<list.length; i++)
	{
		var item = list[i];
		if (item.id == id)
			return item;
	}
	
	return null;
}

function setCaretAtEnd(obj)
{
	obj.focus();
	
	if (obj.createTextRange)
	{
		var range = obj.createTextRange();
		range.collapse(false);
		range.select();
	}
	else if (obj.setSelectionRange)
	{
		obj.focus();
		var length = obj.value.length;
		obj.setSelectionRange(length, length);
	}
}

function setCaretAtStart(obj)
{
	if (obj.createTextRange)
	{
		var range = obj.createTextRange();
		range.collapse(true);
		range.select();
	}
	else if (obj.setSelectionRange)
	{
		obj.focus();
		obj.setSelectionRange(0, 0);
	}
}

function copyToClipBoard() 
{
	var codeBoxObj = document.getElementById("codeBox");
	Copied = codeBoxObj.createTextRange();
	Copied.execCommand("Copy");
	Copied.select();
}

function clickOnEnter(butonId, evt)
{
	return clickOnKeyCode(butonId, evt, 13);
}

function isKey(evt, keyCode)
{
	var keycode;
	
	if (window.event)
	{
		keycode = window.event.keyCode;
		evt = window.event;
	}
	else if (evt)
	{
		keycode = evt.keyCode;
	}
	else
	{
		return false;
	}
	
	return (keycode == keyCode);
}

function clickOnKeyCode(butonId, evt, keyCode)
{
	// E.g.:
	// 13 = ENTER
	// 27 = ESC
	// 9 = TAB
	if (isKey(evt, keyCode))
	{
		evt.cancel = true;
		evt.cancelBubble = true;
		evt.returnValue = false;

		// Use a timer to allow auto-complete to work
		if ($(butonId).click == null)
			setTimeout("$('" + butonId + "').onclick()", 1);		// For FF
		else
			setTimeout("$('" + butonId + "').click()", 1);
		
		return false;
	}
	
	return true;
}

function focusOnEsc(buttonId, event)
{
	if (isKey(event, 27))
	{
		$(buttonId).focus();
		return false;
	}
	
	return true;
}

function handleEditKeyDown(control, buttonId, event)
{
	if (isKey(event, 9))			// Tab
	{
		insertAtCursor(control, "\t");
		return false;
	}
	else if (isKey(event, 27))			// ESC
	{
		$(buttonId).focus();
	}
	
	return true;
}

function insertAtCursor(myField, myValue)
{
  //IE support
  if (document.selection)
  {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA/NETSCAPE support
  else if (myField.selectionStart || myField.selectionStart == '0')
  {
	var lastSelectionStart = myField.selectionStart;
	var lastSelectionEnd = myField.selectionEnd;
	
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
                  + myValue
                  + myField.value.substring(endPos, myField.value.length);

	myField.selectionStart = lastSelectionStart + 1;
	myField.selectionEnd = lastSelectionEnd + 1;
  }
  else
  {
	myField.value += myValue;
  }
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	
	for (var i = 0; i < ca.length;i++)
	{
		var c = ca[i];
		
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length, c.length);
	}
	
	return null;
}

function createCookie(name, value, days)
{
	var expires;
	
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else
	{
		expires = "";
	}
	
	document.cookie = name+"="+value+expires+"; path=/";
}

function hide(id)
{
	$(id).style.display = "none";
}

function show(id)
{
	$(id).style.display = "inline";
}

function hideUnhide(hideObjId, showObjId)
{
	$(hideObjId).style.display = "none";
	$(showObjId).style.display = "inline";
}

function timedStatus(message)
{
	window.status = message;
}

function setStatus(message)
{
	window.status = message;
	setTimeout('timedStatus("' + message + '")', 1);
}

function getHtml(url)
{
	try
	{
		var xmlHttp = null;
		// code for Mozilla, etc.
		if (window.XMLHttpRequest)
		{
			xmlHttp = new XMLHttpRequest();
		}
		// code for IE
		else if (window.ActiveXObject)
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

		xmlHttp.open("GET", url, false);
		xmlHttp.send(null);
		return xmlHttp.responseText;
	}
	catch(e)
	{
	}
	finally
	{
	}
	
	return "";
}

function postAsyncForm(url, args)
{
	try
	{
		var xmlHttp = null;
		// code for Mozilla, etc.
		if (window.XMLHttpRequest)
		{
			xmlHttp = new XMLHttpRequest();
		}
		// code for IE
		else if (window.ActiveXObject)
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

		xmlHttp.open("POST", url, false);
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlHttp.send(args);
		return xmlHttp.responseText;
	}
	catch(e)
	{
	}
	finally
	{
	}
	
	return "";
}

/* ==================================================================================================== */

function performSearch(b)
{
	b.value = "searching...";
	b.disabled = true;
	var term = $("SearchBox").value;
	var byAuthor = $("ctl00_MainContentPlaceHolder_byAuthorRadio").checked;
	if (byAuthor)
		window.location = g_rootUrl + "search.aspx?s=" + term + "&m=a";
	else
		window.location = g_rootUrl + "search.aspx?s=" + term;
}

function FreezeScreen(msg)
{
	scroll(0,0);
	var outerPane = document.getElementById('FreezePane');
	var innerPane = document.getElementById('InnerFreezePane');
	if (outerPane) outerPane.className = 'freezePaneOn';
	if (innerPane && msg != null) innerPane.innerHTML = msg;
}

function html2Txt(html)
{
	var output = html;
	// while loop is for Safari
	do
		output = output.replace("<br>", "\r", "gi");
	while (output.indexOf("<br>") > 0);
	
	// IE makes tags uppercase
	do
		output = output.replace("<BR>", "\r", "gi");
	while (output.indexOf("<BR>") > 0);

	do
		output = output.replace("<span class=\"tab\"></span>", "\t", "gi");
	while (output.indexOf("<span class=\"tab\"></span>") > 0);

	// IE makes tags uppercase, and removes quotes
	do		
		output = output.replace("<SPAN class=tab></SPAN>", "\t", "gi");
	while (output.indexOf("<SPAN class=tab></SPAN>") > 0);

	do
		output = output.replace("&lt;", "<", "gi");
	while (output.indexOf("&lt;") > 0);

	do
		output = output.replace("&gt;", ">", "gi");
	while (output.indexOf("&gt;") > 0);

	do
		output = output.replace("&amp;", "&", "gi");
	while (output.indexOf("&amp;") > 0);

	return output;
}

function countLines(str, columns)
{
	if (str == null || str.length == 0)
		return 1;
		
	var lineCount = 1;
	var colCount = 0;
	// var nl = 0;
	for (var i = 0; i < str.length; i++)
	{
		var chr = str.substr(i, 1);
		if (chr == "\t")
			colCount += 4;
		else
			colCount++;

		// if (chr == '\r') nl++;
			
		if (chr == '\r' || colCount > columns)
		{
			lineCount++;
			colCount = 0;
		}
	}
	
	// alert (lineCount + ", cols: " + columns + ", str.length=" + str.length + ", nl=" + nl);
	
	return lineCount;
}

var g_lastEditedNode = null;

function editNote(node, noteId, isPrivate, noteType, pageNum)
{
	hide("editNotePanel");
	if (g_lastEditedNode != null)
	{
		g_lastEditedNode.style.display = "inline";
		g_lastEditedNode = null;
	}

	g_lastEditedNode = node;

	var editContainer = $("editContainer");

	$("ctl00_MainContentPlaceHolder_OperationInfo").value = noteId;
	var editTextBox = $("ctl00_MainContentPlaceHolder_EditNoteTextBox");
	var contentNode = node.firstChild;
	if (contentNode.tagName != "DIV")
		contentNode = contentNode.nextSibling;		// for FF
	var contents = html2Txt(contentNode.innerHTML);

	g_lastEditedNode.parentNode.insertBefore(editContainer, g_lastEditedNode.nextSibling);
	editTextBox.value = contents;

	// 87 is (approximately) how many characters fit on one line - not determinate due to variable width chars
	var estimatedLines = countLines(contents, 87) + 2;
	if (estimatedLines < 4)
		editTextBox.rows = 4;
	else if (estimatedLines > 35)
		editTextBox.rows = 35;
	else
		editTextBox.rows = estimatedLines;
		
	var privateCheckBox = $("ctl00_MainContentPlaceHolder_EditNotePrivateCheckBox");
	if (privateCheckBox != null)
	{
		if (isPrivate == 1)
			privateCheckBox.checked = true;
		else
			privateCheckBox.checked = false;
	}

	var noteTypeDD = $("ctl00_MainContentPlaceHolder_EditNoteTypeDropDown");
	if (noteType == 1)	// Book quote / summary
		noteTypeDD.selectedIndex = 0;
	else if (noteType == 2)	// Idea
		noteTypeDD.selectedIndex = 1;
	else if (noteType == 3)	// Question
		noteTypeDD.selectedIndex = 2;

	var pageTextBox = $("ctl00_MainContentPlaceHolder_EditNotePageTextBox");
	pageTextBox.value = (pageNum == 0) ? "" : pageNum;

	g_lastEditedNode.style.display = "none";
	show("editNotePanel");
	setCaretAtEnd(editTextBox);
}

function deleteNote(noteId)
{
	if (confirm("Permanently delete this note?"))
	{		
		$("ctl00_MainContentPlaceHolder_OperationInfo").value = noteId;
		$("ctl00_MainContentPlaceHolder_DeleteNoteButton").click();
	}
}

function addComment(node, noteId)
{
	$("ctl00_MainContentPlaceHolder_OperationInfo").value = noteId;
	var editContainer = $("addCommentContainer");
	show("addCommentPanel");
	var editTextBox = $("ctl00_MainContentPlaceHolder_AddCommentTextBox");
	editTextBox.value = "";
	node.parentNode.insertBefore(editContainer, node.nextSibling);
	setCaretAtEnd(editTextBox);
}

function showComments(node, noteId)
{
	var panelId = "commentPanel_" + noteId;
	var panel = $(panelId);
	if (panel != null)
	{
		//panel.style.display = "inline";
		addComment(panel, noteId);
	}
	else
	{	
		addComment(node, noteId);

		var html = getHtml(g_rootUrl + "comments.aspx?n=" + noteId);
		var div = document.createElement("div");
		div.id = "commentPanel_" + noteId;
		div.className = "commentPanel";
		div.innerHTML = html;
		node.parentNode.insertBefore(div, node.nextSibling);
	}
}

var g_lastEditedCommentNode = null;

function editComment(node, commentId)
{
	if (g_lastEditedCommentNode != null)
	{
		g_lastEditedCommentNode.style.display = "inline";
		g_lastEditedCommentNode = null;
	}

	g_lastEditedCommentNode = node;

	$("ctl00_MainContentPlaceHolder_OperationInfo").value = commentId;
	var editContainer = $("editCommentContainer");
	show("editCommentPanel");
	var editTextBox = $("ctl00_MainContentPlaceHolder_EditCommentTextBox");
	var contentNode = node.firstChild;
	if (contentNode.tagName != "DIV")
		contentNode = contentNode.nextSibling;		// for FF
	editTextBox.value = contentNode.innerHTML;
	g_lastEditedCommentNode.parentNode.insertBefore(editContainer, g_lastEditedCommentNode.nextSibling);
	setCaretAtEnd(editTextBox);
	
	g_lastEditedCommentNode.style.display = "none";
}

function deleteComment(noteId)
{
	if (confirm("Permanently delete this comment?"))
	{
		$("ctl00_MainContentPlaceHolder_OperationInfo").value = noteId;
		$("ctl00_MainContentPlaceHolder_DeleteCommentButton").click();
	}
}

function editChapters(numChapters)
{
	var newNumChapters = parseInt(prompt("How many chapters does this book have?", numChapters), 10);
	
	if (newNumChapters > 0)
	{
		$("ctl00_MainContentPlaceHolder_OperationInfo").value = newNumChapters;
		$("ctl00_MainContentPlaceHolder_EditChaptersButton").click();
	}
}

function fave(noteId, control)
{
	postAsyncForm(g_rootUrl + "BookCmd.aspx", "op=AddToFavorites&n=" + noteId);

	var imgNode = control.firstChild;
	if (imgNode.tagName != "IMG")
		imgNode = imgNode.nextSibling;		// for FF
	
	control.onclick = function() {unFave(noteId, this);};
	imgNode.src = g_rootUrl + "img/sCStar.gif";
	imgNode.onmouseover = function() {this.src = g_rootUrl + "img/sCStar2.gif";};
	imgNode.onmouseout = function() {this.src = g_rootUrl + "img/sCStar.gif";};
	imgNode.title = "Remove this note from your favorites page.";
}

function unFave(noteId, control)
{
	postAsyncForm(g_rootUrl + "BookCmd.aspx", "op=RemoveFromFavorites&n=" + noteId);

	var imgNode = control.firstChild;
	if (imgNode.tagName != "IMG")
		imgNode = imgNode.nextSibling;		// for FF
	
	control.onclick = function() {fave(noteId, this);};
	imgNode.src = g_rootUrl + "img/sStar.gif";
	imgNode.onmouseover = function() {this.src = g_rootUrl + "img/sStar2.gif";};
	imgNode.onmouseout = function() {this.src = g_rootUrl + "img/sStar.gif";};
	imgNode.title = "Add this note from your favorites page.";
}

function addToolTips()
{
	var tmp = true;
	var anchors = document.body.getElementsByTagName("a");

	for (var i = 0; i < anchors.length; i++)
	{ 
		var anchor = anchors[i];		
		var images = anchor.getElementsByTagName("img");
		for (var j = 0; j < images.length; j++)
		{
			var image = images[j];

			if (image.src.indexOf(g_rootUrl + "img/sView.gif") >= 0)
			{
				if (image.title == null || image.title.length == 0)
					image.title = "View this user's notes.";
				image.onmouseover = function() {this.src = g_rootUrl + "img/sView2.gif";};
				image.onmouseout = function() {this.src = g_rootUrl + "img/sView.gif";};
			}
			if (image.src.indexOf(g_rootUrl + "img/sDelete.gif") >= 0)
			{
				if (image.title == null || image.title.length == 0)
					image.title = "Delete this note.";
				image.onmouseover = function() {this.src = g_rootUrl + "img/sDelete2.gif";};
				image.onmouseout = function() {this.src = g_rootUrl + "img/sDelete.gif";};
			}
			if (image.src.indexOf(g_rootUrl + "img/sEdit.gif") >= 0)
			{
				if (image.title == null || image.title.length == 0)
					image.title = "Edit this note.";
				image.onmouseover = function() {this.src = g_rootUrl + "img/sEdit2.gif";};
				image.onmouseout = function() {this.src = g_rootUrl + "img/sEdit.gif";};
			}
			if (image.src.indexOf(g_rootUrl + "img/sHist.gif") >= 0)
			{
				if (image.title == null || image.title.length == 0)
					image.title = "View this note's change history.";
				image.onmouseover = function() {this.src = g_rootUrl + "img/sHist2.gif";};
				image.onmouseout = function() {this.src = g_rootUrl + "img/sHist.gif";};
			}
			else if (image.src.indexOf(g_rootUrl + "img/sStar.gif") >= 0)
			{
				if (image.title == null || image.title.length == 0)
					image.title = "Add this note to your favorite page.";
				image.onmouseover = function() {this.src = g_rootUrl + "img/sStar2.gif";};
				image.onmouseout = function() {this.src = g_rootUrl + "img/sStar.gif";};
			}
			else if (image.src.indexOf(g_rootUrl + "img/sCStar.gif") >= 0)
			{
				if (image.title == null || image.title.length == 0)
					image.title = "Remove this note from your favorites page.";
				image.onmouseover = function() {this.src = g_rootUrl + "img/sCStar2.gif";};
				image.onmouseout = function() {this.src = g_rootUrl + "img/sCStar.gif";};
			}
		}
	}
}

function showHistory(noteId)
{
	var url = g_rootUrl + "NoteHistory.aspx?id=" + noteId;
	window.open(url, "_blank", "width=620, height=700, scrollbars=yes", null);
}

function limitLen(control, maxLength)
{
	if (control.value.length > maxLength)
	{
		control.value = control.value.slice(0, maxLength);
		control.scrollTop = control.scrollHeight;
		alert("Each note is limited to " + maxLength + " characters.");
	}
}