/**
 * @param $container {JQuery Element}  where to add the note UI
 * @param navFunc
 * @param errorCallback
 */
function uiNotePage(p) {
  assert(typeof(p.navFunc) == "function", "need navFunc");
  assert(typeof(p.errorCallback) == "function", "need errorCallback");
  changePage("main-sub-page", null);
  var $container = $("#main-sub-page");
  $container.empty();
  $container.addClass("notes");

  var text = noteLoad();

  /*uiSectionTitle({
    container: $container,
    text : tr("notes.section"),
  });*/

  var $bibletextBox = $("<div class='bibletext'>").appendTo($container);

  var $textbox = $("<textarea class='notes' autocorrect='off' x-inputmode='verbatim' />").appendTo($container);

  var $buttons = $("<div class='note-buttons notes buttons'/>")
      .appendTo($container);
  /*var $saveDBButton = uiButton({
    $container : $buttons,
    title : tr("notes.save-db"),
    classes : "save-db notes action",
    errorCallback : p.errorCallback,
    clickCallback : function() {
      noteSave(text);
    },
  });*/
  /*var $saveTextButton = uiButton({
    $container : $buttons,
    title : tr("notes.save-text"),
    classes : "save-text notes action",
    errorCallback : p.errorCallback,
    clickCallback : function() {
      downloadFromVariable(text, "text/plain");
    },
  });*/
  function sendAsEmail(to) {
    var title = text.split("\n")[0]; // first line
    title += " - " + tr("notes.section");
    var mailto = "mailto:" + (to ? to : "") +
        "?subject=" + encodeURIComponent(title) +
        "&body=" + encodeURIComponent(text);
    window.open(mailto, "mailto");
  }
  var $sendEmailButton = uiButton({
    $container : $buttons,
    title : tr("notes.send-email"),
    classes : "send-email notes action",
    errorCallback : p.errorCallback,
    clickCallback : function() {
      sendAsEmail();
    },
  });
  var $sendSelfButton = uiButton({
    $container : $buttons,
    title : tr("notes.send-self"),
    classes : "send-self notes action",
    errorCallback : p.errorCallback,
    clickCallback : function() {
      var userAddr = gSettings.userEmailAddr;
      if ( !userAddr) {
        userAddr = prompt("Your email address");
        if ( !userAddr) {
          return;
        }
        gSettings.userEmailAddr = userAddr;
      }
      sendAsEmail(userAddr);
    },
  });

  var lastVerse = null; // avoid re-creating on every keypress
  function onChange() {
    try {
      text = $textbox.val();
      noteSave(text);

      // show bible text
      var caret = $textbox.get(0).selectionStart;
      if ( !caret) {
        $bibletextBox.empty();
        return;
      }
      var colon = text.lastIndexOf(":", caret);
      if (caret - colon > 100) { // too far away
        $bibletextBox.empty();
        return;
      }
      var potential = text.substring(colon - 10, colon + 10);
      potential = potential.replace(/\n/g, " ");
      if (lastVerse == potential) {
        // Keep existing
        return;
      }
      $bibletextBox.empty();
      lastVerse = potential;
      //console.log("caret " + caret + ", colon " + colon + ", potential bt: " + potential);
      var bts = findBibleTexts(potential);
      if (bts.length > 0) {
        var bt = bts[bts.length - 1].obj;
        if (bt.range == 3) { // whole chapter
          return;
        }
        if (bt.range && bt.verses().length > 4) { // too long
          bt.range = 0;
          bt.verseTo = 0;
        }
        var $bibletextAdd = uiButton({
          $container : $bibletextBox,
          title : tr("notes.bibletext.addquote"),
          classes : "add-quote action",
          errorCallback : p.errorCallback,
          clickCallback : function() {
            var quote = " " + bt.quote.replace(/\n/g, " ").trim() + "\n";
            $textbox.val($textbox.val() + quote);
          },
        });
        var $box = $("<div class='box'>").appendTo($bibletextBox);
        var $bibletextName = $("<span class='name link'>").appendTo($box);
        var $bibletextQuote = $("<span class='quote'>").appendTo($box);
        bt.load(function() {
          $bibletextQuote.text(bt.quote);
        });
        $bibletextName.text(bt.prettyName);
        $bibletextName.click(function() {
          p.navFunc(bt);
        });
      } else {
        // not a bible text
        $bibletextBox.empty();
      }
    } catch (e) { p.errorCallback(e); }
  }

  $textbox.val(text);
  $textbox.on("keyup", onChange);
  $textbox.on("click", onChange);

  $sendEmailButton.click(function() {
    try {
    } catch (e) { p.errorCallback(e); }
  });
  $sendSelfButton.click(function() {
    try {
    } catch (e) { p.errorCallback(e); }
  });
}

/**
 * Save the note content
 */
function noteSave(text) {
  gSettings.notesPage = text;
}
function noteLoad() {
  return gSettings.notesPage || "";
}
