// JavaScript Document

var book_namesLong = new Array('Genesis','Exodus','Leviticus','Numbers','Deuteronomy','Joshua','Judges','Ruth','1 Samuel','2 Samuel','1 Kings','2 Kings','1 Chronicles','2 Chronicles','Ezra','Nehemiah','Esther','Job','Psalms','Proverbs','Ecclesiastes','Song of Solomon','Isaiah','Jeremiah','Lamentations','Ezekiel','Daniel','Hosea','Joel','Amos','Obadiah','Jonah','Micah','Nahum','Habakkuk','Zephaniah','Haggai','Zechariah','Malachi','Matthew','Mark','Luke','John','Acts','Romans','1 Corinthians','2 Corinthians','Galatians','Ephesians','Philippians','Colossians','1 Thessalonians','2 Thessalonians','1 Timothy','2 Timothy','Titus','Philemon','Hebrews','James','1 Peter','2 Peter','1 John','2 John','3 John','Jude','Revelation');

var book_namesShort = new Array('ge','ex','le','nu','de','jos','jud','ru','1sa','2sa','1ki','2ki','1ch','2ch','ezr','ne','es','job','ps','pr','ec','so','isa','jer','la','eze','da','ho','joe','am','ob','jon','mic','na','hab','zep','hag','zec','mal','mt','mr','lu','joh','ac','ro','1co','2co','ga','eph','php','col','1th','2th','1ti','2ti','tit','phm','heb','jas','1pe','2pe','1jo','2jo','3jo','jude','re');

var chapter_count = new Array('50','40','27','36','34','24','21','4','31','24','22','25','29','36','10','13','10','42','150','31','12','8','66','52','5','48','12','14','3','9','1','4','7','3','3','3','2','14','4','28','16','24','21','28','16','16','13','5','6','4','4','5','3','6','4','3','1','13','5','5','3','5','1','1','1','22');

var ref_bk = ref_ch = old_ch = ref_vs = old_vs = 0;

/*
	reference_table - function to create a floating div used to create
		a verse reference to be inserted into the search box.
		
		qd	- query direction: forward or backward
		qt	- query type: book, chapter, verse, question, finished or remove
		qb	- query box id
		num	- current number being passed
*/

function reference_table(qd, qt, qb, num){

	var color_dark = '#666193';
	var color_medium = '#D6D7E7';
	var color_light = '#E7E3EF';
	var white = '#FFFFFF';
	var alt_num = num.replace(':', '').replace('-','');

	var query_box = document.getElementById(qb);
	current_qb = qb ;
	
	/*
		buildRef_div - function to create a div with a table listing the 
			books of the Bible.  Also included is a close button.
							
			qb - query box id
	*/

	_buildRef_div = function (qb) {

		/* Get information about where to place the box */
		var qb_locale = getObjectPosition(qb);

		/* Create the main div that will hold everything */
		var mDiv = document.createElement("Div");
			mDiv.style.position = 'absolute';
			mDiv.style.border = color_dark + ' solid 1px';
			mDiv.style.font = '600 10px arial,heletica,sans-serif';
			mDiv.style.top = (qb_locale.y + (qb_locale.z + 2)) + 'px';
			mDiv.style.left = qb_locale.x + "px";
			mDiv.style.height = 283 + 'px';
			mDiv.style.width = 500 + 'px';
			mDiv.style.padding = 3 + 'px';
			mDiv.style.backgroundColor = color_medium;
			mDiv.id = 'referenceTable';
			mDiv.style.zIndex = '100';

		/* Create the header DIV */
		var hDiv = document.createElement("Div");
			hDiv.style.width = 494 + 'px';
			hDiv.style.height = 20 + 'px';

		/*  Create the table to hold the header info */
		var hTbl = document.createElement("Table");
			hTbl.setAttribute('width', 100 + '%');
			hTbl.style.font = '400 10px arial,heletica,sans-serif';
			hTbl.style.textDecoration = 'none';
			hTbl.setAttribute('cellpadding', '0');
			hTbl.setAttribute('cellspacing', '0');
			hTbl.setAttribute('border', '0');

		/* Create table row */
		var hTR = hTbl.insertRow(0);
		
		/* Create "Reference" cell */
		var hTD1 = hTR.insertCell(0);
			hTD1.setAttribute('valign', 'middle');
			hTD1.setAttribute('align', 'right');
			hTD1.setAttribute('width', 14 + '%');
			hTD1.style.fontWeight = 600;
			hTD1.style.paddingRight = 3 + 'px';
			hTD1.innerHTML = 'Reference:';
		
		/* Create cell for reference data */
		var hTD2 = hTR.insertCell(1);
			hTD2.style.backgroundColor = color_medium;
				hTD2A = document.createElement("Input");
				hTD2A.type = 'text';
				hTD2A.setAttribute('id', 'cell_ref');
				hTD2A.style.border = '1px solid ' + color_dark;
				hTD2A.style.height = 17 + 'px';
				hTD2A.style.fontSize = 9 + 'px';
				hTD2A.style.padding = 0 + ' ' + 3 + 'px';
				hTD2A.style.width = 310 + 'px';
				hTD2A.style.color = '#770077';
				hTD2.appendChild(hTD2A);

		/* Create cell for control data */
		var hTD3 = hTR.insertCell(2);
			hTD3.setAttribute('valign', 'middle');
			hTD3.setAttribute('align', 'right');
			hTD3.setAttribute('id', 'cell_ctl');
			hTD3.setAttribute('width', 12 + '%');
			hTD3.style.borderRight = '1px solid ' + color_dark;
			hTD3.style.paddingRight = 5 + 'px';

		/* Create link for the back button */
			var hTD3A = document.createElement("A");
				hTD3A.setAttribute('href', 'javascript:void(null);');
				hTD3A.setAttribute('id', 'cell_ctrlLink');
				hTD3A.innerHTML = '<< Back';
				hTD3A.style.visibility = 'hidden';
				hTD3.appendChild(hTD3A);
		
		/* Create cell for control data */
		var hTD4 = hTR.insertCell(3);
			hTD4.setAttribute('valign', 'middle');
			hTD4.setAttribute('align', 'left');
			hTD4.setAttribute('id', 'cell_close');
			hTD4.setAttribute('width', 12 + '%');
			hTD4.style.paddingLeft = 5 + 'px';

		/* Create link for the close button */
			var hTD4A = document.createElement("A");
				hTD4A.setAttribute('href', 'javascript:void(null);');
				hTD4A.onclick = function () {reference_table('forward','remove','','');};
				hTD4A.innerHTML = 'Close Box';
				hTD4.appendChild(hTD4A);
		
		/* Create div to hold the main content */
		var cDiv = document.createElement("Div");
			cDiv.style.height = 261 + 'px';
			cDiv.style.width = 100 + '%';
			cDiv.style.border = color_dark + ' solid 1px';
			cDiv.style.backgroundColor = '#ffffff';
			cDiv.setAttribute('id', 'reference_builder');

		/* Append the table to the header div */
		hDiv.appendChild(hTbl);
		/* Append the header div to the main div */
		mDiv.appendChild(hDiv);
		/* Append the header div to the main div */
		mDiv.appendChild(cDiv);
		/* Append to the body */
		document.body.appendChild(mDiv);
	}
	
	/*
		_addTitle_row - function to adds a title row to the table

			tp - table pointer
			txt - title text
			ra 	- text alignment
			fs 	- font size
			fw 	- font weight
			cs 	- number of colums it spans
	*/
	
	_addTitle_row = function (tp, txt, ra, fs, fw, cs) {
		var oTR = tp.insertRow(tp.rows.length);
		var oTD = oTR.insertCell(0);
		if (isNaN(txt)) {
			oTD.style.fontWeight = fw;
			oTD.style.fontSize = fs + 'px';
			oTD.setAttribute('align', ra);
			oTD.colSpan = cs;
			oTD.innerHTML = txt;
		} else {
			oTD.style.height = 10 + 'px';
		}
	}

	/*
		_createBook_section - function to adds rows of books to the table
		
			tp - table pointer
			qb 	- query box id
			sn 	- book start number
			nr 	- number of rows
			nc 	- number of columns
			bm 	- max book number
	*/

	_createBook_section = function (tp, qb, sn, nr, nc, bm) {
		ref_ch = 0;
		ref_vs = 0;
		for(i = 1; i < nr; i++){
			var oTR = tp.insertRow(tp.rows.length);
			for(j = 0; j < nc; j++){
				if (sn == bm) {break;}
				var oTD= oTR.insertCell(j);
					oTD.innerHTML = book_namesLong[sn];
					oTD.style.padding = 1 + 'px ' + 4 + 'px';
					oTD.setAttribute('id', sn);
					oTD.onmouseover = function () {javascript:this.style.backgroundColor = color_light;};
					oTD.onmouseout = function () {javascript:this.style.backgroundColor= white;}; 
					oTD.onclick = function () { reference_table('forward', 'chapter', qb, this.id); };
					sn++;
			}
			if (sn == bm) {break;}
		}
	}

	/*
		_createChapter_section - function to adds rows of chapter numbers to the table
		
			tp - table pointer
			qb - query box title
			sn - book start number
	*/

	_createChapter_section = function (tp, qb) {
		var sn =  (old_ch > 1) ? old_ch + 1 : 1;
		var nr = (chapter_count[ref_bk] / 10) + 2;
		var tc = chapter_count[ref_bk];
		var spacer = (old_ch > 1) ? '-' : '';
		for(i = 1; i < nr; i++){
			var oTR= tp.insertRow(tp.rows.length);
			for(j = 0; j < 15; j++){
				var oTD= oTR.insertCell(j);
					oTD.innerHTML = spacer + sn;
					oTD.style.padding = 1 + 'px ' + 4 + 'px';
					oTD.onmouseover = function () {javascript:this.style.backgroundColor = color_light;};
					oTD.onmouseout = function () {javascript:this.style.backgroundColor= white;};
					oTD.onclick = function () { reference_table('forward', 'verse', qb, this.innerHTML); };
					sn++;
				if (sn > tc) {break;}
			}
			if (sn > tc) {break;}
		}
	}

	/*
		_createVerse_section - function to adds rows of verses to the table
		
			tp - table pointer
			qb 	- query box title
			sn 	- book start number
	*/

	_createVerse_section = function (tp, qb) {
		var url = 'http://new.studylight.org/cgi-bin/default/ref_builder.cgi?b=' + (ref_bk) + '&c=' + (ref_ch);
		var sn = (ref_vs > 1) ? ref_vs + 1 : 1;

		parseData = function() {
			var xmlDocument = this.req.responseXML;
			var spacer = (ref_vs > 1) ? '-' : ':';
			var vn = xmlDocument.getElementsByTagName('verses')[0].firstChild.data
			for(i = 1; i < (vn / 10) + 2; i++){
				var oTR = tp.insertRow(tp.rows.length);
				for(j = 0; j < 15; j++){
					var oTD= oTR.insertCell(j);
						oTD.innerHTML = spacer + sn;
						oTD.style.padding = 1 + 'px ' + 4 + 'px';
						oTD.onmouseover = function () {javascript:this.style.backgroundColor = color_light;};
						oTD.onmouseout = function () {javascript:this.style.backgroundColor= white;};
						oTD.onclick = function () {reference_table('forward', 'question', qb, this.innerHTML); };
						sn++;
					if (sn > vn) {break;}
				}
				if (sn > vn) {break;}
			}

			if (vn < 70) {
				/*  Let's ask what they want to do now */
				_addTitle_row(tp, '<hr width="80%">','center', 16, 600, 15);	

				_showQuestion_list(qt,tp,qb);
			}
		}
		new net.ContentLoader(url, parseData);
	}

	/*
		show_question - function to adds the question section to the table
		
			qt	- query type: book, chapter, verse, question or finished
			tp	- pointer to table div
			qb 	- query box id
			num	- current number being passed
	*/

	_showQuestion_list = function (qt,tp, qb, num){
		
		_addTitle_row(tp, '');
		_addTitle_row(tp, 'What would you like to do now?', 'center', 16, 600, 15);
		_addTitle_row(tp, '');
		_addTitle_row(tp, '<a href="javascript:void(null);" onClick="reference_table(\'stay\', \'finished\', \'' + qb + '\', \'\');">Finish and transfer the reference to the search box!</a>', 'center', 9, 400, 15);

		if (ref_ch > 0) {
			_addTitle_row(tp, '');
			_addTitle_row(tp, '<a href="javascript:void(null);" onClick="reference_table(\'forward\', \'book\', \'' + qb + '\', \'\');">Add another reference!</a>', 'center', 9, 400, 15);
		}

		if (ref_ch > 0 && (old_vs == 0 && ref_vs > 0)) {
			_addTitle_row(tp, '');
			_addTitle_row(tp, '<a href="javascript:void(null);" onClick="reference_table(\'stay\', \'verse\', \'' + qb + '\', \'' + ref_ch + '\');">Add a verse range within the same chapter!</a>', 'center', 9, 400, 15);

			_addTitle_row(tp, '');
			_addTitle_row(tp, '<a href="javascript:void(null);" onClick="reference_table(\'stay\', \'chapter\', \'' + qb + '\', \'' + ref_bk + '\');">Add a verse range from a different chapter within this book!</a>', 'center', 9, 400, 15);
		}

		if (ref_ch > 0 && ref_vs == 0) {
			_addTitle_row(tp, '');
			_addTitle_row(tp, '<a href="javascript:void(null);" onClick="reference_table(\'stay\', \'chapter\', \'' + qb + '\', \'' + ref_bk + '\');">Choose a different chapter!</a>', 'center', 9, 400, 15);
		}
	}
	
	/* 
		fixCtrl_link - function to format the "<< Back" link
	
			dt	- display type for the link: hide or show
			qt	- question type: book, chapter, verse, question or finished
			qb 	- query box id
			num	- current number being passed
	*/
	
	_fixCtrl_link = function (dt, qt, qb, num) {
		if (qt == 'chapter' && old_ch > 0) {
			ref_ch = old_ch ; old_ch = 0;
		}
		if (qt == 'verse' && old_vs > 0) {
			ref_vs = old_vs ; old_vs = 0;
		}
		var oLink = document.getElementById('cell_ctrlLink');
			oLink.onclick = function () { reference_table('backward', qt, qb, num); };
			oLink.style.display = 'block';
			oLink.style.visibility = (dt) ? 'visible' : 'hidden';
	}

	/*
		remove_table - function to remove the div holding the table from the document
	*/
	
	_remove_table = function() {
		ref_bk = old_ch = old_vs = ref_ch = ref_vs = 0;
		document.body.removeChild(document.getElementById('referenceTable'));
	}


	_fixReference = function(qt){
		var obj = document.getElementById("cell_ref");
		var hp = obj.value.lastIndexOf('-');
		var cp = obj.value.lastIndexOf(':');

		switch (qt) {
			case 'book':
				if (obj.value != '' && obj.value.lastIndexOf('; ') > -1) {
					var pos1 = obj.value.lastIndexOf('; ');
					obj.value = obj.value.substr(0, pos1);
				} else {
					obj.value = '';
					document.getElementById('cell_ctrlLink').style.visibility = 'hidden';
				}
				break;
			case 'chapter':
				if (obj.value.lastIndexOf(old_ch + '-' + ref_ch) > -1) {
					obj.value = obj.value.substr(0, hp);
					ref_ch = old_ch + 1;
					old_ch = 0;
				} else {
					var pos1 = obj.value.lastIndexOf(' ');
					obj.value = obj.value.substr(0, (pos1+1));
					ref_ch = 1;
				}
				break;
			case 'verse':
				if (obj.value.lastIndexOf(old_vs + '-' + ref_vs) > -1) {
					obj.value = obj.value.substr(0, hp);
					ref_vs = old_vs + 1;
					old_vs = 0;
				} else {
					obj.value = obj.value.substr(0, cp);
					ref_vs = 1;
				}
				break;
		}
	}

	/*  
		mostRecent_query - function to take apart the current query

			query	- query text being analyzed
	*/

	_mostRecent_query = function(query){
		countNum_char = function(cc,sc){
			var char_number = 0; 
			for (var i = 0; i < cc.length; i++) { 
				if (cc.substr(i,sc.length) == sc) { 
					char_number++; 
				}
			} 	
			return[char_number];
		}

		find_bookNumber = function(bk){
			var bn = 0;
			for(i = 0; i < 66; i++) {
				if (book_namesShort[i] == bk) {
					bn = i;
					break;
				} else if (book_namesLong[i] == bk) {
					bn = i;
					break;
				}
			}
			return[bn];
		}

		var pt = '';
		var query_pattern = new RegExp(/^[123]? ?[a-zA-Z]+ [0-9\:\-\,\;]+/);
		if (query.match(query_pattern)) {
			var search_pattern = new RegExp(/[a-zA-Z]/);
			var query_parts = query.split('; ');

			for(p = query_parts.length - 1; p > -1; p--) {
				var parts_pieces = query_parts[p].split(' ');
				for(r = parts_pieces.length - 1; r > -1; r--) {
					if (parts_pieces[r].match(search_pattern)) {
						if (ref_bk < 1) {
							ref_bk = find_bookNumber(parts_pieces[r]);
							pt = 'book';
						}
					} else {
						if (ref_ch < 1 || ref_vs < 1) {
							var hp = parts_pieces[r].lastIndexOf('-');
							var cp = parts_pieces[r].lastIndexOf(':');
							if (cp > hp) {
								var tmp = parts_pieces[r].split('-');
								var chvs = tmp[tmp.length - 1].split(':');
								ref_ch = chvs[0];
								ref_vs = chvs[1];
								pt = 'chapter';
								qt = 'question';
							} else {
								if (cp > -1) {
									if (hp > -1) {
										var tmp = parts_pieces[r].split('-');
										var chvs = tmp[tmp.length - 2].split(':');
										ref_ch = chvs[0];
										old_vs = chvs[1];
										ref_vs = tmp[1];
										pt = 'chapter';
										qt = 'question';
									} else {
										var tmp = parts_pieces[r].split(':');
										ref_ch = tmp[0];
										ref_vs = tmp[1];
										pt = 'chapter';
										qt = 'question';									
									}
								} else {
									if (hp > -1) {
										var tmp = parts_pieces[r].split('-');
										old_ch = tmp[0];
										ref_ch = tmp[1];
										pt = 'book';
										qt = 'question';
									} else {
										var tmp = parts_pieces[r].split('-');
										ref_ch = tmp[0];
										pt = 'book';
										qt = 'verse';									
									}
								}
							}
						}
					}
				}
				if (ref_bk > 0 && ref_ch > 0 && ref_vs > 0) { break ; }
			}
		} else {
			qt = 'book';
		}
		if (qt == 'question') { qd = 'stay'; }
		return[pt];
	}


	/*
		Main section of code:  This is the section 
	*/

	if (document.getElementById("referenceTable") == null) {
		_buildRef_div(qb);
		if (query_box.value != '') {
			var ref_parts = _mostRecent_query(query_box.value);
			if (qt != 'book') {
				document.getElementById('cell_ref').value = query_box.value;
			}
			
			_fixCtrl_link('TRUE', ref_parts[0]);
		}
	}

	if (qd == 'backward') {
		_fixReference(qt);
	}

	var cur_ref = document.getElementById('cell_ref');

	if (qt == 'finished') {
		query_box.value = cur_ref.value;
		_remove_table();
	} else if (qt == 'remove') {
		_remove_table();
	} else {
		document.getElementById("reference_builder").innerHTML = '';
		
		var cTbl = document.createElement("Table");
			cTbl.setAttribute('width', '100%');
			cTbl.style.font = '400 9px arial,helvetica,sans-serif';
			cTbl.style.cursor = 'pointer';

		switch (qt) {
			case 'book':
				_addTitle_row(cTbl, 'Old Testament', 'left', 12, 600, 6);
				_createBook_section(cTbl, qb, 0, 8, 6, 39);
				_addTitle_row(cTbl, '');
				_addTitle_row(cTbl, 'New Testament', 'left', 12, 600, 6);
				_createBook_section(cTbl, qb, 39, 6, 6, 66);
				break;

			case 'chapter':
				if (qd == 'forward') {
					cur_ref.value = (cur_ref.value != '') ? cur_ref.value + '; ' + book_namesShort[num] + ' ' : book_namesShort[num] + ' ';
					ref_bk = num;
				}
				if (ref_ch > 1) {
					old_ch = parseInt(ref_ch);
					ref_ch += 1;
					ref_vs = 1;
				} else {
					ref_ch = 1;
				}
				
				_fixCtrl_link('TRUE', 'book', qb, num);
				_addTitle_row(cTbl, 'Choose a chapter: ', 'left', 12, 600, 15);
				_createChapter_section(cTbl, qb);
				break;
				
			case 'verse':
				if (qd == 'forward') {
					cur_ref.value += num ;
					ref_ch = parseInt(alt_num);
				}
				
				_fixCtrl_link('TRUE', 'chapter', qb, num);
				_addTitle_row(cTbl, 'Choose a verse: ', 'left', 12, 600, 15);
				_createVerse_section(cTbl,qb);
				break;
				
			case 'question':
				if (qd == 'forward') {
					cur_ref.value += num;
					if (old_ch > 0) {
						ref_ch = parseInt(alt_num);
					} else {
						ref_vs = parseInt(alt_num);
					}
				}
				
				_fixCtrl_link('TRUE', 'verse', qb, num);
				_showQuestion_list(qt,cTbl,qb);
				break;
		}
		document.getElementById('reference_builder').appendChild(cTbl);
	}

}