/**
 * engine.js
 *
 * A multi-version manuscript rendering and traversal engine.
 *
 * @author jose b. chua <jose@zebware.com>
 * @version 0.5
 * @revised by Amit Kumar 18th of June 2002 <kumar@umd.edu>
 * @version 0.6 
 * @revised by Amit Kumar 1st of October 2002 <kumar@umd.edu>
 * @revised by Amit Kumar  5th of November 2002 <kumar@umd.edu>
 * @revised by Amit Kumar  4th of Dec 2002 <kumar@umd.edu>
 * @revised by Amit Kumar  24th of Dec 2002 <kumar@umd.edu>
 * @revised by Amit Kumar  20th of April 2003 <kumar@umd.edu>
 * @revision 0.7
 * @revised by Amit Kumar  27th of April 2003 <kumar@umd.edu>
 * swap function does not work in mozilla - NS
 */
var numManuscripts = 0;
var witnesses = new Array();
var matchingNodes = new Array();
var matchLine; //current line being matched
var sync = true;
var scrollvisible = true;
var scrollsync = false;
var ms;
var witShown = new Array();

// MB 2002-12-27
// Globals needed to keep state of tabbed MS page so we can restore
// scroll position after tab change
var showingMS = true;;
var scrollTops = new Array();
var scrollLefts = new Array();



function init() {
doSplashWindow();

//since displaying the first witness so initializing
witShown[numManuscripts]=witnesses[0];
numManuscripts++; 
//alert("following witnesses were found: "+ witnesses);
//alert("number of witnesses: "+ witnesses.length);
// initialise manuscript to first witness
showWitness(document.getElementById("manuscript"), "first");
}

function showWitness(manuscript, witness) {
  // determine which witness to change to
  var match_string;
	if (witness == "first") {
	  manuscript.current = 0;
	  var match = witnesses[manuscript.current];	
	} else if (witness == "last") {
	  // last witness is undefined
	  manuscript.current = witnesses.length - 1;
		var match = witnesses[manuscript.current];
	} else if (witness == "next" ) {
	  if(manuscript.current == null)
		manuscript.current=0;	
	  manuscript.current++;
		if (manuscript.current >= witnesses.length) manuscript.current--;
		var match = witnesses[manuscript.current];
	} else if (witness == "previous") {
	  manuscript.current--;
		if (manuscript.current < 0) manuscript.current++;
	  var match = witnesses[manuscript.current];	
	}else{
	}
    var position = 0;
	if(witShown.length == 1)
	{
	position = 0;	
	}else if(manuscript.style.left== "50%" || manuscript.style.left=="33%")
	{
	position = 1;	
	}else if(manuscript.style.left=="0%")
	{
	position = 0;	
	}else if(witShown.length== 2 && manuscript.style.left==""){
	 	//alert("came here"); 
	  position = 1;
	}else{
	position = getPosition(manuscript);
	}
witShown[position]= witnesses[manuscript.current];


//alert("in show witness witSHown ARRAY VALUES ARE: " + witShown);
  // update the control panel
//alert(witnesses[manuscript.current]);

var idContainer;
var subspans = new Array;

subspans = manuscript.getElementsByTagName("span");

for (var i=0;i <subspans.length;i++)

  {


   if (subspans[i].id != null && subspans[i].id == "msID")
     {
      idContainer = subspans[i];
      break;
     }

  }

idContainer.innerHTML = witnesses[manuscript.current];



//alert (manuscript.childNodes[1].getAttribute("id"));

//manuscript.childNodes[1].childNodes[10].innerHTML = witnesses[manuscript.current];

//MB-2002-12-26-002
// Locate the MS "paper" div without hard-coded constants
// The mspaper is the last div child of each manuscript.
// This is still not as general as it ought to be, and is
// undesirably sensitive to markup and XSLT changes, 
// but it avoids the crucial whitespace counting problems,
// and puts all browsers and their DOM implementations on the same footing
// towards the current markup and XSLT

var divs = new Array;
var mypaper;

  divs = manuscript.getElementsByTagName("div");
  ms = divs[divs.length-1]

for (var i = 0; i < ms.childNodes.length; i++) {

if(ms.childNodes[i].id != null)

{

//MB-2002-12-26-003
// Use W3C conformant exposure of attribute values.
// This syntax also works with IE5.5+ and so is preferable to
// MS proprietary even on MS platforms

var linewit = ms.childNodes[i].getAttribute("wit");

//if(ms.childNodes[i].id == "stanza")
//	{
  //      ms.childNodes[i].style.visibility = "visible";
    //    ms.childNodes[i].style.display = "block"	;
	//}

if(linewit == match | linewit == "all")
	{
        ms.childNodes[i].style.visibility = "visible";
        ms.childNodes[i].style.display = "block"	;
		if(ms.childNodes[i].id == matchLine )
		{

		}
	}else {
	//if(ms.childNodes[i].id == "stanza") {
	//	}
	//else {	
        ms.childNodes[i].style.visibility = "hidden"	;
        ms.childNodes[i].style.display = "none"	;
	//	}
	}
	}
 	}


}

function getPosition(ms)
{
var dumb = 100/(numManuscripts+1);
var num = parseInt(ms.style.left)/dumb;
    num = Math.round(num);
	//alert("in getposition: " + num);
return num-1;

}

function createManuscript() {
numManuscripts++;
//	alert("IN CREATE MANUSCRIPT");
  matchingNodes = new Array();
	if(numManuscripts > witnesses.length)
	{
	numManuscripts = witnesses.length;
	return ;
	}
  witShown[numManuscripts-1]=witnesses[0];
  toggleNotes(true);
  var newpaper = document.getElementById("manuscript").cloneNode(true);
  var msarea = document.getElementById("manuscriptarea");
	msarea.appendChild(newpaper);
	showWitness(newpaper, "first");
//	alert("after show witness now resize will takke place");
	resizeManuscripts();
	normalStyle();
//	alert("after creating new witness: " + witShown);
}
var current=0;
function moveUp()
{
if(current <= 50)
return ;
var obj = document.getElementById("manuscriptarea");
current = current - 50;
for(i=0;i<obj.childNodes.length;i++)
{
obj.childNodes[i].childNodes[1].style.position="absolute";
obj.childNodes[i].childNodes[1].style.top = current;
}
}

function moveDown()
{
var obj = document.getElementById("manuscriptarea");
current = current + 50;
for(i=0;i<obj.childNodes.length;i++)
{
obj.childNodes[i].childNodes[1].style.position="absolute";
obj.childNodes[i].childNodes[1].style.top = current;
}

}

/** This function is redundant in Mozilla not tested in IE
  * @AKR 27 th of April 2003
  */
// a dumb function which results in the scroll bars being visible
// else the scroll bars sit dumb as a stump
function displayScroll()
{
if(scrollvisible == false)
	{
var obj = document.getElementById("manuscriptarea");
current = current + 50;
for(i=0;i<obj.childNodes.length;i++)
{
obj.childNodes[i].childNodes[1].style.position="absolute";
obj.childNodes[i].childNodes[1].style.top = current;
}
scrollvisible = true;
	}
	
}

// toggles the scrollsync
function setSyncValue()
{
var obj = document.getElementById("syncscrollcheckbox");
if(obj.checked == false)
	scrollsync = false;
else
	scrollsync = true;
}

function synchronizeScroll(self)
{
if(scrollsync == false)
	return;
// now here do the scroll stuff 
//self.scrollTop

var msarea = document.getElementById("manuscriptarea");
var divs = new Array;
var mypaper;

for(i=0;i<msarea.childNodes.length;i++)
{

//  divs = obj.childNodes[i].getElementsByTagName("div");
 var current  = msarea.childNodes[i];
 if(current.nodeName =="DIV"){
   for(j=0;j<current.childNodes.length;j++){
   var this_man = current.childNodes[j];
 if(this_man.nodeName =="DIV"){
  this_man.scrollTop = self.scrollTop;
  this_man.scrollLeft = self.scrollLeft;
  
 }
 
  	}
	
   }
 }

// This replaces code which requires offset 1 for IE6 and offset 3
//obj.childNodes[i].childNodes[1].scrollTop = self.scrollTop;
//obj.childNodes[i].childNodes[1].scrollLeft = self.scrollLeft;


}





function displace()
{
var obj = document.getElementById("manuscriptarea");
for(i=0;i<obj.childNodes.length;i++)
{
obj.childNodes[i].childNodes[1].style.position="absolute";
obj.childNodes[i].childNodes[1].style.top = current;
}

}



function removeManuscript(button) {
  if (numManuscripts > 1) {
		numManuscripts--;
		var ms = button.parentNode.parentNode;
var dumb = 100/(numManuscripts+1);
var num = parseInt(ms.style.left)/dumb;
    num = Math.round(num)+1;
  //  alert("removing: " + ms.style.left +" element number : "+num);
	document.getElementById("manuscriptarea").removeChild(ms);
  	resizeManuscripts();
  } else {
	  alert("Sorry, but one manuscript must remain.");
  }
  witShown.splice(num-1,1);
}

function resizeManuscripts() {
  var msarea = document.getElementById("manuscriptarea");
  var this_man = -1;
	for (var i = 0; i < msarea.childNodes.length; i++) {
	  var current = msarea.childNodes[i];
  		if(current.nodeName =="DIV"){
		  this_man++;
		current.style.width = (Math.floor(100 / numManuscripts) - 0.1) + "%";
		current.style.left = (Math.floor(100 / numManuscripts) * this_man)  + "%";
		}
  }	
}

function changeTab(tab) {
  
// Make all the tabs unselected
    var mtab = document.getElementById("manuscripttab");
	mtab.style.fontWeight = "normal";
	mtab.style.paddingBottom = "0px";
	mtab.style.borderRight = "1px solid black";

    var dtab = document.getElementById("documenttab");
	dtab.style.fontWeight = "normal";
	dtab.style.paddingBottom = "0px";
	dtab.style.borderRight = "1px solid black";
	
   var htab = document.getElementById("helptab");
	htab.style.fontWeight = "normal";
	htab.style.paddingBottom = "0px";
	htab.style.borderRight = "1px solid black";

//

	tab.setAttribute("class", "tabactive");
	tab.style.fontWeight = "bold";
	tab.style.paddingBottom = "1px";
	tab.style.borderRight = "3px solid black";
	tab.style.color = "black";

	document.getElementById("manuscriptarea").style.display = "none";
	document.getElementById("docinfo").style.display = "none";
	document.getElementById("helparea").style.display = "none";

  switch (tab.id) {
	  case "manuscripttab" :
			document.getElementById("manuscriptarea").style.display = "block";
			break;
	  case "documenttab" :
			document.getElementById("docinfo").style.display = "block";
			break;
	  case "helptab" :
			document.getElementById("helparea").style.display = "block";
			break;
  }
}


function toggleNotes(toggle) {
  if (numManuscripts > 1 && toggle == true) {
	  toggle = false;
	  return false;
  }
  if (toggle) {
	  var mode = "inline";
	} else {
	  var mode = "none";
	}
	var spans = document.getElementsByTagName("span");
	for (var i = 0; i < spans.length; i++) {
	  if (spans[i].id.indexOf("noteicon") == 0) {
		  spans[i].style.display = mode;
		}
	}

	
	
	var divs = document.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) {
	  if (divs[i].id.indexOf("note") == 0) {
		  divs[i].style.visibility = "hidden";
		}
	}
}



/*
function toggleNotes(toggle){
var notesNodes = new Array();
var numFound=0;
var obj = document.getElementById("manuscriptarea");
for(i=0;i<obj.childNodes.length;i++)
{
for(j=0;j<obj.childNodes[i].childNodes[1].childNodes.length;j++)
{

  if(obj.childNodes[i].childNodes[1].childNodes[j].childNodes.length > 1)
  {
//  alert("--->" + obj.childNodes[i].childNodes[1].childNodes[j].childNodes[1].id);	
   if(obj.childNodes[i].childNodes[1].childNodes[j].childNodes[1].id != null &&  
	   obj.childNodes[i].childNodes[1].childNodes[j].childNodes[1].id == "noteicon"){
   matchingNodes[numFound]= obj.childNodes[i].childNodes[1].childNodes[j].childNodes[1];
   
   if (toggle) {
	  var mode = "inline";
	} else {
	  var mode = "none";
	}


	  matchingNodes[numFound].style.display = mode;


   numFound++;
   }
  }
}
}
}
*/
function toggleSync(checkbox) {
  sync = checkbox.checked;	  
  // update manuscripts
  var msarea = document.getElementById("manuscriptarea");
	for (var i = 0; i < msarea.childNodes.length; i++) {
	  showWitness(msarea.childNodes[i], "current");
	}
}

function displayNote(noteicon, title) {
	//var note = noteicon.nextSibling;
	var val = eval("document.getElementById(noteicon).innerHTML");
	//alert(val);
     var popUpRef = 
	window.open("", "Edit", "width=250 height=250, location=no, resizable=yes, scrollbars=yes, toolbar=no, status=yes");
	 if ( popUpRef.opener == null ){
                popUpRef.opener = self;
        }

// MB 2002-12-21
// Required for W3C Dom, otherwise we'll concatenate content on persisting window
	popUpRef.document.close();
	popUpRef.document.writeln("<html><head>	<link type=\"text/css\" href=\"../src/notestyle.css\" rel=\"stylesheet\"> <title>Notes: " + title +"</title></head><body>");

	popUpRef.document.writeln("<p>"+val+"</p>");
	popUpRef.document.writeln("</body></html>");
// MB 2002-12-21
	popUpRef.focus();

// IE (but wrong anyway??)
//	popUpRef.document.focus();
	popUpRef.document.close();
	//note.style.visibility = "visible";
}


function callHome() {
     var popUpRef = 
	window.open("http://www.mith2.umd.edu/products/ver-mach", "", "width=500 height=500, location=yes, resizable=yes, scrollbars=yes,toolbar=yes, status=yes");
}

function closeNote(notebutton) {
  notebutton.parentNode.parentNode.style.visibility = "hidden";
}


function imageView(witness, file) {
var imageWindow = new Array();
var num=0;
var PARAMS = "resizable=yes,status=no,scrollbars=yes,toolbar=0,directories=0,menubar=0,location=0,copyhistory=0,width=600,height=600,left=200";
    imageWindow[num] = window.open("","manuscript"+num,PARAMS);
    imageWindow[num].focus();
	imageWindow[num].document.write("<head><title>Versioning Machine--Manuscript Image " + witness + "</title><script>window.resizeTo(550,800);</script><style type='text/css'><!-- body { background: white; solid navy: overflow: hidden; margin: 0;} --> </style></head><body scroll='no'><applet style='border: 20px; border-style: solid; border-color: #cccc66;' code='LightApp.class' archive='../src/lightapp.jar' width=500 height=800><param name=num value='1'><param name=tile value='yes'><param name=filename0 value='images/" + file +"'></applet></body>");

num++;
        }

function imageViewAll() {
var imageWindow = new Array();
var numAll=0;
var numimage=0;
var thisimg=0;
numimage=images.length;

//alert("num"+numimage);
var PARAMS = "resizable=yes,status=no,scrollbars=yes,toolbar=0,directories=0,menubar=0,location=0,copyhistory=0,width=600,height=600,left=200";


imageWindow[numAll] = window.open("","manuscript"+numAll,PARAMS);
    imageWindow[numAll].focus();
imageWindow[numAll].document.write("<head><title>Versioning Machine--Manuscript Image </title><script>window.resizeTo(550,740);</script><style type='text/css'><!-- body { background: white; solid navy: overflow: hidden; margin: 0;} --> </style></head><body scroll='no'><applet style='border: 20px; border-style: solid; border-color: #cccc66;' code='LightApp.class' archive='../src/lightapp.jar' width=500 height=700>");

imageWindow[numAll].document.write("<param name=num value='"+numimage+"'>");
imageWindow[numAll].document.write("<param name=tile value='yes'>");
for(count=0;count<witnesses.length;count++){
witimagelen = images.length;
for(i=0;i<witimagelen;i++)
{
file =  images[i];
imageWindow[numAll].document.write("<param name=filename"+thisimg+" value='images/"+file+"'>");
thisimg++;
}
}
imageWindow[numAll].document.write("</applet></body>");
numAll++;

        }

function imageViewAllDiscrete() {
var imageWindow = new Array();
var numAll=0;
var numimage=0;
var thisimg=0;
for(i=0;i<witnesses.length;i++)
numimage= numimage + eval(witnesses[i]).length;

//alert("num"+numimage);
var PARAMS = "resizable=yes,status=no,scrollbars=yes,toolbar=0,directories=0,menubar=0,location=0,copyhistory=0,width=600,height=600,left=200";


imageWindow[numAll] = window.open("","manuscript"+numAll,PARAMS);
    imageWindow[numAll].focus();
imageWindow[numAll].document.write("<head><title>Versioning Machine--Manuscript Image </title><script>window.resizeTo(550,650);</script><style type='text/css'><!-- body { background: white; solid navy: overflow: hidden; margin: 0;} --> </style></head><body scroll='no'><applet style='border: 20px; border-style: solid; border-color: #cccc66;' code='LightApp.class' archive='../src/lightapp.jar' width=500 height=700>");

imageWindow[numAll].document.write("<param name=num value='"+numimage+"'>");
imageWindow[numAll].document.write("<param name=tile value='yes'>");
for(count=0;count<witnesses.length;count++){
witimagelen = eval(witnesses[count]).length;
for(i=0;i<witimagelen;i++)
{
file =  eval(witnesses[count])[i];
imageWindow[numAll].document.write("<param name=filename"+thisimg+" value='images/"+file+"'>");
thisimg++;
}
}
imageWindow[numAll].document.write("</applet></body>");
num++;

        }

function changeStyle()
{
  for(i=0;i<matchingNodes.length;i++)
  {
	

	if(matchingNodes[i].style.fontWeight=="bold")
	{
	matchingNodes[i].style.fontWeight="normal";
	}else{
	matchingNodes[i].style.fontWeight="bold";
	}
	}
}


// normalize the style from bold 
function normalStyle()
{
  for(i=0;i<matchingNodes.length;i++)
  {
	

	matchingNodes[i].style.fontWeight="normal";
	}
}

/**
  * 
  *@AK redid this function to work with netscape/mozilla
  * getElementByTag made redundant
  *
  */
// line matching function
function getMatching(name){
matchingNodes = new Array();
var numFound=0;
var obj = document.getElementById("manuscriptarea");
var temp_node;
var divs = new Array;
var mypaper;

count=0;
 for(i=0;i<obj.childNodes.length;i++)
  {
	temp_node = obj.childNodes[i];
	if(temp_node != null && temp_node.nodeName =="DIV"){
	  divs[count]= temp_node;
	  count++;
	}
	
}	
	for(k =0; k < divs.length; k++){
    mypaper = divs[k];

for(r = 0; r< mypaper.childNodes.length; r++){	
	if(mypaper.childNodes[r].nodeName =="DIV"){
	  var thisNode = mypaper.childNodes[r];
    for(j=0;j<thisNode.childNodes.length;j++)
      {
       if(thisNode.childNodes[j].id == name)
        {
         matchingNodes[numFound]= thisNode.childNodes[j];
         numFound++;
        }
      }
	}
}

}
	  




changeStyle();

}








<!-- everything below this is new -->
var myimages=new Array()
function preloadimages(){
for (i=0;i<preloadimages.arguments.length;i++){
myimages[i]=new Image()
myimages[i].src=preloadimages.arguments[i]
}
}


preloadimages("../vm-images/indexdown.jpg","../vm-images/new_versiondown.jpg","../vm-images/leftdown.jpg","../vm-images/rightdown.jpg","../vm-images/firstdown.jpg","../vm-images/lastdown.jpg","../vm-images/viewdown.jpg","../vm-images/closedown.jpg","../vm-images/close_notedown.jpg");

/**
  * written by Jarom orignally but modified by AK 27th of April 2003
  *
  */

function imageSwap(name,type){
matchingNodes = new Array();
var numFound=0;
var msarea = document.getElementById("manuscriptarea");
for(i=0;i<msarea.childNodes.length;i++)
{
var current = msarea.childNodes[i];
if(current.nodeName=="DIV"){
for(j=0;j<current.childNodes.length;j++)
{
  var this_man = current.childNodes[j];
for(k=0;k<this_man.childNodes.length;k++)
{
  var another_man = this_man.childNodes[k];
  //alert(another_man.id + "  " + another_man.nodeName);
	for(l=0;l<another_man.childNodes.length;l++)
	{
		var that_man = another_man.childNodes[l];
  	if(that_man.id == 'noteicon')
  	{
//	alert("Adding noteicon");
	  // assuming image is the first child
   	matchingNodes[numFound]= that_man.childNodes[0];
   	numFound++;
  	}
	}
}
}
}// current IF
}
swap(name,type);
}


function swap(name,type)
{
  	//alert("in swap :" + name + "  type: "+ type);
	//alert(matchingNodes.length);
  for(i=0;i<matchingNodes.length;i++)
  {
 	if(matchingNodes[i].id==name) {
	 // alert("found the matching nodes...");
  	matchingNodes[i].src="../vm-images/"+type+"2.jpg";
	//alert("before: "+matchingNodes[i].src);
	document.getElementById(matchingNodes[i].id).src ="../vm-images/"+type+"2.jpg";
  	matchingNodes[i].src="../vm-images/"+type+"2.jpg";
	//alert("after: "+matchingNodes[i].src);
 	}
   }
}


function createSplashWindow()
{
    var w, h;
    var x, y;
    var s;

    //  First calculate the size and position for the window
    w = 400;
    h = 320;
    
    //  We need to test if the screen object exists because
    //  older browsers don't support it.
    if ( window.screen )
    {
        x = (screen.width-w)/2;
        y = (screen.height-h)/3;
    }
    else
    {
        x = 100;
        y = 100;
    }
    s = "width=" + w + ",height=" + h + ",left=" + x + ",top=" + y;
    
    //  create the window with just a title bar
    window.open( "../src/splash.html",
                    "SplashWindow",
                    s + ",resizable=no,scrollbars=no,status=no" );
}

function fetchCookie( sName )
{
    var sValue = "";
    var index = 0;

    //  The "cookie" property on the document is actually a
    //  single string of the form "name=value; name2=value2; ..."
    //  As a result we must search through the cookie string
    //  to find the name=value pair that we are looking for.
    //
    if( document.cookie )
        index = document.cookie.indexOf( sName + "=" );
    else
        index = -1;

    if ( index < 0 )
    {
        sValue = "";
    }
    else
    {
        var nBegin = document.cookie.indexOf( "=", index ) + 1;
        if ( 0 < nBegin )
        {
            var nEnd = document.cookie.indexOf( ";", nBegin );
            if ( nEnd < 0 )
                nEnd = document.cookie.length;
            sValue = document.cookie.substring( nBegin, nEnd );
        }
        else
        {
            sValue = "";
        }
    }
    return sValue;
}

function doSplashWindow()
{   
    //  we use a cookie so the window is only displayed
    //  once per session.  If the visitor closes all of
    //  their open browser windows and then returns to the
    //  site the splash window will show again.
    if ( "" == fetchCookie( "Splash" ) )
        setTimeout( "createSplashWindow()", 0.5*1000 );

    document.cookie = "Splash=yes;";
}

doSplashWindow();




