// ----------- General functions --------------

// The handy addLoadEvent.
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function addClass(target, classValue) {
	var pattern = new RegExp("(^| )" + classValue + "( |$)");
	if (!pattern.test(target.className)) {
		if (target.className == "") {
			target.className = classValue;
		}
		else {
			target.className += " " + classValue;
		}
	}
	return true;
}

// This function grabs all elements whose IDs contain a search string
function getElementsByIDMatch(node,searchPhrase,tag) {
	 var classElements = new Array();
	 var els = node.getElementsByTagName(tag);
	 var elsLen = els.length;
	 var pattern = new RegExp(searchPhrase, "gim");
	
	 for (i = 0, j = 0; i < elsLen; i++) {
		if (els[i].id.match(pattern)) {
		  classElements[j] = els[i];
		  j++;
		}
	  }
	  return classElements;
}

// This function grabs all elements of a certain class
function getElementsByClass(node,searchClass,tag) {
	var classElements = new Array();
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// This function grabs all elements whose classes contain a search string
function getElementsByClassMatch(node,searchClass,tag) {
	var classElements = new Array();
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp(searchClass, "g");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


// ------------  Annotation viewing functions ------------
function showAnnotation(whichAnnotation) {
	// Wipe annotation if visible
	if (document.getElementById(whichAnnotation+"visible")) {
	
		// This is the note <a>
		var note = document.getElementById(whichAnnotation+'link');
		// This is the array of children of the note <a> 
		var notekids = note.childNodes;
		// This is the popup that's gonna be erased
		var erasenote = document.getElementById(whichAnnotation+"visible");
		
		// Loop through the children of the <a>
		for (i=0; i<notekids.length; i++) {
			if (notekids.item(i).id == whichAnnotation+'visible') {
				note.removeChild(erasenote);
			}
		}
		
		// unhighlight annotated text, loop to catch multiple nodes for overlapping text
		//var noteCount = 1;
		//while (document.getElementById(whichAnnotation+"text"+noteCount)) {
		//	document.getElementById(whichAnnotation+"text"+noteCount).className = 'unhighlighted';
		//	noteCount++;	
		//}

	}
	// Show annotation if not visible
	else {
		var annotation = document.getElementsByTagName("p");
		// Loop for each footnote
		for (var i=0;i<annotation.length; i++) {
			// If this is the annotation which was passed, then grab its content
			if (annotation[i].id == whichAnnotation) var note = annotation[i].firstChild.nextSibling.nodeValue;
		}
		
		var noteContainer = document.createElement("div");
		var noteClose = document.createElement("img");
		noteClose.className = 'close';
		noteClose.src = ("http://historicalthinkingmatters.org/i/close.gif");
		var noteText = document.createTextNode(note);
		
		noteContainer.appendChild(noteText);
		noteContainer.id = whichAnnotation+"visible"
		noteContainer.className = 'popUpAnnotation';
		
		var content = document.getElementById("content");
		
		// Append noteContainer to relevant link
		document.getElementById(whichAnnotation+"link").appendChild(noteContainer);
		
		// highlight annotated text, loop to catch multiple nodes for overlapping text
		//var noteCount = 1;
		//while (document.getElementById(whichAnnotation+"text"+noteCount)) {
		//	document.getElementById(whichAnnotation+"text"+noteCount).className = 'highlighted';
		//	noteCount++;	
		//}
		
	}
	
	return false;

}

// ---------------- Annotation creation/editing functions ------------

// This function loads the text block from the server
function getText(id, annotationVisible, userID, annotationID) {
	var xmlHttp = new XMLHttpRequest();			
	if (annotationVisible == 1) var targetURL = globalURL+'annotation/getTextObject.php?annotationFlag=1&id='+id+'&userID='+userID+'&annotationID='+annotationID;
	if (annotationVisible == 0) var targetURL = globalURL+'annotation/getTextObject.php?annotationFlag=0&id='+id+'&userID='+userID+'&annotationID='+annotationID;

	
	alert(targetURL);
	// set up Dojo IO request
	var bindArgs = {
		url:        targetURL,
		error:      function(type, errObj){
			alert("Didn't work");
		},
		load:      function(type, data, evt){
			// clean up popup
			//alert(sendURL);
			var textDiv = document.getElementById('sourceText');
			textDiv.innerHTML = data;
			
			// Make annotations pop up
			if (annotationVisible == 1) prepAnnotations();
			// Make text annotatable
			if (annotationVisible == 0) prepSelection();
		}
	};
	
	// Go, Dojo, Go!
	var requestObj = dojo.io.bind(bindArgs);
	
}

// This function saves an annotation to the server and reloads the 
// text with the new annotation 
function saveAnnotation(annotationsText_selectBeginIndex, annotationsText_selectLength) {
	// Grab annotation text out of form
	annotationsText_text = document.getElementById('popUpText').value;
	
	var data = "Begin Index: "+annotationsText_selectBeginIndex;
	data += "\nLength: "+annotationsText_selectLength;
	data += "\nAnnotation: "+encodeURI(annotationsText_text);
	data += "\nuserID: "+userID;
	data += "\nid: "+id;
	
	//alert(data);
	
	//return;
	
	// Get permission to do stuff (not necessary once script is signed)
	netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	
	// Build URL to save annotation			
	var annotationsText_objectID = id;
	//var annotationsText_text = 'This is a sample annotation';
	var sendURL = globalURL+'flash/annotation.php?action=addAnnotation&type=text&annotationsText_objectID='+id+'&annotationsText_selectBeginIndex='+annotationsText_selectBeginIndex+'&userID='+userID+'&annotationsText_selectLength='+annotationsText_selectLength+'&annotationsText_text='+encodeURI(annotationsText_text);
	
	// set up Dojo IO request
	var bindArgs = {
		url:        sendURL,
		error:      function(type, errObj){
			alert("Didn't work");
		},
		load:      function(type, data, evt){
			// clean up popup
			//alert(sendURL);
			closePopup();
			
			// Turn off annotation mode
			annotateMode();
			
			// Reload text with new annotation
			getText(id, 1, userID);
			
		}
	};
	
	// Go, Dojo, Go!
	var requestObj = dojo.io.bind(bindArgs);
	
// Send annotation, reload text if successful
// 	var xmlHttp = new XMLHttpRequest();
// 	xmlHttp.open('POST', sendURL, true);
// 	xmlHttp.onreadystatechange = function() {
// 		if (xmlHttp.readyState == 4) {
// 			// clean up popup
// 			closePopup();
// 			//getText(id, 1, userID);
// 		}
// 	}
// 	xmlHttp.send(null);

}

function closePopup () {
	var content = document.getElementById("newAnnotationPopup");
	content.parentNode.removeChild(content);
	prepSelection();
}

// This function grabs the selected text and creates a popup window 
// in which an annotation can be entered
function getSel()
{
	var txt = '';
	var foundIn = '';
	
	// Deal with Firefox, Safari 1.3
	if (window.getSelection) {
		var selection = window.getSelection();
		txt = selection.toString();
		//txt = txt.replace(/\*/ig, '');
		
		// Only do the following if an actual selection 
		// (as opposed to a click) has been made
		if (txt != '') {
			
			// Make text non-clickable for the moment
			dePrepSelection();
			
			// Make DOM range object
			var range = selection.getRangeAt(0);
			
			// Figure out start/end of selection (within its specific node
			var selectStart = range.startOffset;
			// Why length-1? I dunno, it just is...[JMG]
			var selectLength = range.toString().length-1;
			
			// Figure out the DOM node that contains *all* the source text
			// (each paragraph of source is considered its own node)
			var source = range.startContainer;
			var endSource = range.endContainer;
			
			// Crawl backwards through siblings to add their lengths to offset
			var currNode = source;
			while (currNode.previousSibling) {
				currNode = currNode.previousSibling;
				if (currNode.nodeName == "BR") {
					selectStart += 1;
				}
				else {
					selectStart += currNode.nodeValue.length;
				}
			}	

			// Deal with line breaks inside selection
			var newlineTest = range.toString();
			if (newlineTest.match(/\n/g)){
				selectLength += newlineTest.match(/\n/g).length;
			}
			
			// Show popup window for annotation entry
			var popupContents = '<h4>What\'s your annotation?</h4><form name="annotationEnter" id="annotationEnter"><textarea size="" id="popUpText" name="popUpText"></textarea><br /><div id="submit"><a href="#" onClick="saveAnnotation('+selectStart+', '+selectLength+')">Save</a></div><div id="closePopup"><a href="#" onclick="closePopup()">close</a></div>';
			noteContainer = document.createElement("div");
			noteContainer.innerHTML = popupContents;
			noteContainer.id = "newAnnotationPopup";
			noteContainer.className = 'popUpAnnotation';
			
			range.insertNode(noteContainer);
		}
	}
	
	// Deal with IE 5.2 Mac, Firefox, Opera, Netscape 4
	else if (document.getSelection)
	{
		txt = document.getSelection().toString();
		if (txt != '') foundIn = 'document.getSelection()';
	}
	
	// Deal with IE for Windows
	else if (document.selection)
	{
		txt = document.selection.createRange().text;
		if (txt != '') foundIn = 'document.selection.createRange()';
	}
	else return;
}

function prepSelection() {
	selectionUniverse = document.getElementById('sourceText');
	selectionUniverse.onmouseup = function() {
		getSel();
	}
}

function dePrepSelection() {
	selectionUniverse = document.getElementById('sourceText');
	selectionUniverse.onmouseup = function() {
		return;
	}
}

function prepAnnotations() {
	var content = document.getElementById("inquiryShell");
	var links = content.getElementsByTagName("a");
	for (var i=0; i<links.length; i++) {
		// Figure out which links refer to anchors on page
		var pattern = new RegExp('#', "g");
		if (pattern.test(links[i].getAttribute("href"))) {
			var annotationId = links[i].getAttribute("href").split("#")[1];
			
			// Weed out links that don't refer to other links on this page
			if (!document.getElementById(annotationId)) continue;
			links[i].destination = annotationId;
			
			// Set up function for popup
			links[i].onclick = function() {
				showAnnotation(this.destination);
				return false;
				
			}
			// Make it hidden on load
			links[i].style.display = 'none';
		}
	}
}

// This function toggles between two states: one where the annotations are
// visible and clickable, the other where there are no annotations and the text
// is annotatable

function annotateMode() {
	if (annotate == 0) {
		getText(id, 0, userID);
		prepSelection();
		annotate = 1;
		document.getElementById('annotateButtonLink').innerHTML = 'cancel annotation';
	}
	else {
		getText(id, 1, userID);
		dePrepSelection();
		prepAnnotations();
		annotate = 0;
		document.getElementById('annotateButtonLink').innerHTML = 'make an annotation';
	}
}


function toggleVisibilityByClass(toggleClass, toggleTag) {
	els = getElementsByClass(document, toggleClass, toggleTag);
	if (els[0].style.display=="inline") {
		for (i=0; i<els.length; i++) {
			els[i].style.display="none";
		}
	}
	else {
		for (i=0; i<els.length; i++) {
			els[i].style.display="inline";
		}
	}
	return;
}

function toggleHighlightByIDMatch(searchPhrase, tag) {
	els = getElementsByIDMatch(document, searchPhrase, tag);
	if (els[0]) {
		if (els[0].className=="highlighted") {
			for (i=0; i<els.length; i++) {
				els[i].className="unhighlighted";
			}
		}
		else {
/*			// Turn off all annotations
			allEls = getElementsByIDMatch(document, 'annot', 'span');
			for (i=0; i<allEls.length; i++) {
				allEls[i].className="unhighlighted";
			}
			*/
			// Turn on relevant annotatons
			for (i=0; i<els.length; i++) {
				els[i].className="highlighted";
			}
		}
	}
	return;
}

function toggleVisibilityByIDMatch(searchPhrase, tag) {
	els = getElementsByIDMatch(document, searchPhrase, tag);
	if (els[0]) {
		if (els[0].style.display=="inline") {
			for (i=0; i<els.length; i++) {
				els[i].style.display="none";
			}
		}
		else {
			
/*			// Turn off all annotations
			allEls = getElementsByIDMatch(document, 'annot', 'a');
			for (i=0; i<allEls.length; i++) {
				allEls[i].style.display="none";
			}
			*/
			// Turn on relevant annotatons
			for (i=0; i<els.length; i++) {
				els[i].style.display="inline";
			}
		}
	}
	return;
}

function showMe(meta){
	
/*	elsA = getElementsByIDMatch(document, 'meta'+meta, 'a');	
	elsSpan = getElementsByIDMatch(document, 'meta'+meta, 'span');	
	if (elsA[0] || elsSpan[0]) {
		
		// Check if we're toggling this on
		if ((elsA[0].style.display != "inline") || (elsSpan[0].class != "highlighted")) {
			document.getElementById('showMe'+meta).
		}
	} */
	
	showLink = document.getElementById('showme'+meta);
	if (showLink.className == 'showmelink') addClass(showLink, 'on');
	else showLink.className = 'showmelink';
	
	
	// Turn on selected items
	toggleHighlightByIDMatch('meta'+meta, 'span');
	toggleVisibilityByIDMatch('meta'+meta+'annot', 'a');
}

function prepFootnotes() {
	if (!document.getElementById('footnotes')) return false;
	var footnotes = document.getElementById('footnotes');
	footnotes.style.display = "none";

}

addLoadEvent(prepFootnotes);
addLoadEvent(prepAnnotations);

