$(function() {

	$("html.no-js").removeClass("no-js");

	if($("#query_field").val() === "") $("#query_field").val("Search Oxford Islamic Studies");
	$("#query_field").focus(function() { if(this.value === "Search Oxford Islamic Studies") this.value = ""; });
	$("#query_field").blur(function() { if(this.value === "") this.value = "Search Oxford Islamic Studies"; });

	$("#mainNav > ul > li").mouseenter(function(evt) {
		var subnav = $(this).children(".subnav");
		var height = subnav.height();
		if(subnav.parent("li").hasClass("resources")) {
			subnav.css({ left:"auto", right:"0", height:"0", overflow:"hidden" });
		}
		else {
			subnav.css({ left:"0", height:"0", overflow:"hidden" });
		}
		subnav.animate({
			height:height
		}, 300);
	});
	$("#mainNav > ul > li").mouseleave(function(evt) {
		var subnav = $(this).children(".subnav");
		subnav.css({ left:"-999em", height:"auto", overflow:"visible" });
	});

	findInfos(); 
	findLinks(); 
	findLookItUps();
	findPops();
	findHighlighters();
	findStructure();

});

/*	"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.png" />
			<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');
	//	alert('found infos' + infos);
	for ( var x = 0; x < infos.length; x++ ) {
		var a = getFirstChildElement (infos[x]);
		if (a == null) {
			//alert (x.innerHTML + " has no child?");
			continue;
		}
		// alert (a + a.tagName + ": " + a.innerHTML);

		//alert (b + b.className);
		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;
	mitt.style.top = ( coors[1] - mitt.offsetHeight + 50 ) + "px";
	mitt.style.left = ( coors[0] + what.offsetWidth ) + "px";
	//mitt.style.top = "100px";
	//mitt.style.left = "100px";
	mitt.style.zIndex = "99999999999999";
	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/editor_letter.html" : "help2.htm",
  "/Public/about.html" : "help2.htm",
  "/Public/ed_advisors.html" : "help2.htm",
  "/Public/whats_inside.html" : "help1.htm",
  "/Public/whats_new.html" : "help2.htm",
  "/Public/faq.html" : "help2.htm",
  "/Public/learning_resources.html" : "help10.htm",
  "/BibSearch.html" : "help3.htm",
  "/Public/contact_us.html" : "help1.htm",
  "/MainSearch.html" : "help5_3.htm",
  "/BioSearch.html" : "help5_4.htm",
  "/ImageSearch.html" : "help5_5.htm",
  "/PrimarySearch.html" : "help5_6.htm",
  "/BibSearch.html" : "help5_7.htm",
  "/QuranSearch.html" : "help5_8.htm",
  "/ConcordanceSearch.html" : "help5_9.htm",
  "/QuranicStudies.html" : "help8.htm",
  "/Timeline.html" : "help9.htm"
};

function launchHelp() {
  var loc = location.pathname;
    var url = helpUrls[loc];
    if (url)
      return pop("/Public/Help/" + url,'Help','790','590');

    if (loc.indexOf("browse") >= 0)
      url = "help6.htm";
    else if (loc.indexOf("islam-9780192831934") >= 0)
      url = "help8.htm#8_2";
    else if (loc.indexOf("islam-9780192835017") >= 0)
      url = "help8.htm#8_2";
	else if (loc.indexOf("quran-both") >= 0)
      url = "help8.htm#8_2";    
    else if (loc.indexOf("islam-0520043278") >= 0)
      url = "help8.htm#8_3";
    else if (loc.indexOf("/Public/") >= 0)
      url = "help2.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],'span')[0].onclick = highlightOn;
		myGetElementsByClass('off',highlight[x],'span')[0].onclick = highlightOff;
	}
}

function highlightOff() {
	var hits = myGetElementsByClass('hit',null,'a');
	for (var i = 0; i < hits.length; i++) {
		hits[i].className = "miss";
	}
}
	
function highlightOn() {
	var hits = myGetElementsByClass('miss',null,'a');
	for (var i = 0; i < hits.length; i++) {
		hits[i].className = "hit";
	}
}

/* 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;
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/* +/- 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
		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
			if (mom.className != "openlist"){									// check if it should be closed
				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
			    }
			} else {
				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";								// hide the first UL that follows this toggle
			    }
			}
			togglers[i].onclick = toggle;						  				// assign toggle function to toggle links' onClick
		}
	} else return;
}

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";
	}
}

/* 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 = 'visible';
      searchForm.style.visibility = 'visible';
    } 

  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 = 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 curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	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;
    }
}


