//General function for retrieving verses
function verseQuery ( pblock, apiParams, callback) {
    var apiUrl = "http://www.esvapi.org/v2/rest/passageQuery?";
    var ajaxOptions = {
      type: "GET",
      url: apiUrl,
      dataType: "html",
      data: apiParams,
      error: function() {
        callback ( "Error searching the ESV Bible." );
      },
      success: function(responseData) {
        callback ( responseData );
      }
    }
    
    if (null === pblock) {
      jQuery.ajax(ajaxOptions);
    } else {
      CmdUtils.previewAjax(pblock, ajaxOptions);
    }
}

//General function for previewing verses
function versePreview (previewBlock, args, myVerseQuery, myNoInputMessage) {
  if (args.object.text.length < 1) {
    previewBlock.innerHTML = myNoInputMessage;
    return;
  }
  previewBlock.innerHTML = "Searching for ESV Bible passages matching " + args.object.summary + "...";
  
  myVerseQuery( previewBlock, args, function( verse ) {
      previewBlock.innerHTML = verse;
  }); 
}

//Main function for inserting ESV text
CmdUtils.CreateCommand({
  names: ["insert from ESV", "insert ESV"],
  homepage: "http://www.duncanandmeg.org/projects/ubiquity-esv-insert.php",
  author: { name: "Duncan Johnson", email: "duncan@duncanandmeg.org" },
  license: "GPL",
  arguments: [{role: "object", nountype: noun_arb_text, label: "verse reference"},
                   {role: "format", nountype: noun_arb_text, label: "plain text (optional)"}],
  icon: "http://www.esv.org/favicon.ico",
  description: "Inserts a passage from the ESV Bible in rich text format. If you need plain text, simply specify that you are inserting \"in plain text\".",
  help: "Try selecting a Bible reference and then issuing \"insert this\". You can also insert a verse by issuing \"insert\" and then typing your reference into the command window.  ESV footnotes and section headings \<b\>are\</b\> inserted. \<h3\>Sample output:\</h3\>\<div class=\"esv\"\>\<h2\>Mark 1:1\</h2\>\<div class=\"esv-text\"\>\<h3 id=\"p41001001.01-1\"\>John the Baptist Prepares the Way\</h3\>\<p class=\"chapter-first\" id=\"p41001001.07-1\"\>\<span class=\"chapter-num\" id=\"v41001001-1\"\>1:1&#160;\</span\>The beginning of the gospel of Jesus Christ, the Son of God.\<span class=\"footnote\"\>&#160;\<a href=\"#f1\" id=\"b1\" title=\"Some manuscripts omit 'the Son of God'\"\>[1]\</a\>\</span\>  (\<a href=\"http://www.esv.org/\" class=\"copyright\"\>ESV\</a\>)\</p\>\</div\>\<div class=\"footnotes\"\>\<h3\>Footnotes\</h3\>\<p\>\<span class=\"footnote\"\>\<a href=\"#b1\" id=\"f1\"\>[1]\</a\>\</span\> \<span class=\"footnote-ref\"\>1:1\</span\> Some manuscripts omit \<i\>the Son of God\</i\>\</p\>\</div\>\</div\>",

  _getVerse: function (previewBlock, args, callback ) {
    var apiParams;
    
    if (typeof args === "function") {
      callback = args;
      args = previewBlock;
      previewBlock = null;
    }
    
    if (args.format.text == "plain text") {
      apiParams = {
      key: "IP",
      "output-format": "plain-text",
      "include-passage-horizontal-lines": "false",
      "include-heading-horizontal-lines": "false",
      "include-headings": "false",
      "include-subheadings": "false",
      "include-footnotes": "false",
      "include-first-verse-numbers": "false",
      "passage": args.object.text
      };
    } else {
      apiParams = {
        key: "IP",
        "link-url": "http://www.gnpcb.org/esv/search/",
        "include-audio-link": "false",
        "passage": args.object.text
      };
    }
    
    verseQuery(previewBlock, apiParams, callback);
  },

  preview: function(previewBlock, args) {
    versePreview(previewBlock, args, this._getVerse, this.description);
  },

  execute: function(args) {
    if (args.object.text.length < 1) {
      displayMessage({icon: this.icon, title: "Error", text: "Please enter a verse reference."});
      return;  
    }
    this._getVerse( args, function( verse ) {
        CmdUtils.setSelection( verse, "text" );
    });
  }
});

//Main function for searching the ESV
CmdUtils.makeSearchCommand({
  names: ["search with ESV", "search ESV"],
  url: "http://www.gnpcb.org/esv/search/?q={QUERY}",
  homepage: "http://www.duncanandmeg.org/projects/ubiquity-esv-insert.php",
  author: { name: "Duncan Johnson", email: "duncan@duncanandmeg.org" },
  license: "GPL",
  icon: "http://www.esv.org/favicon.ico",
  description: "Searches the ESV Bible by verse reference or keyword.",
  help: "Try selecting a Bible reference or phrase and then issuing \"ESV this\". You can also search by issuing \"ESV\" and then typing your reference or phrase into the command window. Press ENTER to open the ESV search results in your browser window.",
  
  _getVerse: function ( previewBlock, args, callback ) {  
    var apiParams = {
      key: "IP",
      "link-url": "http://www.gnpcb.org/esv/search/",
      "include-audio-link": "false",
      q: args.object.text
    };
    
    verseQuery(previewBlock, apiParams, callback);
  },

  preview: function(previewBlock, args) {
    versePreview(previewBlock, args, this._getVerse, this.description);
  }
});

CmdUtils.CreateCommand({
  names: ["link to ESV", "link ESV"],
  homepage: "http://www.duncanandmeg.org/projects/ubiquity-esv-insert.php",
  author: { name: "Duncan Johnson", email: "duncan@duncanandmeg.org" },
  license: "GPL",
  arguments: [{role: "object", nountype: noun_arb_text, label: "verse reference"},
                   {role: "format", nountype: noun_arb_text, label: "plain text (optional)"}],
  icon: "http://www.esv.org/favicon.ico",
  description: "Inserts a link to the ESV Bible by verse reference or keyword.",
  help: "Try selecting a Bible reference or phrase and then issuing \"link this\". You can also search by issuing \"link\" and then typing your reference or phrase into the command window. Press ENTER to insert the ESV link into your current selection (and copy it to the clipboard).",
  
  _getVerse: function ( previewBlock, args, callback ) {
    var apiParams = {
      key: "IP",
      "link-url": "http://www.gnpcb.org/esv/search/",
      "include-audio-link": "false",
      q: args.object.text
    };
    
    verseQuery(previewBlock, apiParams, callback);
  },

  preview: function(previewBlock, args) {
    versePreview(previewBlock, args, this._getVerse, this.description);
  },

  execute: function(args) {
    var url = "http://www.gnpcb.org/esv/search/?q=" + encodeURIComponent(args.object.text);
    var link = '<a href="' + url + '">' + args.object.text + '</a>';

    if (args.format.text == "plain text") {
      CmdUtils.setSelection(url);
    } else {
      CmdUtils.setSelection(link);
    }
    CmdUtils.copyToClipboard(url);
    displayMessage({icon: this.icon, title: "Copied", text: url});
  }
});
