// Determine user browser
var b = navigator.userAgent;
var ie = (b.indexOf("MSIE") > 0 && b.indexOf("Win") > 0 && b.indexOf("Windows 3.1") < 0);

// Define java to use
var base = '"http://www.j2e.com/just2easy"';
var code = '"speak/Speak.class"';
var arch = '"speak.jar, j2e301t.jar"';

// Write out object
document.writeln('<object id="speak" width="1" height="1"');

if (ie == true){	
	document.writeln(' classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" \
		codebase="http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#Version=5,0,0,9"');
}
else
	document.writeln(' code=' +code+ ' archive=' +arch);

document.writeln('type="application/x-java-applet;version=1.5">');

document.writeln(' \
	<param name="type" value="application/x-java-applet;version=1.5"> \
	<param name="codebase" value=' +base+ '> \
	<param name="archive"  value=' +arch+ '> \
	<param name="code"     value=' +code+ '> \
	<param name="scriptable" value="false">');

document.writeln('</object>');

if (ie == true)
	document.getElementById('speak').activate = false;

var next = new Array();
var original = new Array();
var button;

function speakSelection(b){
	var s = document.getElementById('speak');
	var busy = s.speaking();
	button = b;

	if (busy == "1"){
		next = "";

		var talkButton = document.getElementById(button);
		if (talkButton.value == "stop")
			talkButton.value = "talk";

		return;
	}

	var txt = '';

	if (window.getSelection)
		txt = window.getSelection();
	else if (document.getSelection)
		txt = document.getSelection();
	else if (document.selection)
		txt = document.selection.createRange().text;

	txt = ""+txt;

	if (txt.length == 0)
		txt = 'Please select some words.';

	txt = stripCr(txt);

	var talkButton = document.getElementById(button);
	if (talkButton.value == "talk")
		talkButton.value = "stop";

	speak('content',txt);
}

function stripCr(txt){
	while(txt.indexOf("\r\n")!=-1)
      	txt = txt.replace("\r\n"," ");

	while(txt.indexOf("\n")!=-1)
      	txt = txt.replace("\n"," ");

	while(txt.indexOf("\r")!=-1)
      	txt = txt.replace("\r"," ");

	return txt;
}

function read(id){
	var o = document.getElementById(id);

	if (o.speaking)
		o.speaking = false;
	else{
		o.speaking = true;
		var txt = o.innerHTML;
		speak(id,stripHTML(txt));
	}
}

function speak(id, txt){
	txt = ""+txt;	// Force to string, for Firefox!

	while (txt.substring(txt.length-1)==" ")	// Remove trailing spaces.
		txt = txt.substring(0,txt.length-1);

	while (txt.substring(0,1)==" ")	// Remove leading spaces
		txt = txt.substring(1);

	var dot = txt.indexOf(".");
	var que = txt.indexOf("?");
	var exc = txt.indexOf("!");
	var br  = txt.toLowerCase().indexOf("<br>");

	while (dot != -1 && txt.substring(dot,dot+3) == ".co")	// skip .com, and .co.uk
		dot = txt.indexOf(".",dot+1);

	if (dot == -1)
		dot = Number.MAX_VALUE;

	if (que == -1)
		que = Number.MAX_VALUE;

	if (exc == -1)
		exc = Number.MAX_VALUE;

	if (br == -1)
		br = Number.MAX_VALUE;
	else
	 	br--;

	dot = Math.min(dot,que);
	dot = Math.min(dot,exc);
	dot = Math.min(dot,br);
	var n;

	if (dot >= txt.length)
		n = next.push('')-1;
	else{
		var n1 = txt.substr(dot+1);

		if (n1.substring(0,4)=="<br>")
			n1 = n1.substring(4);

		n = next.push(n1)-1;
		txt = txt.substr(0,dot+1);
	}

	var s = document.getElementById('speak');
	s.speak(txt);

	var idSeg = findTxt(id,txt);
	var html = document.getElementById(idSeg);

	index = original.push( html.innerHTML ) - 1;
	var doub = txt.indexOf("  ");
	while (doub!=-1){
		txt = txt.replace("  "," ");
		doub = txt.indexOf("  ");
	}

//alert(">"+txt+"<");
	if (idSeg != 'content' && txt.length>0)	// text was not found within a div.
		highlightSearchTerms(idSeg, txt, true);

	document.getElementById(id).speaking = true;
	var cmd = "monitor('"+id+"','"+idSeg+"','"+index+"','"+n+"')";
	setTimeout(cmd,1500);
}

function say(txt){
	var s = document.getElementById('speak');
	s.speak(txt);
}

function allQuotes(txt){
	var i = txt.indexOf("'")

	if (i!=-1){
		var s = txt.substring(0,i)
		var e = txt.substring(i+1)
		e = allQuotes(e)
		return s + "\\'" + e
	}

	return txt
}

function monitor(id,idSeg,index,n){
	var s = document.getElementById('speak');
	var busy = s.speaking();

	if (busy == "0"){
		var html = document.getElementById(idSeg);

		if (idSeg != 'content' && html != undefined)
			html.innerHTML = original[index];

		var o = document.getElementById(id);

		if (o.speaking && next[n].length > 0 ){
			var cmd = "speak('"+id+"','"+allQuotes(next[n])+"')";
			setTimeout(cmd,500);	// Pause, then speak
		}
		else{
			var talkButton = document.getElementById(button);

			if (talkButton != undefined && talkButton.value == "stop")
				talkButton.value = "talk";
		}
	}
	else{
		var cmd = "monitor('"+id+"','"+idSeg+"','"+index+"','"+n+"')";
		setTimeout(cmd,1000);
	}
}

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
var c = 0;	// global for tag count.

function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
	// the highlightStartTag and highlightEndTag parameters are optional
	if ((!highlightStartTag) || (!highlightEndTag)) {
		highlightStartTag = "<font style='color:blue;'>";	// background-color:yellow;'>";
		highlightEndTag = "</font>";
	}
  
	// find all occurences of the search term in the given text,
	// and add some "highlight" tags to them (we're not using a
	// regular expression search, because we want to filter out
	// matches that occur within HTML tags and script blocks, so
	// we have to do a little extra validation)
	var newText = "";
	var i = -1;
	var lcSearchTerm = searchTerm;	//.toLowerCase();	Preserve case!
	var lcBodyText = bodyText;	//.toLowerCase();
    
	while (bodyText.length > 0) {
		i = htmlIndexOf(lcBodyText, lcSearchTerm, i+1);

		if (i < 0) {
			newText += bodyText;
			bodyText = "";
		} else {
			// skip anything inside an HTML tag
			if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
				// skip anything inside a <script> block
				if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
					newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length + c) + highlightEndTag;
					bodyText = bodyText.substr(i + searchTerm.length + c);
					lcBodyText = bodyText;	//.toLowerCase();
					i = -1;
				}
			}
		}
	}
  
	return newText;
}
 
function htmlIndexOf(text, term, start){
	// Function is like indexOf( ), but ignores html codes within the text.
	var array = term.split(" ");
	var i = text.indexOf(array[0],start);

	while (i!=-1){
		c = 0;
		var subtext = text.substring(i);

		if (subtext.indexOf(term)==0)
			return i;

		while( subtext.indexOf("<")!=-1){
			var j = subtext.indexOf("<");
			var k = subtext.indexOf(">");

			if (k==-1 || k<j)
				break;
			else{
				subtext = subtext.substring(0,j) + subtext.substring(k+1);
				c += k-j+1;	// extra characters for tags.

				if (subtext.indexOf(term)==0)
					return i;
			}
		}

		if (subtext.indexOf(term)==0)
			return i;

		i = text.indexOf(array[0],i+1);
	}

	return -1;
}

function findTxt(id,txt){
	if (id=='content'){
		var content = document.getElementById(id);
		var html = content.innerHTML;
		var i = htmlIndexOf(html, txt, 0);

		if (i>-1){
			while (i>0 && html.substring(i,i+8).toLowerCase()!= "<div id=")
				i--;

			if (i>0){
				var end = html.indexOf('>',i+8);
				var newId = html.substring(i+8, end);

				while( newId.indexOf('"')!=-1)
					newId = newId.replace('"',"");

				return newId;
			}
		}
	}

	return id;
}

/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(id, searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
	// if the treatAsPhrase parameter is true, then we should search for 
	// the entire phrase that was entered; otherwise, we will split the
	// search string so that each word is searched for and highlighted
	// individually
	if (treatAsPhrase)
		searchArray = [searchText];
	else
		searchArray = searchText.split(" ");
  
	var html = document.getElementById(id);

	if (!html || typeof(html.innerHTML) == "undefined") {
		if (warnOnFailure)
			alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");

		return false;
	}
  
  	var bodyText = html.innerHTML;
  	for (var i = 0; i < searchArray.length; i++)
    		bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  
  	html.innerHTML = bodyText;
  	return true;
}

function stripHTML(txt){
	// Strip all < > controls from the text.
	txt = stripCr(txt);
	txt = txt.replace(/<br>/gi,"%br%");

	while( txt.indexOf("<")!=-1){
		var j = txt.indexOf("<");
		var k = txt.indexOf(">");

		if (k==-1 || k<j)
			break;
		else
			txt = txt.substring(0,j) + txt.substring(k+1);
	}

	txt = txt.replace(/%br%/gi,"<br>");

	return txt;
}

