// JavaScript Document

var numPages = 8;
var popWidth = 500;
var popHeight = 350;
var pageWidth = 705;
var characterWidth = 300;
var showCharacter = false;
var currentlyReading = false;
var MIN_CHUNK_SIZE = 400;
var MAX_CHUNKS = 10;
var EulogyTemplate = "<br>";

function setPage(n) {
	// close any open popups
	closePopup();

	if (n != "add_users") {

		// show the relevant page of the Eulogy writer
		for ( var i = 0; i <= numPages; i++) {
			document.getElementById("page" + i).style.display = "none";
		}
		document.getElementById("page" + n).style.display = "block";

		// show the Eulogy Text if switching to that page
		if (n == 7)
			window.setTimeout('setText()', 50);
		else
			getText();

	}

	else {
		location.href = 'users.php';
	}
}
function createEulogy() {
	if (confirm("Click OK to create a new Eulogy based on the data you have saved in Eulogy Builder.\n\nPlease note that this will replace your current Eulogy completely.\n\nClick Cancel to preserve your current Eulogy.\n\n")) {
		var frm = document.getElementById("frmEulogy");
		frm.action = "createEulogy.php";
		frm.submit();
	}
}
function setText() {
	// save local textbox to editor
	var frm = document.getElementById("frmEulogy");
	if (frm.eCopyOfText.value != "")
		sed.setText(frm.eCopyOfText.value);
	else
		sed.setText(EulogyTemplate);
}
function getText() {
	// save editor to local textbox
	var edTxt = sed.getText();
	var frm = document.getElementById("frmEulogy");
	if (edTxt != "") {
		frm.eCopyOfText.value = edTxt;
	}
}
function setup() {
	
	// hide timer
	document.getElementById("timer").style.display = "none";
	// set the initial conditions for the form
	var eName = document.getElementById("eFriendlyName");
	if (eName != "")
		preferredNameSubstitute(eName.value);

	// show or hide the further education box as appropriate
	var fe = document.getElementById("showFE");
	if (fe.checked == 1)
		showFEBox();
	else
		hideFEBox();

	// show or hide the children box as appropriate
	var _hasChildren = document.getElementById("hasChildren");
	if (_hasChildren.checked == 1)
		showhideBox("childrenBox");
	else
		hideBox("childrenBox");

	frm = document.getElementById("frmEulogy");
	//alert (frm.eCopyOfText.value);
	sed.setText(frm.eCopyOfText.value);

	// add dragging for the popup and the character
	_popup = document.getElementById("popup");
	_poptitle = document.getElementById("poptitle");
	_character = document.getElementById("character");
	_characterTitle = document.getElementById("characterTitle");
	Drag.init(_poptitle, _popup);
	Drag.init(_characterTitle, _character);

	// jump to page (if requested)
	var pn = document.getElementById("hpagenum").value;

	if (pn != "")
		setPage(pn);
	else
		setPage(0);



}
function getData(stuffRequested, id, returnToID) {
	sendRequest(stuffRequested + '&id=' + id + '&returnto=' + returnToID)
}
function preferredNameSubstitute(name) {
	var intLbl = 0;
	var intLbl1 = 0;

	// replace labels
	labels = document.frmEulogy.getElementsByTagName("label");
	for (i = 0; i < labels.length; i++)
		labels[i].innerHTML = name;

	// replace -name- in options boxes
	options = document.frmEulogy.getElementsByTagName("option");
	for (i = 0; i < options.length; i++) {
		var fName = document.getElementById("eFriendlyName").value;
		var gender = document.getElementById("eGender").value;
		var Gender = "his";
		if (gender == "female")
			Gender = "her";
		options[i].innerHTML = options[i].innerHTML.replace(/-name-/g, fName); // globally replace the -name- string
		options[i].innerHTML = options[i].innerHTML
				.replace(/-hisher-/g, Gender); // globally replace the -hisher- string
	}

}
function clearChild(obj) {
	if (obj.value == "0") {
		switch (obj.id) {
		case ("child1Gender"):
			document.getElementById("child1Age").value = "";
			document.getElementById("child1Name").value = "";
			break;
		case ("child2Gender"):
			document.getElementById("child2Age").value = "";
			document.getElementById("child2Name").value = "";
			break;
		case ("child3Gender"):
			document.getElementById("child3Age").value = "";
			document.getElementById("child3Name").value = "";
			break;
		case ("child4Gender"):
			document.getElementById("child4Age").value = "";
			document.getElementById("child4Name").value = "";
			break;
		}
	}
}

// 'AJAX' functions ------------------------------------------------------------------------- //
function createRequestObject() {
	var ro;
	var browser = navigator.appName;
	if (browser == "Microsoft Internet Explorer") {
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		ro = new XMLHttpRequest();
	}
	return ro;
}

var http = createRequestObject();

function sendRequest(action) {
	http.open('get', 'dblink.php?action=' + action);
	http.onreadystatechange = handleResponse;
	http.send(null);
}

function handleResponse() {
	if (http.readyState == 4) {

		// coolect variable to subsitute into any response
		var fName = document.getElementById("eFriendlyName").value;
		var gender = document.getElementById("eGender").value;
		var Gender = "his";
		if (gender == "female")
			Gender = "her";

		// collect the response
		var response = http.responseText;    //alert (response);
		var update = new Array();
		//alert (response);
		if (response.indexOf('|' != -1)) {
			update = response.split('|');
			// fill in the control (if appropriate) and subst -name- with friendly name
			// globally replace the -hisher- string
			document.getElementById(update[0]).value = update[1].replace(
					/-name-/g, fName).replace(/-hisher-/g, Gender);
		}
	}
}
//  End of 'AJAX' functions ---------------------------------------------------------------- //

function vh_talkStarted() {
	document.body.style.cursor = 'default';
}
function vh_talkEnded() {
	hideCharacter();
	currentlyReading = false;
	_btn = document.getElementById("btnSpeak");
	_btn.src = "images/speak.gif";
	_btn.alt = "Read my Eulogy";
}
function removeHTMLblock(aSourceString, aTagName) {
	regexp = new RegExp("<" + aTagName + "[^.]\.*\/*" + aTagName + ">", "gi");
	vStrippedHTML = aSourceString.replace(regexp, "");
	return vStrippedHTML;
}
function removeIBlocks(txt) {
	var pos = 0;

	while (pos > -1) {
		pos = txt.indexOf("<i>");
		pos1 = txt.indexOf("</i>");
		if ((pos > -1) && (pos1 > -1)) {
			txt = txt.substring(0, pos) + txt.substring(pos1 + 4, txt.length);
			pos = txt.indexOf("<i>");
		}
	}
	return txt;
}
//function removeNL(s){
// removes control characters
//  return s.replace(/[\n\r\t]/g,);
//}
function removeNL(s) {

	//  Remove NewLine, CarriageReturn and Tab characters from a String
	r = "";
	for (i = 0; i < s.length; i++) {
		if (s.charAt(i) != '\n' && s.charAt(i) != '\r' && s.charAt(i) != '\t') {
			r += s.charAt(i);
		}
	}
	return r;
}
function removeUnicodeChars(s) {
	var r = "";
	for (i = 0; i < s.length; i++) {
		var c = s.charCodeAt(i);
		if ((c > 31) && (c < 123)) {
			if ((c = 32) || (c = 33) || (c = 44) || (c = 46)
					|| ((c > 47) && (c < 60)) || (c = 63)
					|| ((c > 64) && (c < 90)) || ((c > 96) && (c < 123)))
				r += s.charAt(i);
		}
	}
	return r;
}
function removeWhiteSpace(str) {
	return str.replace(/\s+/g, ' ');
}
function readEulogy() {
	// set the speech rate controls
	var srate = "<prosody rate='55%'>";
	var end_srate = "</prosody>";

	// set the cursor to 'wait'
	document.body.style.cursor = 'wait';

	// show the character (will either show or hide depending on the showCharacter boolean)
	showhideCharacter();
	followCursor(0); // don't follow the cursor

	//  change the play button to a stop button
	_btn = document.getElementById("btnSpeak");
	if (!currentlyReading) {
		currentlyReading = true;
		_btn.src = "images/speak_off.gif";
		_btn.alt = "Stop reading my Eulogy";
	} else {
		stopReading();
		return;
	}

	var txt = sed.getText();
	txt = removeUnicodeChars(txt);
	txt = removeWhiteSpace(txt);
	txt = removeIBlocks(txt); //  don't read anything in italics
	txt = removeNL(txt) //  remove control characters

	//     alert ("txt="+ txt);

	txt = txt.replace(/&nbsp;/gi, ""); // remove any non-breakable spaces
	txt = txt.replace(new RegExp("<p>", "gi"), ""); // remove opening paragraphs
	txt = txt.replace(new RegExp("</p>", "gi"), "."); // replace closing paragraphs with a fullstop
	txt = txt.replace(new RegExp("<br>", "gi"), ","); // replace breaks with a comma

	var tlen = txt.length;

	// break into chunks of less than 600 characters (for the synthesis engine)
	// look for the first full stop after n00 characters and call this a chunk
	var chunk = "";
	var have_chunk = false;
	var i = 0;
	var chunki = 0;
	var chunk_count = 0;

	while ((i < tlen) && (chunk_count < MAX_CHUNKS)) {
		chunk = "";
		have_chunk = false;
		chunki = 0;

		while (!have_chunk) {
			chr = txt.substring(i, i + 1);
			chunk = chunk + chr;
			i += 1;
			chunki += 1;
			if (((chunki > MIN_CHUNK_SIZE) && (chr == ".")) || (i >= tlen)) {
				have_chunk = true;
				chunk_count += 1;
				if (chunk.length > 1) {
					//    alert (chunk);
					sayText(srate + chunk + end_srate, 5, 1, 2);
				} else
					break;
			}
		}
	}
}
function stopReading() {
	stopSpeech();
	currentlyReading = false;
	document.body.style.cursor = 'default';
	_btn = document.getElementById("btnSpeak");
	_btn.src = "images/speak.gif";
	_btn.alt = "Read my Eulogy";
	hideCharacter();
}
function printEulogy() {
	sed.printme();
}
function insertRef() {
	// insert the currently selected Reference in to Eulogy writer
	var html = document.getElementById("refSelected").value;
	html = html.replace(/\n/g, "<br/>").replace(/\r/g, "").replace(/<br>/g,
			"<br/>");
	sed.insertTag(html);
	closePopup();
}
function showFEBox() {
	var box = document.getElementById("furtherEducation");
	if (box.style.display == "none")
		box.style.display = "block";
	else
		box.style.display = "none";
}
function hideFEBox() {
	var box = document.getElementById("furtherEducation");
	box.style.display = "none";
}
function showhideBox(boxID) {
	var box = document.getElementById(boxID);
	if (box.style.display == "none")
		box.style.display = "block";
	else
		box.style.display = "none";
}
function hideBox(boxID) {
	var box = document.getElementById(boxID);
	box.style.display = "none";
}
function changeCharacterAvailability() {
	_btnCharacter = document.getElementById("btnCharacter");
	if (showCharacter) {
		showCharacter = false;
		_btnCharacter.src = "images/hideSpeaker.gif";
		_btnCharacter.alt = "Hide the character when reading my Eulogy";
	} else {
		showCharacter = true;
		_btnCharacter.src = "images/showSpeaker.gif";
		_btnCharacter.alt = "Show the character when reading my Eulogy";
	}
}
function showhideCharacter() {
	_character = document.getElementById("character");

	if ((+_character.style.top.replace(/px/, '') < 0) && showCharacter) {
		// show the character
		_character.style.top = "64px";
		var proposedLeft = (pageWidth - characterWidth) / 2;
		if (proposedLeft < 0)
			proposedLeft = 0;
		_character.style.left = proposedLeft + "px";
	} else {
		// hide the character
		_character.style.top = "-1000px";
	}
}
function hideCharacter() {
	_character = document.getElementById("character");
	_character.style.top = "-1000px";
}
function saveEulogy(n) {
	// provides basic sanity checking and submits form to be saved
	// it saves everything on the Eulogy pages and returns the user to
	// the page containing the clicked 'save' button.
	var frm = document.getElementById("frmEulogy");
	var eid = document.getElementById("heulogyid").value;

	frm.eCopyOfText.value = sed.getText();
	frm.action = "saveEulogy.php?page=" + n + "&eulogyid=" + eid;
	frm.submit();
}
function addBible() {
	// shows the dialog to add a biblical reference
	btn = document.getElementById("btn_addBible");
	pop = document.getElementById("popup");
	_poptitle = document.getElementById("poptitle");
	centrePopUp();

	// show the relevant list of titles
	document.getElementById("refBibleSelector").style.display = "block";
	document.getElementById("refPoemSelector").style.display = "none";
	document.getElementById("refJokeSelector").style.display = "none";

	if (pop.style.display != "block") {
		pop.style.display = "block";
		btn.src = "images/add_a_biblical_reference_up.gif";
		_poptitle.innerHTML = "Add a Biblical Reference";
	} else {
		pop.style.display = "none";
		btn.src = "images/add_a_biblical_reference.gif";
	}
}
function addPoem() {
	// shows the dialog to add a poem or part of a poem
	btn = document.getElementById("btn_addPoem");
	pop = document.getElementById("popup");
	_poptitle = document.getElementById("poptitle");
	centrePopUp();

	// show the relevant list of titles
	document.getElementById("refBibleSelector").style.display = "none";
	document.getElementById("refPoemSelector").style.display = "block";
	document.getElementById("refJokeSelector").style.display = "none";

	if (pop.style.display != "block") {
		pop.style.display = "block";
		btn.src = "images/add_a_poem_up.gif";
		_poptitle.innerHTML = "Add a Poem";
	} else {
		pop.style.display = "none";
		btn.src = "images/add_a_poem.gif";
	}
}
function addJoke() {
	// shows the dialog to add a joke
	btn = document.getElementById("btn_addJoke");
	pop = document.getElementById("popup");
	_poptitle = document.getElementById("poptitle");
	centrePopUp();

	// show the relevant list of titles
	document.getElementById("refBibleSelector").style.display = "none";
	document.getElementById("refPoemSelector").style.display = "none";
	document.getElementById("refJokeSelector").style.display = "block";

	if (pop.style.display != "block") {
		pop.style.display = "block";
		btn.src = "images/add_a_joke_up.gif";
		_poptitle.innerHTML = "Add a Joke";
	} else {
		pop.style.display = "none";
		btn.src = "images/add_a_joke.gif";
	}
}
function closePopup() {
	btn = document.getElementById("btn_addBible");
	btn1 = document.getElementById("btn_addPoem");
	btn2 = document.getElementById("btn_addJoke");
	btn.src = "images/add_a_biblical_reference.gif";
	btn1.src = "images/add_a_poem.gif";
	btn2.src = "images/add_a_joke.gif";

	// clear the selected reference
	txt = document.getElementById("refSelected");
	txt.value = "";

	// reset the selections
	document.getElementById("refBibleSelector").value = "0";
	document.getElementById("refPoemSelector").value = "0";
	document.getElementById("refJokeSelector").value = "0";

	pop = document.getElementById("popup");
	pop.style.display = "none";
}
function centrePopUp() {
	var pop = document.getElementById("popup");
	pop.style.width = popWidth + "px";
	pop.style.height = popHeight + "px";

	var proposedLeft = (pageWidth - popWidth) / 2;
	if (proposedLeft < 0)
		proposedLeft = 0;

	var proposedTop = (WindowHeight() - popHeight) / 2;
	if (proposedTop < 0)
		proposedTop = 0;

	pop.style.top = "60px";
	//        pop.style.top = proposedTop + "px";   // option to centre vertically
	pop.style.left = proposedLeft + "px";
}
function WindowWidth() {
	if (self.innerWidth)
		return self.innerWidth;
	else if (document.body && document.body.clientWidth)
		return document.body.clientWidth;
	else
		return 0;
}

function WindowHeight() {
	if (self.innerHeight)
		return self.innerHeight;
	else if (document.body && document.body.clientHeight)
		return document.body.clientHeight;
	else
		return 0;
}

