// ==== For remembering the TOC state ==== //

function triggerSpan(color) {
  $$('a.t','a.codeHead').each(
        function(choo){ 
            //this line overwrites the former onclick function, so make sure to include ToggleDisplay
            if ( choo.hasAttribute('id') ) {
				try{
	                choo.parentNode.firstChild.onclick = function(){ 
	                sirOrfeo('span'+choo.id); 
	                ToggleDisplay( this, color); 
	                };  
	                choo.parentNode.firstChild.id = 'span'+choo.id;
				}
				catch(err){ }
            }
        }
    );
    for (i in top.frames["nav"].eurydice) {
        ToggleDisplay( $(i), color ); 
    };
}

function sirOrfeo(lyre) {
    var hades = top.frames["nav"].eurydice;
    //NB that sirOrfeo fires before ToggleDisplay, so a closed span will still contain "+"
    if ( $(lyre).innerHTML == "+" ) {
        hades[lyre] = lyre;

    }
    else { //otherwise it's open and we're about to close it
        delete hades[lyre];
    }
}

// ==== For inserting the checkboxes it's faster to do this with JavaScript than with Perl ==== //
    
function checkInit() {	
    $$('.ptoc a.t','.ptoc a.t3').each( //for the chapter/title level links
        function(choo){ 
            var myLink = choo.href;
            var willCall = choo.id;
            var belongsTo = choo.name;
            myLink = myLink.replace(/.*\/(html\d?)\//ig,"../$1/");
            buildForm(myLink, willCall, belongsTo, choo); 
        }
    );
}

	
function buildForm(myHref, willCall, belongsTo, theLink) {
// originally we dynamically constructed the object--see above--but then IE6 & IE7 displayed a fascinating selection of bugs
// Essentially, IE won't let us construct the onlick event as a string, but it also won't let us interpolate a variable into a DOM declaration
// Ergo: the brute force method.
    var myCheck = '<input type="checkbox" value="' +myHref +'" name="'+belongsTo+'" ';
    if ( theLink.hasAttribute('id') ) {
        myCheck = myCheck + 'onClick="changeCheck(document.myForm.'+willCall+', this.checked);" />';
    }
    else { myCheck = myCheck +' />'; }
    var ouji = document.createElement('span');
    ouji.innerHTML = myCheck;
    theLink.parentNode.insertBefore(ouji,theLink);
}


// ==== For Ord Search, search form, etc. ==== //

function openWindow(url, name, width, height) {
	var q = window.open(url,name,'width='+width+',height='+height+',left=200,top=250,scrollbars=yes,toolbar=no,menubar=no, location=no, directories=no,personalbar=no');	
	q.focus();
}

// ==== For Ord Search, specifically ==== //

function searchOrd( e ) {
    var f = document.getElementById('searchForm');
    f.request.value = "\"Ord. " + e + "\"";
    openWindow('Ord Search', 'formtarget', '300', '350'); //this puts the results in a pop-up
    f.submit();
}

function setOrdSearch() {
    var links = document.getElementsByTagName( 'span' );
    for( var i=0; i < links.length; i++) {
        links[i].onclick = function(){searchOrd( this.innerHTML );  };
        links[i].onkeyup = function(){ToggleDisplay( this.innerHTML )};
        links[i].style.cursor = "pointer";
        links[i].style.display = "inline";
        links[i].style.textDecoration = "underline";
    }
}


// ==== Open links to specific pages within the frameset ==== //

function reDirect() {
var n = location.href.indexOf("?") + 1; //get where the parameter starts in the location string
if (n>0) { //if there is no ? in the location, then the value of n will be 0 (-1 + 1), and this section will be skipped
	var myLoc = "html/" + location.href.substring(n); //create proper file path
	parent.doc.location = myLoc; //redirect to proper location
	}
}

// ==== For the TOC page ==== //

function fewButtons() { 
	parent.nav.document.getElementById("searchtabs").style.display='none';
 	parent.nav.document.getElementById("codetabs").style.display='block';
	parent.nav.document.forms[0].style.display='block';
}	 
	
function moreButtons() { 
	parent.nav.document.getElementById("searchtabs").style.display='block';
	parent.nav.document.getElementById("codetabs").style.display='none';
parent.nav.document.forms[0].style.display='none';
}

function changeCheck(myCheck, checkAll){ //grab the title/CH name & checked status
	try { //use a try/catch because there might be no sublevels 
		for(var x=0; x<myCheck.length; x++){ //run through all checkboxes with the right "name" value
			myCheck[x].checked = checkAll; //change each chapter/section to the checked status of the title
			try { myCheck[x].onclick(); }//try to trigger the chapter's onlick event,
			catch(err) {} //if the onClick fails, go on
		}
		myCheck.checked = checkAll; //if there's only one chapter/section, this will catch it (the array doesn't)
		try { myCheck.onclick(); }//onClick, etc.
		catch(err) {} 
	}
	catch(err) {} //catch for initial try
}

function selectAll() {
	for(var x=0; x<document.myForm.length; x++){
		document.myForm[x].checked = true;
	}
}

function clearAll() {
	for(var x=0; x<document.myForm.length; x++){
		document.myForm[x].checked = false;
	}
}
function clearAll2() {
	for(var x=0; x<document.SearchForm.fileConditions.length; x++){
		document.SearchForm.fileConditions[x].checked = false;
	}
}


// ==== Hide/Show Hits button ==== //

function runtheloop(color) {
	var myHits = parent.doc.document.getElementsByTagName("span"); //grabs all <span> tags
	for(var x=0; x<myHits.length; x++) { //goes through each span
        var spanType = myHits[x].getAttribute("name"); //gets the name attribute of each span
        if (spanType=="hitresult") { //checks to see if its name is "hitresult"
            myHits[x].style.backgroundColor=color; //set background to the color fed in by swaphits()
        }
    }
}

function swapHits() {
	var hitHeader = parent.doc.document.getElementById("hitheader"); //gets the entire search result header
	var mainContent = parent.doc.document.getElementById("mainContent");

   	if ( hitHeader.style.display != "none") { //if the hit header visible
        hitHeader.style.display="none"; //and makes the entire header invisible to be on the safe side
        runtheloop("#FFFFFF"); //tells runtheloop() to give the hits a white background
        document.getElementById('swap').innerHTML="Show Hits"; //changes text on swap button
    }
    else { //if it's invisible
        hitHeader.style.display="inline"; //and makes the entire area visible
        runtheloop("#FFFF00"); //highlights hit resultws
        document.getElementById('swap').innerHTML="Hide Hits"; //and changes the button to match
    }  
}

// === for retaining search settings === //


function recallS() {
var type = top.frames["nav"].type;

	document.SearchForm.searchType[type].checked = true;
	document.SearchForm.stemming.checked = top.frames["nav"].stem;
	document.SearchForm.fuzzy.checked = top.frames["nav"].fuzz;
	document.SearchForm.fuzziness.value = top.frames["nav"].fuzzlevel;
	document.SearchForm.phonic.checked = top.frames["nav"].phonic;
    
    for (i=0;i<top.frames["nav"].scope.length;i++) { //go through all the scope search array
        var x = top.frames["nav"].scope[i]; //get the index of the checked box
        document.SearchForm.fileConditions[x].checked = true; //so let it be done
    }
    
}

function rememberS() {
var stem=document.SearchForm.stemming.checked;
var fuzz=document.SearchForm.fuzzy.checked;
var fuzzlevel=document.SearchForm.fuzziness.value;
var phonic=document.SearchForm.phonic.checked;

var type; //get the search type by cycling through radio buttons--code from quirksmode.org
	for (i=0;i<document.SearchForm.searchType.length;i++) {
		if (document.SearchForm.searchType[i].checked) {
			type = i;  //we don't need the value, we just need to know which one is checked
		}
	}
    
var scope = new Array(); //create an array
var rlyeh = 0; //counter variable
    for (i=0;i<document.SearchForm.fileConditions.length;i++) { //go through all the index checkboxes
        if (document.SearchForm.fileConditions[i].checked) { //find the checked ones
            scope[rlyeh] = i; //save the LOCATION of the  checkbox to be remembered
            rlyeh++; //forward the counter! Cthulhu fhtagn!
        }
    }

top.frames["nav"].scope = scope;
top.frames["nav"].stem = stem;
top.frames["nav"].fuzz = fuzz;
top.frames["nav"].fuzzlevel = fuzzlevel;
top.frames["nav"].phonic = phonic;
top.frames["nav"].type = type;

} //end rememberS()


// ==== Bookmarking functions! ==== //

function getLink() {
	var docloc = String(parent.doc.location); //get the location of the doc frame
    var codeStem = String(parent.location.hostname) + String(parent.location.pathname); //get the codepublishing.com/state/city base URL
	var codeMatch = new RegExp(codeStem,"i");//and make it a regex to check that we're bookmarking a code page
    
	if (docloc.match(/dtisapi/)) { //for search results
		try {  //try to get the page's location from the <base href> tag
			docloc = parent.doc.document.getElementsByTagName("base")[0].href;  
            if (docloc.match(codeMatch)) {
                openWindow('../../cgi-bin/bookmark.pl?href=' + docloc, 'bookmark', '500', '400');
            }
            else {  // if the search results are from the wrong code
                failmark('These search results are from the wrong code.'); 
            }
		}
		catch(err) { //if getElementsByTagName("base")[0].href fails
            failmark('There is an error on the page.'); 
        } 
	}
	else if (parent.doc.document.getElementById('book')) { 
        return; // So we don't reload the bookmark window, which is a problem.
    } 
	else if (docloc.match(codeMatch)) {
		openWindow('../../cgi-bin/bookmark.pl?href=' + docloc, 'bookmark', '500', '400');
	}
    else {  failmark(' '); } //generic failure
}

function failmark(message) { //the error message!
    alert('Sorry, this location cannot be bookmarked! ' + message); 
}

// ==== Older fancy stuff from Advanced Demo ==== //



function toggleTOC( e ) {
	var fs = parent.document.getElementById('cols');
	if (fs.cols == "0,*" ) {
		fs.cols = "300px, *";
		e.innerHTML = "Hide TOC";
	}
	else { 
		fs.cols= "0,*";
		e.innerHTML = "Show TOC";
	}
}

function onTOC() { 
//this is fired when the navbar search is used, in case someone hid the TOC
	var fs = parent.document.getElementById('cols');
	var e = parent.nav.document.getElementById('toggleTOC');
		if (fs.cols == "0,*" ) {
			fs.cols = "300px, *";
			e.innerHTML = "Hide TOC";
		}
}


fontSize = 11;
function decreaseFont() {
	var fs = parent.document.getElementById('doc');
	//alert( fs.contentWindow.document.body.style.fontSize );
	if( fontSize > 7 && fs.contentWindow.document.body.style.fontSize) {
		fontSize--;
		fs.contentWindow.document.body.style.fontSize = fontSize + "pt";
	}
	else if( fontSize > 7) {
		fontSize = 11;
		fontSize--;
		fs.contentWindow.document.body.style.fontSize = fontSize + "pt";
	}
	
}
function increaseFont() {
	var fs = parent.document.getElementById('doc');
	//alert( fs.contentWindow.document.body.style.fontSize );
	if( fontSize < 20 && fs.contentWindow.document.body.style.fontSize) {
		fontSize++;
		fs.contentWindow.document.body.style.fontSize = fontSize + "pt";
	}
	else if (fontSize < 20 ) {
		fontSize = 11;
		fontSize++;
		fs.contentWindow.document.body.style.fontSize = fontSize + "pt";
	}
}

// ==== Search hit funtions ==== //

haveEH = 1;

function safeShowNoHitsMsg()
{   var name = "Unknown";
    try {
        name = new String(parent.doc.location);
        }
    catch(err) {
        }
    finally {
        if (name.indexOf("#xml=") != -1)
            alert("Use the buttons on the Adobe Reader toolbar to navigate hits in a PDF file.  Click the Help button for more information.");
        else
            alert("There are no hits marked in this document.");
        }
}

function initBar() {
    }

function showNoHitsMsg()
{    
if (haveEH)
        safeShowNoHitsMsg()
    else {
        var name = new String(parent.doc.location);
        if (name.indexOf("#xml=") != -1)
            alert("Use the buttons on the Adobe Reader toolbar to navigate hits in a PDF file.  Click the Help button for more information.");
        else
            alert("There are no hits marked in this document.");
        }
}

function newSearch() {
    parent.toc.window.location.hash = "NewSearch";
    }

function nextDoc() {
    if (parent.toc.nextDoc)
        parent.toc.nextDoc();
    }
function prevDoc() {
    if (parent.toc.prevDoc)
        parent.toc.prevDoc();
    }
function topOfFile() {
    if (parent.doc.gotoNthHit)
        parent.doc.gotoNthHit(0);
    else
        showNoHitsMsg();
    }
function nextHit() {
    if (parent.doc.nextHit)
        parent.doc.nextHit();
    else
        showNoHitsMsg();
}
function prevHit() {
    if (parent.doc.prevHit)
        parent.doc.prevHit();
    else
        showNoHitsMsg();
}

function firstHit() {
    if (parent.doc.gotoNthHit)
        parent.doc.gotoNthHit(1);
    else
        showNoHitsMsg();
    }


function printDoc() {
	parent.doc.focus();
	parent.doc.print();
    }
    
 
