
var gBibleBookmark;

function onLoad() {
  try {
    $("#app-title").text(tr("appname"));
    $("#logo").click(function () { gBrowsingHistory.mainPage.go(); });
    $("#bible-quick-lookup").click(showBibleLookup);
    $("#search-header").returnKey(doSearchHeader);
    $("#search-mainpage").returnKey(doSearchMainpage);
    $("#search-button").click(doSearchMainpage);
    $("#search-button").attr("value", tr("search.button"));
    $("#search-header").attr("placeholder", tr("search.header.placeholder"));
    $("#search-mainpage").attr("placeholder", tr("search.mainpage.placeholder"));
  } catch (e) { showError(e); }
}
$(document).ready(onLoad);


function showMainPage() {
  try {
    changePage("main", null);
    $("title").text(tr("mainpage.title", [ tr("appname") ]));
    $("#app-title").text(tr("appname"));
    if (gDevice.deviceType == "desktop") {
      $("#search-mainpage").focus();
    } // else mobile: avoid on-screen keyboard without user requesting it

    if ( !gBibleBookmark) {
      if ( !gSettings.bibleBookmark) {
        gSettings.bibleBookmark = "mt. 6";
      }
      gBibleBookmark = new BibleBookmark(gSettings.bibleBookmark);
      gBibleBookmark.save = function(str) {
        gSettings.bibleBookmark = str;
      };
    }
    window.scroll(0, 0);

    if ($("#main-persons").size() > 0) {
      return;
    }
    var containerE = $("#main-page");

    // search
    uiSectionTitle({
      container: $("<div/>").prependTo(containerE),
      text : tr("mainpage.search.section"),
    });

    mainpageBible(containerE);
    mainpageListAll(containerE);
    //mainpageEvents(containerE);
    mainpagePersons(containerE);

  } catch (e) { showError(e); }
}

// main persons
function mainpagePersons(containerE) {
  uiSectionTitle({
    container: $("<div/>").appendTo(containerE),
    text : tr("mainpage.persons.section"),
  });
  var personsE = $("<div id='main-persons' class='button-list'/>").appendTo(containerE);
  var persons = [
    gStorage.getID("I0000"), // Adam
    gStorage.getID("I0002"), // Noah
    gStorage.getID("I0025"), // Abraham
    gStorage.getID("I0060"), // Jacob
    gStorage.getID("I0240"), // David
    gStorage.getID("I1000"), // Jesus
  ];
  for (var i = 0; i < persons.length; i++) {
    var person = persons[i];
    uiObjButton({
      $container : personsE,
      classes : "main-person",
      obj : person,
      navFunc : showDetail,
    });
  }
}

function mainpageListAll(containerE) {
  uiSectionTitle({
    container: $("<div/>").appendTo(containerE),
    text : tr("mainpage.listall.section"),
  });
  var listallE = $("<div id='listall-buttons' class='button-list'/>").appendTo(containerE);
  [ Person, Event, Place ].forEach(function(type) {
    var typename = type.prototype.typename;
    uiButton({
      $container : listallE,
      title : tr("mainpage.listall." + typename + ".button"),
      classes : "listall " + typename,
      icon : "static/" + typename + ".png",
      clickCallback : function() {
        listAll({
          type : type,
          tn : type.prototype.typename,
          navFunc : showDetail,
          errorCallback : showError,
        });
      },
      errorCallback : showError,
    });
  });

  // personal notes
  function showNotes() {
    // HACK fake breadcrum
    $("#breadcrums").empty();
    uiButton({
      $container : $("#breadcrums"),
      title : tr("notes.section"),
      classes : "breadcrum",
      icon : "static/notes.png",
      clickCallback : showNotes,
      errorCallback : showError,
    });

    uiNotePage({
      navFunc : showDetail,
      errorCallback : showError,
    });
  };
  uiButton({
    $container : listallE,
    title : tr("notes.section"),
    icon : "static/notes.png",
    clickCallback : showNotes,
    errorCallback : showError,
  });
}

function mainpageEvents(containerE) {
  gStorage.getAll(Event, function(allEvents) {
    uiTimeline({
      container : $("<div/>").appendTo(containerE),
      events : allEvents,
      navFunc : showDetail,
      errorCallback : showError,
    });
  }, function(e) { console.log(e); });
}

function mainpageBible(containerE) {
  uiSectionTitle({
    container: $("<div/>").appendTo(containerE),
    text : tr("mainpage.bible.section"),
  });
  var $buttons = $("<div id='bible-buttons' class='button-list'/>").appendTo(containerE);
  var $bibleLookup = uiButton({
    $container : $buttons,
    title : tr("mainpage.bible.lookup"),
    classes : "bible-lookup",
    icon : "static/lookup-16.png",
    clickCallback : showBibleLookup,
    errorCallback : showError,
  });
  var $bibleBookmark = uiButton({
    $container : $buttons,
    title : tr("mainpage.bible.personal"),
    classes : "bible-bookmark",
    icon : "static/love.png",
    clickCallback : cbParams(showDetail, gBibleBookmark),
    errorCallback : showError,
  });
  new LoadWeeklyScheduleJSON().loadThisWeek(function(display, bibletexts) {
    var $bibleWeekly = uiButton({
      $container : $buttons,
      title : tr("mainpage.bible.cong"),
      classes : "bible-weekly",
      icon : "static/group.png",
      clickCallback : function() {},
      errorCallback : showError,
    });
    // display is in English, thus need to construct
    //display = bibletexts[0].name + " - " + bibletexts[bibletexts.length - 1].name;
    //bibleWeeklyE.text(tr("mainpage.bible.cong") + ": " + display); // too long
    $bibleWeekly.click(cbParams(showDetail, bibletexts[0],
        bibletexts, tr("mainpage.bible.cong")));
  }, errorNonCritical);
}

function doSearchMainpage() {
  doSearch($("#search-mainpage").val(), function(e) {
    if (e instanceof NoResultException) {
      $("#search-error").text(e).slideDown(800).delay(3000).slideUp(800);
    } else {
      showError(e);
    }
  });
}

function doSearchHeader() {
  doSearch($("#search-header").val(), function(e) {
    $("#search-header").attr("error", e);
    setTimeout(function() {
      $("#search-header").removeAttr("error");
    }, 3000);
  });
  setTimeout(function() {
    $("#search-header").val("");
  }, 10000);
}

function NoResultException() {
  this.message = tr("search.noresult");
}
extend(NoResultException, Exception);

function doSearch(searchTerm, errorCallback) {
  try {
    gStorage.searchFulltext(searchTerm, function(results) {
      if (results.length == 0) {
        throw new NoResultException();
      }
      showDetail(results[0], results, tr("search.resultsfor", searchTerm));
    }, errorCallback);
  } catch (e) { errorCallback(e); }
}
