var appCache = window.applicationCache;

// REFRESH
// Bound to a link to allow a user to refresh the page and cache once
// the cache is available.
function userCacheRefresh(installFlag) {
  var contextAction = (installFlag) ? "installed": "updated";
  if (confirm("The Offline Bible has been " + contextAction + " successfully. Reload?")) {
    window.location.reload();
  }
  return false;
};

// CREATED
// The application cache has been created. This only occurs once,
// the first time that the application cache is installed.
function handleCacheCreated(e) {
  $("#status").addClass("success");
  $("#status > div").hide();
  $("#status #status-installed").fadeIn();
};

// CHECKING
// The page is looking for the cache manifest and checking whether
// an update is required.
function handleCacheChecking(e) {
  $("#status > div").hide();
  $("#status #status-checking").fadeIn();
};

// DOWNLOADING
// The application cache manifest has been found and resources are
// now being downloaded.
function handleCacheDownloading(e) {
  $("#status > div").hide();
  $("#status #status-downloading").fadeIn();
};

// ERROR
// The manifest changed during download, or returned a 404/410 error
// code. This will result in the cache being deleted.
function handleCacheError(e) {
  $("#status").addClass("fail");
  $("#status > div").hide();
  $("#status #status-error").fadeIn();
};

// NO UPDATE
// The manifest was checked and no update was required.
function handleCacheNoUpdate(e) {
  $("#status > div").hide();
  $("#status #status-available").fadeIn();
}

// OBSOLETE
// The manifest could not be found and the application cache will
// therefore be deleted.
function handleCacheObsolete(e) {
  $("#status").addClass("fail");
  $("#status > div").hide();
  $("#status #status-obsolete").fadeIn();
}

// PROGRESS CHANGED
// The cache is being downloaded and stored locally. This fires
// multiple times as each manifest entry is downloaded and stored on
// the local device.
function handleCacheProgress(e) {
  if (e.lengthComputable) {
    $("#status-downloading .progress").css("width", Math.ceil(((100/e.total) * e.loaded) * 2).toString() + "px");
    $("#status-downloading .progress-value").text(Math.ceil((100/e.total) * e.loaded).toString() + "%");
  }
  else {
    $("#status-downloading .progress").css("width", "200px");
    $("#status-downloading .progress-value").text("Downloading...");
  }
};

// READY
// The application cache has been successfully updated. The local
// resources will be served when the current page is next refreshed.
function handleCacheUpdateReady(e) {
  appCache.swapCache();
  $("#status").addClass("success");
  $("#status > div").hide();
  $("#status #status-updated").fadeIn();
};

if (appCache)
{
  appCache.addEventListener('cached', handleCacheCreated, false);           // Fired after the first cache of the manifest.
  appCache.addEventListener('checking', handleCacheChecking, false);        // Checking for an update. Always the first event fired in the sequence.
  appCache.addEventListener('downloading', handleCacheDownloading, false);  // An update was found. The browser is fetching resources.
  appCache.addEventListener('error', handleCacheError, false);              // The manifest returns 404 or 410, the download failed, or the manifest changed while the download was in progress.
  appCache.addEventListener('noupdate', handleCacheNoUpdate, false);        // Fired after the first download of the manifest.
  appCache.addEventListener('obsolete', handleCacheObsolete, false);        // Fired if the manifest file returns a 404 or 410. This results in the application cache being deleted.
  appCache.addEventListener('progress', handleCacheProgress, false);        // Fired for each resource listed in the manifest as it is being fetched.
  appCache.addEventListener('updateready', handleCacheUpdateReady, false);  // Fired when the manifest resources have been newly redownloaded.
}

$(document).ready(
  function () {
    if (!window.applicationCache) {
      $("#status div").hide();
      $("#status-not-supported").fadeIn();
    }
    $("#status a.installRefresh").bind("click", function () { userCacheRefresh(true); });
    $("#status a.updateRefresh").bind("click", function () { userCacheRefresh(false); });
    
    $(window).bind('hashchange', function(e) { var vr = $.bible.parseRef(window.location.hash.substring(1)); displayPassage(vr); });
    if (window.location.hash) { var vr = $.bible.parseRef(window.location.hash.substring(1)); displayPassage(vr); }
    
    $("#indicator").bind("selectstart", function () {return false; });
    $("#header").bind("selectstart", function () {return false; });
    
    $(window).bind("mousemove", function (e) {
        var indicator = $("#indicator");
        if (e.clientY > 79) { 
          indicator.fadeOut(); 
          $("#nav rect").attr("class","");
          return; 
        } else {
          indicator.fadeIn();
  
          var poly = $("#pointer-poly");
          var nav = $("#nav");
          
          var indicatorText = $("#indicator span");
          var header = $("#header");
          var proportion = (100 / header.width()) * (e.clientX - header.offset().left);
          var x = e.clientX - Math.ceil((indicator.width()) / 100 * proportion);
          var bm = BibleBookmark.FromPosition(proportion);
          if (bm.bookId() < 40) {
            indicator.removeClass("nt");
            indicator.addClass("ot");
          } else {
            indicator.removeClass("ot");
            indicator.addClass("nt");
          }
          
          $("#nav rect").attr("class","");
          $("#navBook" + bm.bookId().toString()).attr("class","hover");
          
          var p1 = 1.3 * proportion - 12;
          var p2 = 1.3 * proportion;
          var p3 = 1.3 * proportion + 12;
          p1 = (p1 < 0) ? 0 : p1;
          p3 = (p3 > 130) ? 130 : p3;
          var text = $.bible.getBook(bm.bookId()).text + " " + bm.chapterNum();
          poly.attr("points", p2.toString() + ",0 " + p1.toString() + ",12 0,12 0,37 130,37 130,12 " + p3.toString() + ",12, " + p2.toString() + ",0");
          
          
          
          indicator.css("left", x.toString() + "px");
          indicatorText.text(text); 
        }
      }).bind("click", function (e) {
        if (e.clientY < 81) { 
          var header = $("#header");
          var proportion = (100 / header.width()) * (e.pageX - header.offset().left);
          var vr = VerseReference.fromPosition(proportion);
          window.location.hash = "#" + $.bible.getBook(vr.bookId).name + vr.chapterNumber;
        }
      });
  }
);

function displayPassage(vr)
{
  $.get('/bibles/kjv/' + vr.bookId + '/' + vr.chapterNumber + '.html').success(
    function (data) { 
      var prevChapter = VerseReference.fromChapterId(vr.chapterId - 1);
      var nextChapter = VerseReference.fromChapterId(vr.chapterId + 1);

      $('#chapter').html(data);
      $('#location').text($.bible.getBook(vr.bookId).text + ' ' + vr.chapterNumber.toString()).attr("title", vr.toLongString());
      
      if (prevChapter) { $('#prevChapter').attr('href', '#' + $.bible.getBook(prevChapter.bookId).name.toLowerCase() + prevChapter.chapterNumber.toString()).show(); }
      if (nextChapter) { $('#nextChapter').attr('href', '#' + $.bible.getBook(nextChapter.bookId).name.toLowerCase() + nextChapter.chapterNumber.toString()).show(); }
      
      $("#chapter p rt > a").bind("mouseover", function () { $("#chapter p rt > a." + $(this).attr("class").toString()).css("background-color", "yellow"); } )
        .bind("mouseout", function () { $("#chapter p rt > a." + $(this).attr("class").toString()).css("background-color", "transparent"); })
        .bind("click", function () { alert("Lexicon not yet available"); });
      $("body").scrollTop(0);
    }
  );
  
}
