/* All scripts to be triggered onload should be referenced here. */

window.onload = function() {
	findInfos(); 
	findLinks(); 
	findLookItUps();
	findPops();
	findHighlighters();
	findStructure();
	updateVerseNumber();

//Submit form elements via enter in IE
//	document.getElementById("lookup_chapter").onkeyup = bibleSearchSubmit;
//	document.getElementById("lookup_verse").onkeyup = bibleSearchSubmit;
	var forms = document.getElementsByTagName('form');
	for (var i=0;i < forms.length;i++) {
		var inputs = forms[i].getElementsByTagName('input');
		for (var j=0;j < inputs.length;j++) {
			addInputSubmitEvent(forms[i], inputs[j]);
		}
	}
}


/*	Main Navigation Drop Down Menus -- uses Suckerfish	*/
/*  Drop down navigation state for IE6					*/
sfHover = function() {
	var sfEls = document.getElementById("mainNav").getElementsByTagName("LI");
	for (var i=0; i < sfEls.length; i++) {
		sfEls[i].onmouseout=function() { this.className = this.className.replace(new RegExp(" sfhover\\b"), ""); }
		sfEls[i].onmouseover=function() { this.className += " sfhover"; }
	}
}
isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
if(window.attachEvent && isIE6) { window.attachEvent("onload", sfHover); }


/*	"What is This?" popups

	Popup with explanatory text appears when the user rolls over a question mark icon. 
	
	For each instance of a "What's This", create a span classed "whatsThis".  Inside this span, 
	include some markup (the first child element, whatever it may be, will receive an
	onmouseover event) followed by a div classed "moreInfo" that 
	contains the info to be revealed on rollover.

	E.g.

		<span class="whatsThis">
			<img alt="What is This?" src="images/ico-help.gif" />
			<div class="moreInfo">
				Morbi pretium orci iaculis ligula. Nulla facilisi. 
			</div>
		</span>

	Also required is a div with id "moreInfo" placed anywhere on the page (typically at the 
	bottom), containing a blank <span> tag.

	E.g.

		<div id="moreInfo"><span> </span></div>

	If javascript is disabled, nothing happens onclick.

*/


function findInfos() {
	var mitt = document.getElementById('moreInfo');
	var infos = myGetElementsByClass('whatsThis',null,'span');
	for ( var x = 0; x < infos.length; x++ ) {
		var a = getFirstChildElement (infos[x]);
		if (a == null) {
			continue;
		}

		a.onmouseover = function() { openInfo(this); }
		a.onmouseout = function() {
			mitt.style.visibility = "hidden";
			mitt.getElementsByTagName('span')[0].innerHTML = "";
		}
	}
}

function getFirstChildElement (node)
{
  var k = node.firstChild;
  // skip over non-element children - text I think
  while (k && k.tagName == null)
  	k = k.nextSibling;
  return k;
}

function openInfo(what) {
	var coors = findPos(what);
	var p = what.parentNode;
	var b = myGetElementsByClass('moreInfo',p,'span');
	if (b == null || b.length == 0)
		return;
	b = b[0];
	var mitt = document.getElementById('moreInfo');
	mitt.getElementsByTagName('span')[0].innerHTML = b.innerHTML;

	//test for IE6 specific scenario:
	var ie6test = /msie|MSIE 6/.test(navigator.userAgent);
	var parentContainer = what.parentNode.parentNode.parentNode.parentNode.id;
	if(ie6test && (parentContainer == "bibletools")) {
		mitt.style.top = "3px";
		mitt.style.left = coors[0] + "px";
	}
	else {
		mitt.style.top = ( coors[1] - mitt.offsetHeight + 50 ) + "px";
		mitt.style.left = ( coors[0] + what.offsetWidth ) + "px";
	}
	
	mitt.style.zIndex = "1000";
	mitt.style.visibility = "visible";
}


/*	Show more/Show Less Links

Used in the Related Links section of Article Pages when there are 10 or more links available. 
Default state is to show first 9 links with a 'show more' link at the end. When the user clicks 
the link, all links are exposed with a 'show less' link at the end. When the user clicks 
'show less', the list returns to its original state.

For each instance of a set of sibling lists classed "first_batch" and "last_batch", include a 
single link classed "more" at the end of the first_batch and a link classed "less" at the end 
of the last_batch.  

If javascript is disabled, no more/less links will appear, but both sets of links will appear 
fully expanded.
	
*/

function findLinks() {
  var batch1 = myGetElementsByClass('first_batch',null,'ul');
  for ( var x = 0; x < batch1.length; x++ ) {
    var parent = batch1[x].parentNode;
    var batch2 = myGetElementsByClass('last_batch',parent,'ul');
    for (var y = 0; y < batch2.length; y++) {
      var item = batch2[y];
      if ( item )
        item.style.display = "none";
    }

    var moreItems = myGetElementsByClass('more',batch1[x],'li');
    for (var i = 0; i < moreItems.length; i++) {
      var moreItem = moreItems[i];
      if (moreItem && moreItem.style) {
        moreItem.style.display = "block";
        var moreLink = moreItem.getElementsByTagName('a')[0];
        if (moreLink) {
          moreLink.onclick = function() {
            for (var i=0; i < batch2.length; i++)
              batch2[i].style.display = "block";
            for (var i=0; i < moreItems.length; i++)
              moreItems[i].style.display = "none";
            return false;
          }
        }
      }
    }

    var lessItems = myGetElementsByClass('less',batch2[y],'li');
    for (var i = 0; i < lessItems.length; i++) {
      var lessItem = lessItems[i];
      if (lessItem && lessItem.style) {
        lessItem.style.display = "block";
        var lessLink = lessItem.getElementsByTagName('a')[0];
        if (lessLink) {
          lessLink.onclick = function() {
            for (var i=0; i < batch2.length; i++)
              batch2[i].style.display = "none";
            for (var i=0; i < moreItems.length; i++) {
              moreItems[i].style.display = "block";
              moreItems[i].parentNode.style.display = "block";
            }
            return false;
          }
        }
      }
    }
  }
}

/*	Look It Up

	The user can highlight any word and run quick search on it by clicking the 'look it up' link. 
	
	Class each button that should launch the "search selection" function with "lookItUp".

	If javascript is disabled, nothing happens onclick.
	
*/

function selectSearch() {
	var txt = '';
	var foundIn = '';
	if (window.getSelection)
	{
		txt = window.getSelection();
		foundIn = 'window.getSelection()';
	}
	else if (document.getSelection)
	{
		txt = document.getSelection();
		foundIn = 'document.getSelection()';
	}
	else if (document.selection)
	{
		txt = document.selection.createRange().text;
		foundIn = 'document.selection.createRange()';
	}
	if (txt == '') {
		alert ("Highlight any word or phrase and click the button to begin a new search.");
		return;
	}

	f = document.getElementById("searchFormForm");
	document.getElementById("query_field").value = "\"" + txt + "\"";
	f.submit();
}

function findLookItUps() {
	var LIUs = myGetElementsByClass('lookItUp',null,'a');
	for ( var x = 0; x < LIUs.length; x++ ) {
		LIUs[x].onmousedown = function() { selectSearch(); return false }
	}
}


/*	Popup windows script

	Links intended to launch popups should be classed "popup" and given a target of "blank".  
	Supply an href for the link to be opened, as you would a normal link.  If you'd like the 
	new window to have a name, include a title.

	E.g.

		<a class="popup" href="popup.html" target="_blank" title="Print">Print</a>

	The script will launch a 700x600 window with no tool or menu bars, but with the ability to 
	be resized and scrolled.

	If javascript is disabled, the link will launch in a new window.
	
*/

function findPops(){
	var a = myGetElementsByClass('popup',null,'a');
	for (var i = 0; i < a.length; i++) {
		a[i].onclick = function() {
			var url = this.href;
			var name = this.getAttribute('title');
			var width = "700";
			var height = "600";
			return pop(url,name,width,height);
		}
	}
}

function pop(url,name,width,height) {
	var newwindow = window.open(url,name,'height='+height+',width='+width+',menubar=yes,toolbar=no,resizable=yes,scrollbars=yes');
	if (window.focus) {newwindow.focus()}
	return false;
}

function launchDC() {
	return pop('/DateConverter.html','Converter','550','320');
}

var helpUrls = {
  "/Public/Login.html" : "help3.htm",
  "/MainSearch.html" : "help5_3.htm",
  "/AdvancedSearch.html" : "help5_4.htm",
  "/ImageSearch.html" : "help5_5.htm",
  "/BibSearch.html" : "help5_6.htm",
  "/Timeline.html" : "help8.htm"
};

function launchHelp() {
  var loc = location.pathname;
    var url = helpUrls[loc];
    if (url)
      return pop("/Public/Help/" + url,'Help','790','590');

    if (loc.indexOf("/Public/") >= 0)
      url = "help2.htm";	
	else if (loc.indexOf("/search") >= 0)
	  url = "help5_7.htm";
    else if (loc.indexOf("browse") >= 0)
      url = "help6.htm";
    else if (loc.indexOf("/book/") >= 0)
      url = "help7.htm";
    else if (loc.indexOf("/resource/") >= 0)
      url = "help9.htm";
    else
      url = "help1.htm";
    return pop("/Public/Help/" + url,'Help','790','590');
}

/*  Highlight On/Off

	Controls the style of search result hit text (e.g. background color) and toggles this style 
	on/off when clicked.

	This script toggles the class of search hits between "hit" and "miss".  To ascribe toggling 
	function to an object, class one span "on" and one "off" and class their parent element 
	"rtHilight".

	If javascript is disabled, nothing happens onclick.
	
*/

function findHighlighters() {
	var highlight = myGetElementsByClass('rtHilight',null,'li');
	for ( var x = 0; x < highlight.length; x++ ) {
		myGetElementsByClass('on',highlight[x],'a')[0].onclick = highlightOn;
		myGetElementsByClass('off',highlight[x],'a')[0].onclick = highlightOff;
	}
}
function highlightOn() {
	this.className = "on highlight_selected";
	GetParentByTagName("li", this).getElementsByTagName("a")[1].className = "off";

	var hits = myGetElementsByClass('miss',null,'a');
	for (var i = 0; i < hits.length; i++) {
		hits[i].className = "hit";
	}
	return false;
}
function highlightOff() {
	this.className = "off highlight_selected";
	GetParentByTagName("li", this).getElementsByTagName("a")[0].className = "on";

	var hits = myGetElementsByClass('hit',null,'a');
	for (var i = 0; i < hits.length; i++) {
		hits[i].className = "miss";
	}
	return false;
}

/* Tools used in the other scripts */

function myGetElementsByClass(searchClass,node,tag) {
  var classElements = new Array();
  if (node == null)
    node = document;
  if (tag == null)
    tag = '*';
  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;
}

/* +/- Show/Hide All for Results */

var subs_array = new Array("sub1","sub2","sub3");// Put the id's of your hidden divs in this array

function displaySubs(the_sub){
	 if (document.getElementById(the_sub).style.display==""){
	   document.getElementById(the_sub).style.display = "none";return
  }
  for (i=0;i<subs_array.length;i++){
	   var my_sub = document.getElementById(subs_array[i]);
	   my_sub.style.display = "none";
	 }
  document.getElementById(the_sub).style.display = "";
}





/* Expandable Lists */

function findStructure() {
	if ( myGetElementsByClass('filter_list') != null ) {					// first see if we even have a nav structure to find.  If so...
		var togglers = myGetElementsByClass('toggle',null,'a');  			// find all of our toggle links

		if(togglers.length) {
			if(GetParentByTagName("fieldset", togglers[0]).className.indexOf("donotcollapse") >= 0) {	 // DON'T COLLAPSE ANYTHING!
				return;
			}
		}

		var toggle = function() { toggleStructure(this); }        			// define the toggle function
		for ( var i = 0; i < togglers.length; i++ ) {
			var mom = togglers[i].parentNode;								// find the LI that contains this toggle
			var expandMom = mom.className.indexOf("openlist") >= 0 ||
			     hasCheckedDescendant(mom); 
			if (expandMom) {												// check if it should be opened
				togglers[i].className = "open";
				var sisters = mom.getElementsByTagName('ul');				// find all ULs that follow this toggle
				for (var x = 0; x < sisters.length; x++) {
					sisters[0].style.display = "block";						// show the first UL that follows this toggle
			    }
			}
			else {
				var sisters = mom.getElementsByTagName('ul');				// find all ULs that follow this toggle
				for (var x = 0; x < sisters.length; x++) {
					sisters[0].style.display = "none";						// hide the first UL that follows this toggle
			    }
			}
			togglers[i].onclick = toggle;						  			// assign toggle function to toggle links' onClick
		}
	} else return;
}

function hasCheckedDescendant(e) {
	try {
		var childUL = e.childNodes[3];
		var inputs = childUL.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].checked) { return true; }
		}
			return false;
	}
	catch(err) { }
}

function toggleStructure(what) {

    var obj;

    if ( typeof (what) == "string" )
	obj = myGetElementById(what);
    else
	obj = what;
	
	var mom = obj.parentNode;								  // find the LI that contains this toggle
	var sisters = mom.getElementsByTagName('ul');			  // find all ULs that follow this toggle

	for (var x = 0; x < sisters.length; x++) {
		var sister = sisters[0];			  				  // find the first UL that follows this toggle
    }

    if ( sister.style.display=="block" ) {                    // if it's on, turn if off
		sister.style.display="none";
		obj.className="closed";
		this.className="toggle closed";
	} else {             								      // if it's off, turn if on
		sister.style.display="block";
		obj.className="open";
		this.className="toggle open";
	}
}


function showPriorCommentary() {
	var prioria = document.getElementById('prior_commentary');
	if(prioria.style.display == "block") {			// if it's on, turn if off
		prioria.style.display = "none";
		document.getElementById('prior_commentary_toggle').className = "closed";
	}
	else {											// if it's off, turn if on
		prioria.style.display = "block";
		document.getElementById('prior_commentary_toggle').className = "open";
	}
}

/* First principles */

var isIE = (document.getElementById && document.all)?true:false;
var isNS4 = (document.layers)?true:false;
var isNS6 = (document.getElementById && !document.all)?true:false;


function myGetElementById (id)
{
    if ( isIE )
    {
	var str = "document.all('" + id + "')";
	var o = eval(str);
	return o;
    }

    return document.getElementById(id);
}

function showLookup (show)
{

  var lookUp = myGetElementById ('lookUp');
  var topNav = myGetElementById ('topNav');
  var searchForm = myGetElementById ('searchForm');

  if (show) 
    {
      lookUp.style.visibility = 'visible';
      topNav.style.visibility = 'hidden';
      searchForm.style.visibility = 'hidden';
    } 

  else 
    {
      lookUp.style.visibility = 'hidden';
      topNav.style.visibility = 'visible';
      searchForm.style.visibility = 'visible';
    }
}

function clearAllFormElements(form) {
	for (var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if (e.tagName == 'INPUT') {
			var type = e.getAttribute ('type');
			if (type == 'text') { e.value = ''; }
			else if (type == 'checkbox' || type == 'radio') {
				e.checked = false; //e.getAttribute('checked') ? true : false;
			}
		}
		else if (e.tagName == 'SELECT') {
			// TODO - handle multiselect
			e.selectedIndex = -1;
		}
	}
}


/* palette */

var paletteElement;

function openPalette(ename) {
	var trigger = document.getElementById('open_palette');
	var palette = document.getElementById('charPalette_wrapper');
    paletteElement = document.getElementById(ename);
	var inputW = paletteElement.offsetWidth;
	var inputH = paletteElement.offsetHeight;
	var coors = findPos(trigger);
	trigger.style.display = "none";
	palette.style.width = ( inputW ) + "px";
	palette.style.display = "block";
}

function closePalette() {
	var trigger = document.getElementById('open_palette');
	var palette = document.getElementById('charPalette_wrapper');
	palette.style.display = "none";
	trigger.style.display = "block";
}


function findPos(obj) {
	var isPopup = false;
	if (obj.childNodes[0].src) {
		if(obj.childNodes[0].src.indexOf("ico-help.gif") > -1) { isPopup = true; }
	}

	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	if(isPopup) {
		var viewportwidth;
		// All browsers 'cept IE6
		if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerWidth; }
		// IE6
		else { viewportwidth = document.documentElement.clientWidth; }
		if((viewportwidth - 788)/2 < 300 && curleft > 485) { curleft -= 300; }
	}

	return [curleft,curtop];
}

function click_char(c){
    insertAtCursor(paletteElement,c);
}

function charPalette_up(){
 document.getElementById("charPalette_lower").style.display="none";
 document.getElementById("charPalette_upper").style.display="block";

}
function charPalette_down(){
 document.getElementById("charPalette_upper").style.display="none";
 document.getElementById("charPalette_lower").style.display="block";
}


/** 
from alexking.org
*/
function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
	myField.focus();
	sel = document.selection.createRange();
	sel.text = myValue;
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == '0') {
	var startPos = myField.selectionStart;
	var endPos = myField.selectionEnd;
	myField.value = myField.value.substring(0, startPos)
	    + myValue
	    + myField.value.substring(endPos, myField.value.length);
    } else {
	myField.value += myValue;
    }
}

//IE6 submit works on this function
//function bibleSearchSubmit(variable) {
//	var keyCode;
//	if(window.event) { keyCode = window.event.keyCode; } //IE
//	else if(variable) { keyCode = variable.which; } //Other
//	if(keyCode == 13) { document.bibleLookupPopup.submit() } //13 = enter key
//}
function addInputSubmitEvent(form, input) {
	input.onkeydown = function(e) {
		e = e || window.event;
		if (e.keyCode == 13) {
			form.submit();
			return false;
		}
	};
}


function updateVerseNumber(){
	if (document.getElementById('bibletools') != null && document.location.hash.substr(0,6) == '#verse'){
		document.forms['bibleLookupNav'].elements['verse'].value = document.location.hash.substr(6);
	}
}

function GetParentByTagName(parentTagName, childElementObj) {
	var parent = childElementObj.parentNode;
	while(parent.tagName.toLowerCase() != parentTagName.toLowerCase() && parent.tagName.toLowerCase() != "body") {
		parent = parent.parentNode;
	}
	return parent;
}

//dreamweaver native function for popups
function MM_openBrWindow(theURL,winName,features) { //v2.0
   window.open(theURL,winName,features);
}