/* Copyright 2003 Paul A Norman
   P.O. Box 1005, Nelson 7015 N.Z.
	 email: 106121.717@compuserve.com
	 http://PaulANorman.com
	 Assistance from Michael F. To'o colours
	    Use freely.
	 */


//Global

var textBlocks = new Array();
var textUpto = 0;

var originalColor, originalBackground, originalLetterSpacing;

var chapterList = new Array();
  var chapterNumber =0;
  var currentChapter;

var indexWindow;
//End Global



function beforePrint() {
//place new printing style sheet in the header
				
// document.createStyleSheet("../css/bookPrintStyle.css");
	

 try //for speed try to get XML from opening document if it was our ie6 index.html
 {
 var menuXml =opener.menuData.cloneNode(true);
  }
 catch(e)
  	{  // alert('oh owh '+ e);
        var menuXml = new ActiveXObject("Msxml2.DOMDocument");
          menuXml.async = false;
          menuXml.resolveExternals = false;
          menuXml.load('../menu/htmlMenu.xml');
     }
	finally
	  {	 
       var ns2 = "xmlns:menu='http://PaulANorman.com'";

       menuXml.setProperty("SelectionNamespaces", ns2);
        menuXml.setProperty("SelectionLanguage", "XPath");

       menuXml = menuXml.documentElement;
		}//end try catch finally	

   filename = document.location.pathname;
  filename = decodeURIComponent(filename.substr(filename.lastIndexOf('/')+1));
 
   //locate filename in tree menu tree
	 //[@url='books\Education.htm'] Xpath NOT AVAILABLE!!!
	

	  var thisXmlNodeList = menuXml.getElementsByTagName('menu:item');
		
		// initialise text holder for opening pages in case of a non return 
		mainTitle = '&nbsp;'; subTitle = '&nbsp;'; 	moreInfo = '&nbsp;'; introduction = '&nbsp;'; series = '&nbsp;'; 	
 
 for (i=0; i < thisXmlNodeList.length; i++)
   {
	      curNode = thisXmlNodeList.item(i);
				if (curNode.getAttribute('url') == 'books\\'+filename)
				    {
						mainTitle = curNode.getAttribute('text')
						subTitle = curNode.getAttribute('title');
					moreInfo =curNode.getAttribute('moreinfo');
				 introduction =curNode.getAttribute('introduction');		
					series = 	curNode.getAttribute('documenttype');
								 break;
						  }  
	  }
  
	
	 var infoXml = new ActiveXObject("Msxml2.DOMDocument");
          infoXml.async = false;
          infoXml.resolveExternals = false;
          infoXml.load('../xml/Information.xml');
			//alert(infoXml.url);					
	        infoXml = infoXml.documentElement;
	       // alert( infoXml.childNodes(0).text);
				 
		//  alert('before Print');		
	
			
		var   buildDisplayUp = '';
	 frontPage = '<span id="fadingGreyBar"></span>';

 frontPage += '<h2 id="mainTitle">'+mainTitle+'</h2><div style="page-break-after: always;"></div>';

 titlePage ='<h2 id="subTitle">'+subTitle+'</h2>' + '<div id="introTextBlock"><p id="moreInfo">'+moreInfo+'</p><p id="introduction">'+introduction+'</p></div><div id="seriesTextBlock"><span id="seriesLegend">Series: </span><span id="seriesText">'+series+'</span></div>';

//infoXml.childNodes(0).childNodes(0).setAttribute("className","publisherInfo"); //sets style on the embracing lead SPAN tag //NOW DONE IN STYLE SHEET bookStyle.css::MEDIA print {}

  Divs = infoXml.childNodes(0).childNodes(0).getElementsByTagName('div') ;
       for (i = 0; i < Divs.length; i++)
			      { 
						 Divs.item(i).setAttribute("class" ,"publisherInfoDivs");
						 }
			 
			 
 publisherPage ='<h2 id="publisherLegend">Publisher\'s Information</h2>' + '<div id="publisherGap"><p>'+''+'</p><p>'+''+'</P></div>'+infoXml.childNodes(0).xml+'<div style="page-break-after:always;"></div>';

	pictures = document.images;
	for (i=0; i<pictures.length; i++)
	  {
  if (pictures[i].style.pixelWidth > 150) {pictures[i].style.cssText += 'position:relative; left -50; display:block'}
       //pictures[i].filters("progid:DXImageTransform.Microsoft.Chroma").color='';
//pictures[i].filters("progid:DXImageTransform.Microsoft.Chroma").enabled=true; //in style sheet now q.v.
		 }
			
			Brs = document.all.tags('BR');
			 for (i = Brs.length -1; i > -1 ; i--)
	    {Brs[i].outerHTML = '<span style="display:block"></span>';	
	     //prob with <BR> breaking up text
				}	
				
			sups = document.all.tags('sup');
			 for (i= 0 ; i < sups.length; i++)
			   {//(sups[i].className=='likeHyperLink') & 
				  if (sups[i].innerText== 'Return')
					{					
					 sups[i].style.display = 'none';
				  }	
					}//for
			
		 var  buildChpatersListUp = '<div style="page-break-after:always;text-align:left;">';// </div> is below
 buildChpatersListUp += '<h2 style=" font-size:20pt; padding-bottom: 44">Chapters</h2><p />';
 
 var 	chapterUptoPrint = 0;
				 
  for (i = 0; i < textBlocks.length; i++) //textBlocks defined above in //Global 
	    {	
				if (textBlocks[i].dontPrint != null)
				 {
				  continue;
				  }
					
				textBlocks[i].style.display='block';		
				textBlocks[i].style.width = 500;
/*chapterDisplay="" chapterName="" */				
				
				if (textBlocks[i].chapterName != null)
				 {
				 chapterUptoPrint++;
				
				if  (textBlocks[i].chapterDisplay != 'undefined')
				 { textBlocks[i].innerHTML = '<h3 style=" position:relative; left : -120; text-align:left; margin-bottom: 45;  border-style:  solid; border-color:darkgrey ; border-size: 1px; padding:8; width: 250">'+textBlocks[i].chapterDisplay +'</h3>' +  textBlocks[i].innerHTML;
          }

					
					if (chapterUptoPrint == 1)
					  {
						 doPageBreakBefore ='auto';}
						else 
						{
						 doPageBreakBefore ='always';} 
					
				 textBlocks[i].innerHTML = '<p style="page-break-before: '+doPageBreakBefore+'; position:relative; left : -120; font-weight:bold; font-size:15pt; color:#4e4c4a; font-style : italic; margin-top:25; margin-bottom:20; text-align: left">Chapter '+ chapterUptoPrint.toString()+' &nbsp; '+textBlocks[i].chapterName +'</p>' + textBlocks[i].innerHTML;
				
			//	 fromTop = 100 + (chapterUptoPrint * 30);
			    chapterNumber = chapterUptoPrint.toString();
					
				 if (chapterNumber.length < 2)//padd numbers to keep names even
				  {
					 var chapterNumber = '<tt>&nbsp;'+chapterUptoPrint.toString() +'.</tt>';
					 }
					else
					 {
					  chapterNumber = '<tt>'+chapterUptoPrint.toString() +'.</tt>';
						} 
				 buildChpatersListUp += '<p style=" font-weight:bold; font-size:12.5pt; color: black; font-variant : small-caps; position:relative; top:11; left: 90; ">'+ chapterNumber+'<span style="display:inline-block; position:relative; left: 100 ; font-style: normal">'+textBlocks[i].chapterName +'</span></p>';
				  }
				
				
				buildDisplayUp += textBlocks[i].outerHTML; 
	     } 
			 
	  		  buildChpatersListUp += '</div>';
			 
					
document.body.innerHTML = frontPage + titlePage +  publisherPage + buildChpatersListUp + buildDisplayUp; 

/*var 	heading1s = document.all.tags('h1');
	 for (i = 0; i < heading1s.length; i++)
	    {	
	     heading1s[i].style.marginTop='10'; 
				}
				*/


alert('This kind of Printing is for your convenience, and sometimes may not look the best. Pages may be broken and sometimes have little printed on them.\n\nPlease check  to see if there is a PDF available. Many of the PDFs print to make foldable booklets.');		

document.execCommand('SelectAll');
document.execCommand('Copy');		
}  


function afterPrint() {
document.location.reload();
}


window.onbeforeprint=beforePrint;
window.onafterprint=afterPrint;




function addText(textId){

textBlocks[textUpto] = textId;
textUpto++;

//END function
}

function cancelBubbles(){
if (window.event != null)
{
window.event.cancelBubble = true;
}
//END function
}


function getHeight(){
return parent.window.document.body.clientHeight ;

//END function
}

function getDisplayWidth(){
calc = parent.window.document.body.clientWidth - parseInt(menuLeft.style.width);
//calc = calc +28;
return calc  ;

//END function
}

function getButtonStart(){
//buttonPlacement.style.left =  Math.round(parseInt(menuLeft.style.width)/2) -45;

//END function
}

function setDisplayPaddingWidth(){

calc =  getDisplayWidth();
calc = calc - 420;
if (calc < 40){calc=40;}
calc = calc /2;
return  calc;

//End function
}

function setDisplayPaddingHeight(){

calc =  getHeight();
calc = calc - 400;
calc = calc /2;

if (calc < 20){calc=20;}
return  calc;

//End function
}

function closeIndex(){

 if (indexWindow != null){
     indexWindow.close();
		 }

//End function
}

function closingIndex(){indexWindow=null;}

function searchText(lookFor){
//clear previous results if any

indexWindow.results.innerHTML = '';

re = new RegExp(lookFor,["igm"]);
//alert( textBlocks[1].innerText);

 for (x=0; x < textBlocks.length; x++){

   if ( re.test(textBlocks[x].innerText))
	 {
	 indexWindow.results.innerHTML += '<BR />Page. '+(x+1).toString();
	    start = textBlocks[x].innerText.indexOf(lookFor);

	thisMuch = textBlocks[x].innerText;

	thisMuch =thisMuch.substr(start-12,80);
  pageNo = x;
			indexWindow.results.innerHTML +='&nbsp;<span onclick=\"opener.focus();opener.gotoPage('+x.toString()+');\" style=\"color:darkgreen;text-decoration:underline;cursor:hand\">'+ thisMuch+'</span>';
	 }//if regular.test

  }// for loop

 if (indexWindow.results.innerHTML == ''){
   indexWindow.results.innerHTML = '<span style=\"color:darkred\" >Sorry There Are No Results For: </span>'+ lookFor;
 }


}

function openIndex(){
 if (indexWindow == null){
indexWindow = window.open('about:blank',null,
    "height=300,width=600,status=no,toolbar=no,menubar=no,location=no");
     indexWindow.document.body.innerHTML='<div style="position:absolute;top:0;left:0;height:120;width:600;background-color:silver;padding:20" id="top">'+
'<P>Please Enter Your Search Text</P>'+
'<input style="position:relative;left:20" id="findThis" onkeydown="if (event.keyCode == 13){event.returnValue=false;findButton.click();}" type="text" width=75 />&nbsp;'+
'<button id="findButton" style="position:relative;left:20" onclick=opener.searchText(findThis.value) TABINDEX="1">Find</button>'+
' </div>'+
' <div id="results" style="position:absolute;top:129;left:5;height:162;width:590;overflow:auto;padding:10;border:1pt solid black;padding-top:10;padding-bottom:6;padding-right:15;padding-left:15;">'+
'</div>';
     indexWindow.attachEvent('onunload',closingIndex);

                         }

indexWindow.focus();


//End function
}


function makeBooks(html){
//alert(html);
chooseBook.outerHTML = '<p>Hi</p>';

//End function
}


function whichPage(){

moused =window.event.srcElement;
 // onclick on number in chapter list is hitting an Italics tag created in inital setup
  if (moused.tagName == 'I'){moused = moused.parentElement;}

          if (moused.className == 'menuItem'){
              moused.style.color='white';
              gotoPage(parseInt(moused.goto));
                                                }
//End function
}

function linkHover(){
moused =window.event.srcElement;
// mouseover on number in chapter list is hitting an Italics tag created in inital setup
  if (moused.tagName == 'I'){moused = moused.parentElement;}

originalColor = moused.style.color;
originalBackground = moused.style.backgroundColor;
moused.style.backgroundColor = 'black';
originalLetterSpacing =moused.style.letterSpacing ;
//moused.style.letterSpacing='0.2mm';
moused.style.color='honeydew';
moused.title= 'Chapter: '+moused.innerText+' - '+ moused.chapterDisplay +'\n\n'+
															getPortion(moused.goto,40) ;

//End function
}

function getPortion(pageNum,words){

splitText = textBlocks[pageNum].innerText.split(' ');
re = /,/g;
return 'Chapter\'s Opening Text:\n\n'+
       splitText.slice(0,words).toString().replace(re,' ')+
       ' ..\n\n'+
			 '\t\t\t\t\t\tPage ' +(parseInt(pageNum)+1).toString()+'.\n';

//End function
}


function linkOut(){
moused =window.event.srcElement;

// mousout on number in chapter list is hitting an Italics tag created in inital setup
  if (moused.tagName == 'I'){moused = moused.parentElement;}
	
moused.style.color=originalColor;
moused.style.backgroundColor = originalBackground;
//moused.style.letterSpacing = originalLetterSpacing;
//End function
}


function gotoPage(num){
textUpto = num;
jumpTo();

//End function
}

function jumpTo(){
									prev.disabled=false;
									next.disabled=false;


									prev.title='Back To Page, '+textUpto.toString()+'.' ;

				next.title='Next Page, '+ (textUpto +2).toString()+'.';


additionalInformation='';

if (textUpto <= 0){textUpto=0;
                  additionalInformation += '(First Page)';
									prev.title='You Are At The First Page';
									prev.disabled=true;}

if (textUpto >= (textBlocks.length -1)){textUpto=textBlocks.length -1;
                  additionalInformation += '(Last Page)';
									next.title='You Are At The Last Page';
									next.disabled=true;}

//if (additionalInformation == '&nbsp; '){additionalInformation='';}

personPageNumber = textUpto +1;
pageNumber.innerHTML = 'Page '+ personPageNumber.toString() + '.';

var foundChapter;

   for (chaptNum in chapterList){
//	      if (chapterList[chaptNum].pageNo >= textUpto){
  	      if (chapterList[chaptNum].goto <= textUpto){
								foundChapter =chaptNum;
								//break;
																}

																   }
			additionalChapterInformation =chapterList[foundChapter].chapterDisplay;

	         if (additionalChapterInformation != '') {
					     additionalChapterInformation = ' &#151; '+
							                                   additionalChapterInformation  }

				        pageHeader.innerHTML =('Chapter ').italics()+chapterList[foundChapter].innerHTML + 	additionalChapterInformation;

                currentChapter.style.backgroundColor = 'darkslateblue';
								chapterList[foundChapter].style.backgroundColor = 'black';

								originalBackground =  'black';
								currentChapter = chapterList[foundChapter];
								currentChapter.scrollIntoView(true);

								spacer ='   ';
			if(chapterList[foundChapter].chapterDisplay != ''){
											spacer =' - ';
			}


		window.status = additionalInformation +
		        '  Chapter: '+
						chapterList[foundChapter].innerText +spacer+
						chapterList[foundChapter].chapterDisplay;

display.innerHTML = textBlocks[textUpto].innerHTML;
					/*
					the parent division is being monitored for events to catch the clicks on
					chapter links this also means that the child  button clicks would double
					render and cause other problems so:-
					*/

cancelBubbles();

//End function
}

function nextPageNumber(move){

textUpto = textUpto + move;
jumpTo();

//End function
}


function 	establishTextBlocks(){
       /*
       Obtain a Collection of all DIVs in the document
      */
divList = document.all.tags('DIV');
//alert('This Many: ' +divList.length);
       /*
       Iterate through Collection of all DIVs in the document and
			 copy the textBlocked Id DIVs to the array textBlocks[] using
			 the addText() function. use long hand version of for loop as IE6 does not
			 appear to cope well with the 'for in' format when the DIVs have no id
			 preset
       */
			 for (idText = 0; idText < divList.length; idText++){
       /*
			 Set id for DIVs that have none incase DHTML reacts against them IE6 seems
			 to like haveing IDs for some things.
			 */
	if ( divList(idText).id == ''){
				 divList(idText).setAttribute('ID',document.uniqueID,0);
				}//END if id== ''

    hold = divList(idText);
	    if (hold != null){
        if (hold.className=='pagetext'){
//         alert(hold.id);
		       addText(hold);
      /*
      make left hand area menu items (Chapters) from textBlocks that have chapterName
      */
		if (hold.chapterName != null){
            oNewNode = document.createElement("SPAN");
	          chapterArea.appendChild(oNewNode);
buffer = '';
  if (chapterNumber < 9){
	buffer ='&nbsp;&nbsp;';
	}
	  // 
	
	          oNewNode.innerHTML=(buffer+(chapterNumber+1).toString()+'. &nbsp;').italics()+ hold.chapterName;

            oNewNode.className='menuItem';
						oNewNode.setAttribute('ID',document.uniqueID,0);
      /*
      Add any Chapter Display information for the top right of the page.
      */
 if (hold.chapterDisplay != undefined){
	additionalChapterInformation =hold.chapterDisplay;}
	else{additionalChapterInformation = '';}
						oNewNode.setAttribute('chapterDisplay',additionalChapterInformation,0);

						oNewNode.attachEvent('onmouseover',linkHover);
						oNewNode.attachEvent('onmouseout',linkOut);
      /*
      set currentPage, textUpto is set ready for a new textBlock so is
			too high by one. Place currentPage as jump to page number.
     */
						currentPage = (textUpto -1).toString();
						oNewNode.setAttribute( 'goto',currentPage);
	 //         oNewNode.innerHTML += '&nbsp;&nbsp;P. '+textUpto.toString();
      /*
			fill chapterList[] array with chapter names and their corresponding page
			numbers through the created span object to enable pageHeader to have
			chapter name in it and chapter in menu to be highlighted.
     */
						chapterList[chapterNumber] =  oNewNode;
							chapterNumber++;
																  }   // END if (hold.chapterName != null)
                                    }   //END if (hold.className=='narritive')
                  }   //END if (hold != null)
                         }   //END for (idText in divList)
textUpto =0;
currentChapter = chapterList[0];

//END function
}

function setUpBookList(){
books = XMLbooklist.XMLDocument.documentElement;
for (EachOne =0;  EachOne< books.childNodes.length; EachOne++)
     {
    bookItem = books.childNodes.item(EachOne);
  newOption = document.createElement('option');
		     newOption.innerText = bookItem.childNodes(0).text;
		     newOption.value = bookItem.childNodes(1).text;
		     newOption.setAttribute('title', bookItem.childNodes(2).text);
 				 newOption.style.cssText = bookItem.childNodes(3).text;
	     chooseBook.appendChild(newOption);

       }
//END function
}


function newPage(optionX)
{
     cancelBubbles();
		 
		 if (optionX.options[optionX.selectedIndex].innerText != 'Main Page') 
		   {
			 	 navigate(optionX.options[optionX.selectedIndex].value);
				}
				else
				 {
				 //going to call processJump() and it expects an anchor as below

				 clicked = document.createElement('A target="MainPage"');
				 
				 //hreff (double ff) is the correct name of the attribute to be sought later
				 clicked.setAttribute('hreff', optionX.options[optionX.selectedIndex].value);
				 clicked.style.display ='none';
				 document.body.appendChild(clicked);
				 processJump(clicked); //in common.js
				 } 
		 window.attachEvent('onunload', closeIndex);
}


function setUp(){

/*alteration to this tag and code done: 9 February 2008

<span id="otherBooks">Book:
<br />
<select  id="chooseBook"  style="width=134;height:25;position:relative;"    onclick="newPage(this);" size=1>
</select>
</span>

*/
 
 otherBookArea = document.getElementById("otherBooks");
 
 otherBookArea.title = "Chose A Book Below and Click On the \"Open Book\" Link";
 otherBookArea.innerHTML = "<a title=\"Click Here After Choosing A Book Below\" style=\"display:inline-block; color:blue; padding-bottom:5px\" href=\"javascript:newPage(document.getElementById(\'chooseBook\'))\">Open Book</a><b>&#8600;</b><br /><select  id=\"chooseBook\"  style=\"width=134;height:25;position:relative;\"  size=1></select>";

otherBookArea.style.cssText += "color:navy; padding:2px;background-color:white;border:black solid 1px;"

// end of alteration: 9 February 2008

  document.body.style.overflow = 'hidden';
	establishTextBlocks();

for (idBlock in textBlocks){
textBlocks[idBlock].style.display='none';
textBlocks[idBlock].style.className='javascriptNarritive';
      }

    // Set resize and positions functions on key elements and blocks

document.body.style.padding ='0';

menuLeft.style.setExpression('height','getHeight()+7');
chapterArea.style.setExpression('height','getHeight() - 125');
display.style.setExpression('height','getHeight() -25');

pageFooter.style.setExpression('top','getHeight() -30');
buttonPageMove.style.setExpression('top','getHeight() -32');

otherBooks.style.setExpression('top','getHeight() -92');

menuLeft.style.width = '152';
display.style.left = '153';
pageFooter.style.left = '153';
pageHeader.style.left = '153';


buttonPageMove.style.setExpression('left','getButtonStart()');

display.style.setExpression('width','getDisplayWidth()');

buttonPlacement.style.setExpression('top','getHeight() -24');
buttonPlacement.style.setExpression('left','getDisplayWidth() +27'); //27

display.style.setExpression('paddingLeft','setDisplayPaddingWidth() -15');
display.style.setExpression('paddingRight','setDisplayPaddingWidth()');

display.style.setExpression('paddingBottom','setDisplayPaddingHeight()');
display.style.setExpression('paddingTop','setDisplayPaddingHeight()+8');

pageFooter.style.setExpression('width','getDisplayWidth()');
pageHeader.style.setExpression('width','getDisplayWidth()');

otherBooks.style.display ='block';
buttonPageMove.style.display='block';
menuLeft.style.display ='block';
pageFooter.style.display = 'block';
pageHeader.style.display = 'block';
chapterHeading.style.display = 'block';
buttonPlacement.style.display = 'block'
setUpBookList()

jumpTo(); //uptoPage is already set to 0 in global variables

//End function
}
//From and for Royal Law Love

function linkOut(){
moused =window.event.srcElement;
moused.style.color=originalColor;
moused.style.backgroundColor = originalBackground;
//moused.style.letterSpacing = originalLetterSpacing;
//End function
}

function jumpToLink(linkText){

 re = new RegExp(linkText+'VJZx',["igm"]);
 for (x=0; x < textBlocks.length; x++){

   if ( re.test(textBlocks[x].innerText))
	 {

  gotoPage(x);
  return;
	 }//if regular.test

  }// for loop



}
