// LaoBible.js: script for navigation, name highlighting and footnote display

// Arrays of English and Lao book names
var BooksEng=["Genesis","Exodus","Leviticus","Numbers","Deuteronomy","Joshua",
  "Judges","Ruth","1 Samuel","2 Samuel","1 Kings","2 Kings","1 Chronicles","2 Chronicles",
  "Ezra","Nehemiah","Esther","Job","Psalms","Proverbs","Ecclesiastes","Songs",
  "Isaiah","Jeremiah","Lamentations","Ezekiel","Daniel","Hosea","Joel","Amos",
  "Obadiah","Jonah","Micah","Nahum","Habakkuk","Zephaniah","Haggai","Zechariah","Malachi",
  "Matthew","Mark","Luke","John","Acts","Romans","1 Corinthians","2 Corinthians",
  "Galatians","Ephesians","Philippians","Colossians","1 Thessalonians","2 Thessalonians",
  "1 Timothy","2 Timothy","Titus","Philemon","Hebrews","James","1 Peter","2 Peter",
  "1 John","2 John","3 John","Jude","Revelation"];
var BooksLao = ["ປະຖົມມະການ","ອົບພະຍົບ","ກົດລະບຽບການເລວີ","ຈົດເຊັນບັນຊີ",
  "ພຣະບັນຍັດສອງ","ໂຢຊວຍ","ພວກຜູ້ປົກຄອງ","ນາງຣຸດ","1 ຊາມູເອນ","2 ຊາມູເອນ",
  "1 ກະສັດ","2 ກະສັດ","1 ຂ່າວຄາວ","2 ຂ່າວຄາວ","ເອັດຊະຣາ","ເນເຮມີຢາ","ເອສະເທີ",
  "ໂຢບ","ເພງສັນລະເສີນ","ສຸພາສິດ","ປັນຍາຈານ","ຍອດເພງ","ເອຊາຢາ","ເຢເຣມີຢາ","ເພງຄ່ຳຄວນ",
  "ເອເສກຽນ","ດານີເອນ","ໂຮເຊອາ","ໂຢເອນ","ອາໂມດ","ໂອບາດີຢາ","ໂຢນາ","ມີກາ","ນາຮູມ",
  "ຮາບາກຸກ","ເຊຟານີຢາ","ຮັກກາຍ","ເຊກາຣີຢາ","ມາລາກີ","ມັດທາຍ","ມາຣະໂກ","ລູກາ","ໂຢຮັນ",
  "ກິດຈະການ","ໂຣມ","1 ໂກຣິນໂທ","2 ໂກຣິນໂທ","ຄາລາເຕຍ","ເອເຟໂຊ","ຟີລິບປອຍ","ໂກໂລຊາຍ",
  "1 ເທຊະໂລນິກ","2 ເທຊະໂລນິກ","1 ຕີໂມທຽວ","2 ຕີໂມທຽວ","ຕີໂຕ","ຟີເລໂມນ","ເຮັບເຣີ",
  "ຢາໂກໂບ","1 ເປໂຕ","2 ເປໂຕ","1 ໂຢຮັນ","2 ໂຢຮັນ","3 ໂຢຮັນ","ຢຸດາ","ພຣະນິມິດ"];
var Chapters =[50,40,27,36,34,24,21,4,31,24,22,25,29,36,10,13,10,42,150,31,12,8,
  66,52,5,48,12,14,3,9,1,4,7,3,3,3,2,14,4,28,16,24,21,28,16,16,13,6,6,4,4,5,3,6,
  4,3,1,13,5,5,3,5,1,1,1,22];

var xsl;

// Initialization
function initialize()
{
  enableJavaScript();
  fillBookList();
  
  var i,buttons=document.getElementsByTagName("div");
  for(i=0; i<buttons.length; i++)
  {
    if(buttons[i].className == 'icon')
    {
      buttons[i].onmousedown = pressButton;
      buttons[i].onmouseup = releaseButton;
      buttons[i].onmouseout = releaseButton;
    }
  }

  // Load the correct transform table XML, then load the selected chapter XML
  toggleEnglish(showEnglish());
}

// Highlight or remove highlights from proper nouns (names of people or places)
function setNames(n)
{
  setCookie('highlightStyle',n,30);
  setCookie('highlightNames',1,30);
  markNames();
}

function markNames()
{
  var n = getCookie('highlightNames'), s = getCookie('highlightStyle');
  if(typeof(n) == 'undefined') n = 0;
  if(typeof(s) == 'undefined') s = 2;
  if(n == 0) s = 0;
  document.getElementById('book').className='highlightNames'+s;
  var hb = document.getElementById('highlights');
  if(hb) hb.className = (n!=0)?'icon1on':'icon1off';
}

// Hide the Javascript must be enabled message
function enableJavaScript(n)
{
  var notice=document.getElementById('notice');
  if(notice) notice.style.display = 'none';
}

function showHLMenu(s)
{
  var opt=document.getElementById('options');
  if(s) s =((opt.style.display =='block') ? 0 : 1);
  opt.style.display = s ?'block':'none';
}

function toggleHighlights()
{
  var n=getCookie('highlightNames');
  if(typeof(n) == 'undefined' || (n == 0)) n = 1; else n = 0;
  setCookie('highlightNames',n,30);
  markNames();
}

function showEnglish()
{
  var n=getCookie('englishTips');
  return ((typeof(n) == 'undefined') || (n == 0)) ? 0 : 1;
}

function toggleEnglish(n0)
{
  var n,bookNo,chapter,savedBook=getCookie("BookNo"),savedChapter=getCookie("Chapter");

  if(isNaN(savedBook)) bookNo = 1; else bookNo = Number(savedBook);
  if(isNaN(savedChapter) || savedChapter == "") chapter = 1; else chapter = Number(savedChapter);

  selectBook(bookNo); selectChapter(chapter);

  if(arguments.length > 0) n = n0;
  else n = showEnglish() ? 0 : 1;

  setCookie('englishTips',n,30);
  
  // Set the icon appropriately by changing the class name
  var te=document.getElementById('tooltips');
  if(te)te.className = n?"icon2on" : "icon2off";

  // Load the correct transform table XML
  xsl=loadXMLDoc(n ? "/Bible/LaoBibleXSL.xml" : "/Bible/LaoBibleXSLalt.xml" );
  
  // And refresh the page content
  updatePage(bookNo,chapter);
}

function gotoBook(n)
{
  location='./'+filePrefix(n)+'1.htm';
  return false;
}

function gotoChapter(t)
{
  location='./'+t+'.htm';
  return false;
}

// Get the file prefix for a given English book name or book number (1-66)
function filePrefix(n)
{
  if(isNaN(n))
    return n.toString().replace(" ","");
  else
    return BooksEng[n-1].replace(" ","");
}

function fillBookList()
{
  var n,opt,bkList=document.getElementById("bklist");
  for(n=0;n<66;n++)
  {
    opt = document.createElement("option");
    bkList.appendChild(opt);     // In IE, must append option first!
    opt = bkList.options[n];
    opt.value = BooksEng[n];
    opt.text = BooksLao[n];
  }
}

function selectBook(nBook)
{
  var n,bkList=document.getElementById('bklist');
  for(n=0; n<bkList.options.length; n++)
    bkList.options[n].selected=false;
  bkList.options[nBook-1].selected=true; 
  fillChapterList(nBook);
}

function fillChapterList(nBook)
{
  var n,opt,chList=document.getElementById('chlist');
  for(n=chList.options.length; n>0; n--)
    chList.removeChild(chList.options[n-1]);
  for(n=1; n<=Chapters[nBook-1]; n++)
  {
    opt = document.createElement("option");
    chList.appendChild(opt);
    opt = chList.options[n-1];     // In IE, must append option first!
    opt.value = opt.text = n.toString();
  }
}

function selectChapter(nChapter)
{
  var n,opt,chList=document.getElementById('chlist');
  for(n=0; n<chList.options.length; n++)
    chList.options[n].selected=false;
  chList.options[nChapter-1].selected=true;
}

// Document navigation: go to fisrt chapter if currently selected book, then to previous book
function gotoPreviousBook()
{
  var nBook,bkList = document.getElementById("bklist"),
    nCh, chList = document.getElementById("chlist");
  nBook = bkList.selectedIndex+1;
  nCh = chList.selectedIndex+1;
  if(nCh == 1)
  {
    if(nBook > 1) nBook = nBook - 1; else nBook = 1;
  }
  selectBook(nBook); updatePage(nBook,1);
}

function gotoNextBook()
{
  var nBook,bkList = document.getElementById("bklist");
  nBook = bkList.selectedIndex+1;

  if(nBook < 66 )nBook = nBook + 1; else nBook = 66;
  selectBook(nBook); updatePage(nBook,1);
}

function gotoPreviousChapter()
{
  var nCh,nBook,bkList = document.getElementById("bklist"),
    chList = document.getElementById("chlist");
  nBook = bkList.selectedIndex+1;
  nCh = chList.selectedIndex+1;

  if(nCh > 1) nCh = nCh - 1;
  else
  {
    if(nBook > 1)
    {
      nBook = nBook - 1; nCh = Chapters[nBook-1];
      selectBook(nBook);
    }
  }
  selectChapter(nCh); updatePage(nBook,nCh);
}

function gotoNextChapter()
{
  var nCh,nBook,bkList = document.getElementById("bklist"),
    chList = document.getElementById("chlist");
  nBook = bkList.selectedIndex+1;
  nCh = chList.selectedIndex+1;
  
  if(nCh < Chapters[nBook-1]) nCh = nCh + 1;
  else
  {
    if(nBook < 66)
    {
      nBook = nBook + 1; nCh = 1;
      selectBook(nBook);
    }
  }
  selectChapter(nCh); updatePage(nBook,nCh);
}

function updateSource(bc)
{
  var nBook,bkList=document.getElementById("bklist");
  nBook = bkList.selectedIndex+1;
  if(bc == 0)
  {
    fillChapterList(nBook);
    selectChapter(1);
  }
  
  var nCh,chList=document.getElementById("chlist");
  nCh = chList.selectedIndex+1;
  updatePage(nBook,nCh);
}

// AJAX loading of XML document
function loadXMLDoc(dname)
{
  var xhttp;
  if (window.XMLHttpRequest)
    xhttp=new XMLHttpRequest();
  else
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");

  xhttp.open("GET",dname,false);
  xhttp.send("");
  return xhttp.responseXML;
}

function displayXML(path)
{
  var xml=loadXMLDoc(path);

  // code for IE
  if(window.ActiveXObject)
  {
    ex=xml.transformNode(xsl);
    document.getElementById("middleSection").innerHTML=ex;
  }
  // code for Mozilla, Firefox, Opera, etc.
  else if (document.implementation && document.implementation.createDocument)
  {
    xsltProcessor=new XSLTProcessor();
    xsltProcessor.importStylesheet(xsl);
    resultDocument = xsltProcessor.transformToFragment(xml,document);
    resultDocument.id = "bookContent";
    var ms=document.getElementById("middleSection")
    ms.innerHTML="";
    ms.appendChild(resultDocument);
    // If using Chrome, must delete discretionary hyphens - Chrome messes up with them,
    // and using explicit &shy; is no different, so best without trying to split names.
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    if(is_chrome) ms.innerHTML = ms.innerHTML.replace(/­/g,'');
  }
}

function updatePage(bookNo,chapter)
{
  var bookPage=document.getElementById("middleSection"),
    bookText=document.getElementById("bookContent");
  if(bookText) bookpage.removeChild(bookText);
  document.title = "Lao Bible Online - "+filePrefix(bookNo)+" "+chapter;
  displayXML("/Bible/books/"+filePrefix(bookNo)+chapter+".xml");
  
  var title=document.getElementById("bookHeader");
  
  if(Chapters[bookNo-1] > 1)
    title.innerHTML = BooksLao[bookNo-1]+" - ບົດ​ທີ "+chapter;
  else
    title.innerHTML = BooksLao[bookNo-1];
  showMenu(0);
  markNames();
  setCookie("BookNo",bookNo,30); setCookie("Chapter",chapter,30);
  if(chapter == 1)
    document.getElementById("previousBook").title = "Previous Book";
  else
    document.getElementById("previousBook").title = "Start of Book";
}

function showMenu(n)
{
  var bMenu=document.getElementById('booklist'),
    sMenu=document.getElementById('selectmenu');

  if(n)
  {
    if(bMenu) bMenu.style.display='block';
    if(sMenu) sMenu.style.display='none';
  }
  else
  {
    if(bMenu) bMenu.style.display='none';
    if(sMenu) sMenu.style.display='block';
  }
}

function setCookie(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++)
  {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
    {
      return unescape(y);
    }
  }
}

function goHome()
{
  location="/index.php"; return false;
}

// Get the absolute position of the current element
function findPos(obj) {
	var x=y=0;
	if (obj.offsetParent) {
  	do {
  			x += obj.offsetLeft;
  			y += obj.offsetTop;
  		} while (obj=obj.offsetParent); //this is intentional, and terminates loop when offsetParent is undefined
	}
	return [x,y];
}

function pressButton()
{
  this.style.margin='3px 1px 1px 3px';
}

function releaseButton()
{
  this.style.margin='2px';
}


function showFootnote(t,id)
{
  var ref=document.getElementById(id);
  if(typeof(ref)!='undefined')
  {
    var base=document.getElementById("middleSection");
    if(base == null) base = document.getElementById("body");
    var p=findPos(ref),
      fn=document.getElementById("footnote"),dy=10; 
    if(Browser.Version() < 999) dy = 18;
    fn.innerHTML = t;
    fn.style.display='block';
    fn.style.top=(p[1]-fn.offsetHeight-dy)-base.scrollTop+"px";
    fn.style.left=(p[0]+ref.offsetWidth+2)-base.scrollLeft+"px";
  }
}

function hideFootnote()
{
  var fn=document.getElementById("footnote");
  if(fn) fn.style.display='none';
}

var Browser = {
// courtesy of Bjørn Arild Mæland  http://obvcode.blogspot.com/2007/11/easiest-way-to-check-ie-version-with.html
  Version: function() {
    var version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
    // bah, IE again, lets downgrade version number
      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return version;
  }
}

