/*
 * Copyright 2006 Christian Classics Ethereal Library
 */

/* contents of the old util-dom.js file */

/* add a function to be called for the body's onload event */
if(!self.addLoadEvent){
	function addLoadEvent(func)
	{
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			}
		}
	}
}

//initialize note visibility by preference
function initNote(id){
	if(preferences['notes'] == 'hidden')
		document.getElementById(id).style.display = 'none';
	else if(preferences['notes'] == 'foot'){
		var note = document.getElementById(id);
		var note2 = note.cloneNode(true);
		note.style.display = 'none';
		note.id = 'old_' + note.id;
		addLoadEvent(function(){addFooterNote(note2);});
	}
}

function addFooterNote(note){
	var nav = document.getElementById('book_navbar_bottom');
	if(!document.getElementById('footer_hr')){
		var foot_hr = document.createElement('hr');
		foot_hr.id = "footer_hr";
		nav.parentNode.insertBefore(foot_hr,nav);
	}else
		nav.parentNode.insertBefore(document.createElement('br'),nav);
	note.className='footer_note';
	note.childNodes[0].href='#fna'+note.id.substring(3);
	nav.parentNode.insertBefore(note,nav);
}

function goBible(type, book, fch, fv, tch, tv){
 	var url = "/ccel/bible/"+ preferences[type] +"."+ book +"."+ fch 
 		+".html?scrBook="+ book +"&scrCh="+ fch +"-"+ tch +"&scrV="+ 
 		fv +"-"+ tv;
 	if(goBCBNewWin(url)) //try bcb new window
 		document.location.href = url; //not in bcb: follow new url
 	return false;
}
function goBCBNewWin(url){
	if(bcb.length > 0){
 		window.open(url, "bcb_"+bcb);
 		return false;
 	}
 	return true;
}
function goBCBParam(url){
	if(bcb.length > 0){
 		var hashIndex = url.lastIndexOf('#');
 		var hash='';
 		if(hashIndex!=-1){
 			hash = url.substring(hashIndex);
 			url = url.substring(0,hashIndex);
 		}
 		var qIndex = url.indexOf('?');
 		if(qIndex == -1) //no query string
 			url += '?';
 		else
 			url += '&';
 		url += "bcb="+ bcb + hash;
	 	document.location.href = url;
 		return false;
 	}
 	return true;
}

//image rollover for toc plus/minus icons
function highlight(obj){
	var source=obj.src;
	var i=source.indexOf(".gif");
	if(source.indexOf("_hilite.gif")==-1 && i!=-1){
		source=source.substring(0,i);
		obj.src=source+"_hilite.gif";
	}
}
function unhighlight(obj){
	var source=obj.src;
	var i=source.indexOf("_hilite.gif");
	if(i!=-1){
		source=source.substring(0,i);
		obj.src=source+".gif";
	}
}

//this function displays or hides object t
//used for toggling footnotes (or jumping to for footer notes)
function toggle(t) {
	if(preferences['notes']=='foot'){
		var loc = document.location.href;
		if(loc.indexOf('#')!=-1)
			loc = loc.substring(0, loc.indexOf('#'));
		document.location.href = loc + '#'+t;
	}else{
		var x=document.getElementById(t);
		if (x.style.display != "none")
			x.style.display = "none";
		else
			x.style.display = "inline";
	}
}

//this function will page backward or forward with the press of
//an arrow key (in IE) or comma or dot (Netscape or IE)
//function handler(e) {
//	var k, shift;
//	if (navigator.appName.indexOf("Microsoft") != -1){
//		k = window.event.keyCode;
//		shift = window.event.shiftKey;
//	}else if(navigator.userAgent.indexOf("Firefox") != -1) {
//		k = e.keyCode;
//		shift = e.shiftKey;
//	}else{
//		k=e.which;
//		shift=false;
//	}
//	var link;
//	if(location.href.indexOf(".toc.html?") == -1 && location.href.indexOf(".toc.html") != -1) {
//		//on title page
//		if(shift && k == 38){ //up -> book info
//			link=document.links['bookInfo'];
//		}else if(k == 39){ //right->1st section
//			link=document.links['titlepage'];
//		}
//	}else if (k==37 || k==44 || k==188){
//		link=document.links['prevNav']; //prev of navbar
//	}else if (k==39 || k==46 || k==190 || k==13){
//		link=document.links['nextNav']; //next of navbar
//	}else if (shift && k==38) { //up ->toc
//		link=document.links['toc'];
//	}
//	if(link)
//		location.href = link.href;
//}
//
//document.onkeydown=handler;


//-------------------------------------------------------------
//Image zoom in/out script- by javascriptkit.com
//Visit JavaScript Kit (http://www.javascriptkit.com) for script
//Credit must stay intact for use

var zoomfactor=0.15 //Enter factor (0.05=5%)

function zoomhelper(originalW, originalH){ 
	if (parseInt(whatcache.style.width)>10&&parseInt(whatcache.style.height)>10){
		whatcache.style.width=parseInt(whatcache.style.width)+parseInt(whatcache.style.width)*zoomfactor*prefix; 
		whatcache.style.height=parseInt(whatcache.style.height)+parseInt(whatcache.style.height)*zoomfactor*prefix;
	}
}

function zoom(originalW, originalH, what, state){
	if (!document.all&&!document.getElementById)
		return;
	whatcache=eval("document.images."+what);
	if (parseInt(whatcache.style.width) > (originalW*3) && state=="in")
		return;
	if (parseInt(whatcache.style.width) < (originalW/3) && state=="out")
		return;
	prefix=(state=="in")? 1 : -1;
	
	if (whatcache.style.width==""||state=="restore"){
		whatcache.style.width=originalW;
		whatcache.style.height=originalH;
		if (state=="restore")
			return;
	}
	zoomhelper(originalW, originalH);
}

function clearzoom(){
	if (window.beginzoom)
		clearInterval(beginzoom);
}

function getCookie(NameOfCookie){
  if (document.cookie.length > 0){
    begin = document.cookie.indexOf(NameOfCookie+"=");
    if (begin != -1){
      begin += NameOfCookie.length+1;
      end = document.cookie.indexOf(";", begin);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(begin, end));
    }
  }
  return null;
}

/* code from the old  sidebar.js file */

/*
 * jph5, 2006-07-14
 */

// -- this is redundant (this code is duplicated at the top of the file) -- //
/* add a function to be called for the body's onload event */
//if (!self.addLoadEvent)
//{
//	// Only define addLoadEvent() if it hasn't already been defined
//	function addLoadEvent(func)
//	{
//	        var oldonload = window.onload;
//	        if (typeof window.onload != 'function') {
//	                window.onload = func;
//	        } else {
//	                window.onload = function() {
//	                        if (oldonload) {
//	                                oldonload();
//	                        }
//	                        func();
//	                }
//	        }
//	}
//}

function createResizeHandle()
{
	var resizehandle = document.createElement('td');
	resizehandle.id = 'resizehandle';
	resizehandle.style.cursor = 'e-resize';
	resizehandle.style.color = '#999';
	resizehandle.style.backgroundImage = 'url(/pix/resizeHandle.jpg)';
	resizehandle.style.width = '5px';
	resizehandle.title = 'Click and drag to resize area';
	if (resizehandle.addEventListener)
		resizehandle.addEventListener("mousedown", downHandler, true);
	else if (resizehandle.attachEvent)
		resizehandle.attachEvent("onmousedown", downHandler);
	resizehandle.appendChild(document.createTextNode('.'));
	var sidebarleft = document.getElementById('sidebar-left');
	sidebarleft.parentNode.insertBefore(resizehandle, sidebarleft.nextSibling);

	function downHandler(event)
	{
		beginDrag(resizehandle, event);
	}
}

function beginDrag(element, downevent)
{
	var sidebarleft = document.getElementById('sidebar-left');
	var tocdiv = document.getElementById('tocdiv');
	var sidebarorigwidth = parseInt(sidebarleft.offsetWidth);
	var tocdivorigwidth = parseInt(tocdiv.offsetWidth);
	var startX = downevent.clientX;
	if (document.addEventListener)
	{
		document.addEventListener("mousemove", moveHandler, true);
		document.addEventListener("mouseup", upHandler, true);
	}
	else if (document.attachEvent)
	{
		document.attachEvent("onmousemove", moveHandler);
		document.attachEvent("onmouseup", upHandler);
	}

	if (downevent.stopPropagation)
		downevent.stopPropagation();
	else
		downevent.cancelBubble = true;
	if (downevent.preventDefault)
		downevent.preventDefault();
	else
		downevent.returnValue = false;

	function moveHandler(event)
	{
		var deltaX = event.clientX - startX;
		var width = sidebarorigwidth + deltaX;
		var tocdivwidth = tocdivorigwidth + deltaX;
		if (width > 0)
			sidebarleft.style.width = width + 'px';
		if (tocdivwidth > 0)
			tocdiv.style.width = tocdivwidth + 'px';
		if (event.stopPropagation)
			event.stopPropagation();
		else
			event.cancelBubble = true;
	}

	function upHandler(event)
	{
		if (document.removeEventListener)
		{
			document.removeEventListener("mouseup", upHandler, true);
			document.removeEventListener("mousemove", moveHandler, true);
		}
		else if (document.detachEvent)
		{
			document.detachEvent("onmouseup", upHandler);
			document.detachEvent("onmousemove", moveHandler);
		}
		if (event.stopPropagation)
			event.stopPropagation();
		else
			event.cancelBubble = true;
	}
}

//image rollover for toc plus/minus icons
function highlight(obj){
	var source=obj.src;
	var i=source.indexOf(".gif");
	if(source.indexOf("_hilite.gif")==-1 && i!=-1){
		source=source.substring(0,i);
		obj.src=source+"_hilite.gif";
	}
}
function unhighlight(obj){
	var source=obj.src;
	var i=source.indexOf("_hilite.gif");
	if(i!=-1){
		source=source.substring(0,i);
		obj.src=source+".gif";
	}
}

function t(div,pic) {
  var d, p;
  if (document.getElementById) { // DOM-compliant browsers
    d=document.getElementById(div);
    p=document.getElementById(pic);
  }
  if (d.style.display == "block") {
    d.style.display="none";
    p.src="/pix/shut_hilite.gif";
  } else {
    d.style.display="block";
    p.src="/pix/open_hilite.gif";
  }
}

function expand_subsection()
{
	if (document.getElementById('book_section_id'))
	{
		var id = document.getElementById('book_section_id').name;
		if (document.getElementById('toc'+id))
		{
			var elem = document.getElementById('toc'+id);
			if (elem.nextSibling && elem.nextSibling.nodeName.toLowerCase() == 'div' && elem.nextSibling.style.display != 'block')
			{
				var div_id = elem.nextSibling.id.substr(1);
				t('d'+div_id, 'p'+div_id);
				if (document.getElementById('p'+div_id))
					unhighlight(document.getElementById('p'+div_id));
			}
		}
	}

}

function expand_toc()
{
	if (document.getElementById('book_section_id'))
	{
		var id = document.getElementById('book_section_id').name;
		if (document.getElementById('toc'+id))
		{
			var elem = document.getElementById('toc'+id);
			elem.className = elem.className + ' toc_selected_section';
			_expand_toc(elem.parentNode);
		}
	}
}

function _expand_toc(div_elem)
{
	if (div_elem.style.display != 'none')
	{
		// Base case
		return;
	}

	// Continue recursively up the tree
	var id = div_elem.id.substr(1);
	t('d'+id, 'p'+id);
	if (document.getElementById('p'+id))
		unhighlight(document.getElementById('p'+id));

	_expand_toc(div_elem.parentNode);
}

/* code from the old highlight.js file */

//Handles highlighting of search text and scripture links based off of parameters

function highlightScripture(book, fch,fv, tch,tv){
	if(isNaN(fch)) fch=0;
	if(isNaN(fv)) fv=0;
	if(isNaN(tch)) tch=fch;
	if(isNaN(tv)) tv=fv;
	var arr=document.links;//first highlight the SCRIPREF anchors
	var needToPlaceAnchor=true;
	for(var i=0; i<arr.length; i++){
		if(arr[i].name){
			var parsed=arr[i].name.split(';');
			for(var j=0; j<parsed.length; j++){
				if(parsed[j].length<1)
					break;
				var scr=parsed[j].toLowerCase().split('_');
				for(var k=2; k<scr.length; k++)
					scr[k]=parseInt(scr[k]);
				//0=trans, 1=bk, 2=fc, 3=fv, 4=tc, 5=tv
				if(!scr[4] || scr[4]==0)
					scr[4]=scr[2];
				if(!scr[5] || scr[5]==0)
					scr[5]=scr[3];
				if(book.toLowerCase()==scr[1] && 
					(fch==0 || (fch>=scr[2] && tch<=scr[4])) && 
					(fv==0 || ((fch!=scr[2] || fv<=scr[3]) && (tch!=scr[4] || tv>=scr[5])))){
						arr[i].className="scrRefHighlight";
						arr[i].style.backgroundColor="red";
						arr[i].style.color="white";
						if(needToPlaceAnchor){
							insertAnchorAt(arr[i]);
							needToPlaceAnchor=false;
						}
				}
			}
		}
	}
	book = book.replace(/1/,"i").replace(/2/,"ii").replace(/3/,"iii").replace(/4/,"iv");
	var scrStart=book+"."+fch+"."+fv;
	var scrEnd=book+"."+tch+"."+(tv+1);
	var start=document.getElementById(scrStart);
	if(start){
		insertAnchorAt(start);
		var end=document.getElementById(scrEnd);
		if(!end){
			end=document.getElementById("noteBottom");
			if(!end)
				end=document.getElementById("book_navbar_bottom");
		}
		highlightUp(start.parentNode, start, end, null); //highlights the SCRIPTURE tag range
	}
}
function highlightUp(current, startingPlace, end, searchText){ //return true if find end
	if(!current) return false;
	if(current==end) return true;
	var i;
	for(i=0; current.childNodes[i]!=startingPlace; i++);
	for(i++; i<current.childNodes.length; i++){
		if(highlightDown(current.childNodes[i],end, searchText)==-1)
			return true;
	}
	return highlightUp(current.parentNode, current, end, searchText); //continue higher
}
function highlightDown(current, end, searchText){
	if(!current) return false;
	if(current.nodeValue){
		if(searchText)
			return textHighlightNode(current, searchText);
		return scriptureHighlightNode(current);
	}
	if(current==end) return -1;
	var temp;
	for(var i=0; i<current.childNodes.length; i++){
		temp = highlightDown(current.childNodes[i], end, searchText);
		i+=temp;
		if(temp==-1)
			return -1;
	}
	return 0;
}

function scriptureHighlightNode(current){
	var wrapper = document.createElement('span');
	var text=document.createTextNode(current.nodeValue);
	wrapper.appendChild(text);
	wrapper.style.backgroundColor='#fff3b0';
	current.parentNode.replaceChild(wrapper,current);
	return 0;
}

//returns offset from current to continue
function textHighlightNode(current, text){
	var nodeText = current.nodeValue.replace(/[\n\r]/g," ");
	var i = nodeText.toLowerCase().indexOf(text);
	if(i!=-1 && (i==0 || " \t\b\"'\n\r".indexOf(nodeText.charAt(i-1))!=-1)){
		var before = document.createTextNode(nodeText.substring(0,i));
		var highlight = document.createElement("span");
		highlight.id = "searchHighlight";
		highlight.style.backgroundColor='yellow';
		var highlightText = document.createTextNode(nodeText.substring(i,i+text.length));
		highlight.appendChild(highlightText);
		var after = document.createTextNode(nodeText.substring(i+text.length));
		current.parentNode.insertBefore(before, current);
		current.parentNode.insertBefore(highlight, current);
		current.parentNode.replaceChild(after,current);
		return 1;
	}
	return 0;
	
}

function debug(lcBodyText){
	var x;
	for(x=0; x+1000<lcBodyText.length; x+=1000)
  	  alert(lcBodyText.substring(x,x+1000));
    alert(lcBodyText.substring(x));
}

function highlightSearch() {
	info = getBookInfoFromUrl();
	return highlightSearchTerms( info[0], info[1], info[2], info[3] );
}

/* Extract information about the search text and/or scripture reference
 *  from the request URL
 * Returns an array of the info with the following indexes:
 *  0 - search text
 *  1 - book
 *  2 - chapter
 *  3 - verse
 */
function getBookInfoFromUrl(){
	var url = document.location.href;
	var index = url.indexOf('?');
	var searchText="";
	var book="",ch="",v="";
	if(index!=-1){
		url=url.substring(index+1);
		index=url.indexOf('#');
		if(index!=-1)
			url=url.substring(0,index);
		url+='&';
		index=url.indexOf("highlight=");
		if(index!=-1){
			var index2=url.indexOf('&',index);
			searchText=url.substring(index+10,index2);
		}
		index=url.indexOf("scrBook=");
		if(index!=-1){
			var index2=url.indexOf('&',index);
			book=url.substring(index+8,index2);
			index=url.indexOf("scrCh=");
			if(index!=-1){
				index2=url.indexOf('&',index);
				ch=url.substring(index+6,index2);
				index=url.indexOf("scrV=");
				if(index!=-1){
					index2=url.indexOf('&',index);
					v=url.substring(index+5,index2);
				}
			}
		}
	}
	if(!book && window.location.hash.length>0){
		var scr = window.location.hash.split(/\./);
		if(scr.length==3){
			book=scr[0].substring(1);
			ch=scr[1];
			v=scr[2];
		}
	}
	return new Array(searchText, book, ch, v);
}

function highlightSearchTerms(searchText, scrBk,scrCh,scrV)
{	
	if (!searchText && !scrBk && !scrCh && !scrV)
    return true;
  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    return false;
  }
  if(scrBk){
  	var books=scrBk.split(",");
  	var chs=scrCh.split(",");
  	var vs=scrV.split(",");
  	for(var i=0; i<books.length; i++){
  		var ch = chs[i].split("-");
  		var v = vs[i].split("-");
  		highlightScripture(books[i],parseInt(ch[0]),parseInt(v[0]),
  			ch[1]?parseInt(ch[1]):NaN,v[1]?parseInt(v[1]):NaN);
  	}
  }
  if(searchText){
  	searchText = decodeURI(searchText);
	  searchArray = searchText.split(",");
	  var start = document.getElementById("book_navbar_top");
	  var end = document.getElementById("book_navbar_bottom");
	  var color = "yellow";
	  for (var i = 0; i < searchArray.length; i++) {
	    if(searchArray[i].length > 0 && start)
	    	highlightUp(start.parentNode, start, end, searchArray[i]);
	  }
	  var insertNode=document.getElementById("searchHighlight");
	  if(insertNode)
		insertAnchorAt(insertNode);
  }
  
  //jump to the highlight anchor
  if(!window.location.hash || window.location.hash.length <1){
  	window.location.hash='#highlight';
  }else{
  	if ( window.location.hash != '' )
		window.location.hash=window.location.hash;
  }
  return true;
}

function insertAnchorAt(node){
	var highlightAnchor=document.createElement('A');
	highlightAnchor.href="#highlight";
	highlightAnchor.id="highlight";
	highlightAnchor.name='highlight';
	var insertNode=getLinkNodeIsIn(node);
	if(insertNode)
		node=insertNode;
	node.parentNode.insertBefore(highlightAnchor, node);
}
function getLinkNodeIsIn(node){
	while(node && node.className && node.className!='a' && node.className!='A')
		node=node.parentNode;
	return node;
}


