/*
 * OFFLINE BIBLE - BIBLE ENTITIES
 * Objects used to interact with Bible data including
 * verses, books, passages and references.
 *
 * You are free to modify or redistribute this code and
 * any derived works, but where possible please do so
 * without charge. Thanks.
 *
 * Nathan Kitchen (offlinebible.com)
 */

// NAME: BibleTestament
// DESC: Contains data about one of the testaments of the Bible.
function BibleTestament(name, text, title, books, length)
{
  this._name   = name   ? name   : 0;
  this._text   = text   ? text   : 0;
  this._title  = title  ? title  : "";
  this._books  = books  ? books  : new Array();
  this._length = length ? length : 0;

  BibleTestament.prototype.name   = function() { return this._name; }
  BibleTestament.prototype.text   = function() { return this._text; }
  BibleTestament.prototype.title  = function() { return this._title; }
  BibleTestament.prototype.books  = function() { return this._books; }
  BibleTestament.prototype.length = function() { return this._length; }
}

// NAME: BibleBook
// DESC: Contains data about a single book of the Bible.
function BibleBook(bookId, name, text, title, abbr, length)
{
  this._bookId        = bookId ? bookId : 0;
  this._name          = name   ? name   : 0;
  this._text          = text   ? text   : 0;
  this._title         = title  ? title  : "";
  this._abbreviations = abbr   ? abbr   : new Array();
  this._length        = length ? length : 0;

  BibleBook.prototype.bookId    = function() { return this._bookId; }           // Integer value (1-66)
  BibleBook.prototype.name    = function() { return this._name; }             // Computer readable (no spaces) e.g. "1Samuel"
  BibleBook.prototype.text    = function() { return this._text; }             // Human readable (short) e.g. "1 Samuel"
  BibleBook.prototype.title   = function() { return this._title; }            // Human readable (long) e.g. "The first book of Samuel"
  BibleBook.prototype.abbreviations = function() { return this._abbreviations; }    // Array of abbreviations e.g. ["1sa", "1sam", "1sml"]
  BibleBook.prototype.length    = function() { return this._length; }           // Number of chapters in the book
}

// NAME: BibleBookmark
// DESC: Contains data referencing a single chapter of the Bible.
function BibleBookmark(bookId, chapterId, chapterNum)
{
  this._bookId    = bookId     ? bookId     : 0;
  this._chapterId   = chapterId  ? chapterId  : 0;
  this._chapterNum  = chapterNum ? chapterNum : 0;

  BibleBookmark.prototype.bookId     = function() { return this._bookId; }
  BibleBookmark.prototype.chapterId  = function() { return parseInt(this._chapterId); }
  BibleBookmark.prototype.chapterNum = function() { return this._chapterNum; }
  BibleBookmark.prototype.text       = function() { return Bible.Books()[this._bookId - 1].text() + " " + this._chapterNum; }
  BibleBookmark.prototype.position   = function() { return (100 / 1189) * this._chapterId; }
}
BibleBookmark.ToJson   = function(realBookmark) { return JSON.stringify([realBookmark.bookId(), realBookmark.chapterId(), realBookmark.chapterNum()]); }  
BibleBookmark.FromJson = function(jsonBookmark) { var data = JSON.parse(jsonBookmark); return new BibleBookmark(data[0], data[1], data[2]); }
BibleBookmark.FromChapterId = function(chapterId)
{
  var chapterNumber = chapterId;

  for(var i=0;i<66;i++)
  {
    var book = Bible._books[i];
    if (book.length() - chapterNumber > 0)
    {
      return new BibleBookmark(book.bookId(), chapterId, Math.floor(chapterNumber + 1));
    }
    else
    {
      chapterNumber = chapterNumber - book.length();
    }
  }
  return "[Error]: Could not find chapter";
}
BibleBookmark.FromPosition = function(position) { return BibleBookmark.FromChapterId(position*11.89); }

// NAME: Bible
// DESC: Contains information on the Bible and the books within it. Provides methods
// for accessing the books by testament, position, and other information.
function Bible() {}
Bible._books = [
  new BibleBook(1,"Genesis","Genesis","The book of Genesis",["ge","gen","genesis"],50),
  new BibleBook(2,"Exodus","Exodus","The book of Exodus",["ex","exo","exodus"],40),
  new BibleBook(3,"Leviticus","Leviticus","The book of Leviticus",["le","lev","levi","leviticus"],27),
  new BibleBook(4,"Numbers","Numbers","The book of Numbers",["nu","num","numb","numbers"],36),
  new BibleBook(5,"Deuteronomy","Deuteronomy","The book of Deuteronomy",["de","deut","deuter","deuteronomy"],34),
  new BibleBook(6,"Joshua","Joshua","The book of Joshua",["jos","josh","joshua"],24),
  new BibleBook(7,"Judges","Judges","The book of Judges",["judge","judges"],21),
  new BibleBook(8,"Ruth","Ruth","The book of Ruth",["ru","rut","ruth"],4),
  new BibleBook(9,"Samuel1","1 Samuel","The first book of Samuel",["1sa","1sam","1samuel"],31),
  new BibleBook(10,"Samuel2","2 Samuel","The second book of Samuel",["2sa","2sam","2samuel"],24),
  new BibleBook(11,"Kings1","1 Kings","The first book of the Kings",["1k","1ki","1kin","1king","1kings"],22),
  new BibleBook(12,"Kings2","2 Kings","The second book of the Kings",["2k","2ki","2kin","2king","2kings"],25),
  new BibleBook(13,"Chronicles1","1 Chronicles","The first book of the Chronicles",["1ch","1chr","1chron","1chronicles"],29),
  new BibleBook(14,"Chronicles2","2 Chronicles","The second book of the Chronicles",["2ch","2chr","2chron","2chronicles"],36),
  new BibleBook(15,"Ezra","Ezra","The book of Ezra",["ez","ezr","ezra"],10),
  new BibleBook(16,"Nehemiah","Nehemiah","The book of Nehemiah",["ne","neh","nehemiah"],13),
  new BibleBook(17,"Esther","Esther","The book of Esther",["es","est","esth","esther"],10),
  new BibleBook(18,"Job","Job","The book of Job",["job"],42),
  new BibleBook(19,"Psalms","Psalms","The book of the Psalms",["ps","psa","psalm","psalms"],150),
  new BibleBook(20,"Proverbs","Proverbs","The book of Proverbs",["pro","prov","proverb","proverbs"],31),
  new BibleBook(21,"Ecclesiastes","Ecclesiastes","The book of Ecclesiastes",["ec","ecc","eccles","ecclesia","ecclesiastes"],12),
  new BibleBook(22,"SongOfSongs","Song of Songs","The Song of Songs, which is Solomons",["so","son","song","songs","sol","solo","solomon","song of songs","song of solomon"],8),
  new BibleBook(23,"Isaiah","Isaiah","The book of the prophet Isaiah",["is","isa","isaiah"],66),
  new BibleBook(24,"Jeremiah","Jeremiah","The book of the prophet Jeremiah",["je","jer","jerem","jeremiah"],52),
  new BibleBook(25,"Lamentations","Lamentations","The Lamentations of Jeremiah",["lam","lament","laments","lamentation","lamentations"],5),
  new BibleBook(26,"Ezekiel","Ezekiel","The book of the prophet Ezekiel",["ez","eze","ezek","ezekiel"],48),
  new BibleBook(27,"Daniel","Daniel","The book of the prophet Daniel",["da","dan","daniel"],12),
  new BibleBook(28,"Hosea","Hosea","The book of the prophet Hosea",["ho","hos","hose","hosea"],14),
  new BibleBook(29,"Joel","Joel","The book of the prophet Joel",["joe","joel"],3),
  new BibleBook(30,"Amos","Amos","The book of the prophet Amos",["am","amo","amos"],9),
  new BibleBook(31,"Obadiah","Obadiah","The book of the prophet Obadiah",["ob","oba","obad","obadiah"],1),
  new BibleBook(32,"Jonah","Jonah","The book of the prophet Jonah",["jon","jonah"],4),
  new BibleBook(33,"Micah","Micah","The book of the prophet Micah",["mi","mic","micah"],7),
  new BibleBook(34,"Nahum","Nahum","The book of the prophet Nahum",["na","nah","nahum"],3),
  new BibleBook(35,"Habakkuk","Habakkuk","The book of the prophet Habakkuk",["hab","haba","habak","habakkuk","habakuk"],3),
  new BibleBook(36,"Zephaniah","Zephaniah","The book of the prophet Zephaniah",["zeph","zephan","zephaniah"],3),
  new BibleBook(37,"Haggai","Haggai","The book of the prophet Haggai",["hag","hagg","haggai"],2),
  new BibleBook(38,"Zechariah","Zechariah","The book of the prophet Zechariah",["zach","zacheriah","zech","zechariah"],14),
  new BibleBook(39,"Malachi","Malachi","The book of the prophet Malachi",["mal","malachi"],4),
  new BibleBook(40,"Matthew","Matthew","The gospel according to Matthew",["mat","matt","mathew","matthew"],28),
  new BibleBook(41,"Mark","Mark","The gospel according to Mark",["mar","mark"],16),
  new BibleBook(42,"Luke","Luke","The gospel according to Luke",["lu","luk","luke"],24),
  new BibleBook(43,"John","John","The gospel according to John",["john"],21),
  new BibleBook(44,"Acts","Acts","The Acts of the Apostles",["act","acts"],28),
  new BibleBook(45,"Romans","Romans","The letter to the believers in Rome",["rom","rome","roman","romans"],16),
  new BibleBook(46,"Corinthians1","1 Corinthians","The first letter to the believers in Corinth",["1co","1cor","1corinth","1corinthians"],16),
  new BibleBook(47,"Corinthians2","2 Corinthians","The second letter to the believers in Corinth",["2co","2cor","2corinth","2corinthians"],13),
  new BibleBook(48,"Galatians","Galatians","The letter to the believers in Galatia",["ga","gal","galatia","galatians"],6),
  new BibleBook(49,"Ephesians","Ephesians","The letter to the believers in Ephesus",["ep","eph","ephesus","ephesians"],6),
  new BibleBook(50,"Philippians","Philippians","The letter to the believers in Philippi",["phili","phils","philippi","phillipians","philipians","philippians","phillippians"],4),
  new BibleBook(51,"Colossians","Colossians","The letter to the believers in Collossae",["co","col","colossia","collossians","colosians","collosians","colossians"],4),
  new BibleBook(52,"Thessalonians1","1 Thessalonians","The first letter to the believers in Thessalonica",["1th","1thes","1thess","1thessalonia","1thessalonica","1thessalonians"],5),
  new BibleBook(53,"Thessalonians2","2 Thessalonians","The second letter to the believers in Thessalonica",["2th","2thes","2thess","2thessalonia","2thessalonica","2thessalonians"],3),
  new BibleBook(54,"Timothy1","1 Timothy","Paul's first letter to Timothy",["1ti","1tim","1timothy","1timotheus"],6),
  new BibleBook(55,"Timothy2","2 Timothy","Paul's second letter to Timothy",["2ti","2tim","2timothy","2timotheus"],4),
  new BibleBook(56,"Titus","Titus","The letter to Titus",["ti","tit","titus"],3),
  new BibleBook(57,"Philemon","Philemon","The letter to Philemon",["phile","philemon"],1),
  new BibleBook(58,"Hebrews","Hebrews","The letter to the Hebrews",["he","heb","hebrew","hebrews"],13),
  new BibleBook(59,"James","James","James' letter",["ja","jam","james"],5),
  new BibleBook(60,"Peter1","1 Peter","Peter's first letter",["1pe","1pet","1peter"],5),
  new BibleBook(61,"Peter2","2 Peter","Peter's second letter",["2pe","2pet","2peter"],3),
  new BibleBook(62,"John1","1 John","John's first letter",["1jo","1jon","1john"],5),
  new BibleBook(63,"John2","2 John","John's second letter",["2jo","2jon","2john"],1),
  new BibleBook(64,"John3","3 John","John's third letter",["3jo","3jon","3john"],1),
  new BibleBook(65,"Jude","Jude","The letter from Jude",["jude"],1),
  new BibleBook(66,"Revelation","Revelation","The Revelation of Jesus the Christ",["re","rev","revel","revelation","revelations"],22)
];

Bible.OldTestament = function() { return new BibleTestament("Old", "Old Testament", "The first testament in the Bible", Bible._books.slice(0,39), 929); }
Bible.NewTestament = function() { return new BibleTestament("New", "New Testament", "The second testament in the Bible", Bible._books.slice(39,66), 260); }
Bible.Contents = function() { return [Bible.OldTestament(), Bible.NewTestament()]; }
Bible.Books = function() { return Bible._books; }

function BibleNavigator(host, src)
{
  var _dragging = false;
  var _markerPosition = 0;

  var _onClick = null;
  var _onTextRequested = null;
  var _onPositionChanged = null;

  var _element = jQuery(host);
  var _marker = jQuery(document.createElement("button"));
  _marker.addClass("bookmark marker");

  var _tooltip = jQuery(document.createElement("span"));
  _tooltip.addClass("tooltip");
  
  if (src)
  {
    var _image = jQuery(document.createElement('img'));
    _image.attr("src", src);
  }

  var updateMarker = function(position)
  {
    _markerPosition = position;
    _marker.css("left", _markerPosition.toString() + "%");
  }

  _element.bind("selectstart", function(e) { return false; } );
  _element.bind("mousedown", function(e)
      {
        var button = 0;
        if (typeof(e.which) == "number") { button = e.which; }
        else if(typeof(e.button) == "number") { e = e.button; }
        _dragging = (button == 1);
        return false; 
      }
    );
    
  _element.bind("mousemove", function(e)
      {
        var navigator = _element;
        var position = (100.0 / navigator.innerWidth()) * parseInt(e.pageX);

        if (_onTextRequested)
        {
          _tooltip.text(_onTextRequested(position));
        }
        else
        {
          _tooltip.text(position.toString());
        }
        var offset = -(_tooltip.outerWidth() / 100.0) * position;

        _tooltip.css('top', e.pageY + 'px');
        _tooltip.css('left', e.pageX + 'px');
        _tooltip.css('margin-left', offset);
        
        if (_dragging)
        {
          updateMarker(position);
        }

        return false;
      }
    );
    
  _element.bind("mouseup", function(e)
      {
        var navigator = _element;
        var position = (100.0 / navigator.innerWidth()) * parseInt(e.pageX);

        updateMarker(position);
        if (_onPositionChanged) { _onPositionChanged(BibleBookmark.FromPosition(position)); }       

        _dragging = false;
        return true;
      }
    );

  _element.append(_marker);
  _element.append(_tooltip);
  _element.append(_image);

  this.onTextRequested = function(callback)
  {
    _onTextRequested = callback;
  }
  
  this.onPositionChanged = function(callback)
  {
    _onPositionChanged = callback;
  }
  
  this.marker = function(position)
  {
    if (position == null) { return _markerPosition; }
    else { updateMarker(position); }
  }
}

window.onload = jQuery(document).ready(function () {
    var nav = new BibleNavigator( jQuery("#bible"), "http://" + location.host + "/wp-content/themes/offlinebible/images/biblescale.png");
    nav.onTextRequested(function(pos) { return BibleBookmark.FromPosition(pos).text(); } );
});