var resourceLoader;
// Entry point for JavaScript code
App.onLaunch = function(options) {
  var javascriptFiles = [
    `${options.BASEURL}js/presenter.js`,
    `${options.BASEURL}js/ResourceLoader.js`
  ];

  // Evaluate the scripts using evaluateScripts() – takes two arguments: An array of script URLs to evaluate
  // and a callback function (called only when ALL scripts are evaluated successfully)
  evaluateScripts(javascriptFiles, function(success) {
    if (success) {
      // Use ResourceLoader to load TVML templates
      resourceLoader = new ResourceLoader(options.BASEURL);
      resourceLoader.loadResource(`${options.BASEURL}templates/catalogTemplate.xml.js`,
        function(resource) {
          var doc = Presenter.getDocument(resource);

          // Attach an event listener for selection event
          doc.addEventListener("select", Presenter.loadVideo.bind(Presenter));

          // Push the document onto the view stack
          Presenter.pushDocument(doc);
        });
    } else {
      var errorDocument = createAlertDocument("Loading scripts failed!");
      Presenter.presentDocument(errorDocument);
    }
  });
}

var createAlertDocument = function(title) {
  // Create a template literal (ES6 specification) for an alertTemplate
  var alertXMLString = `<?xml version="1.0" encoding="UTF-8"?>
    <document>
      <alertTemplate>
        <title>${title}</title>
        <description></description>
        <button>
          <text>OK</text>
        </button>
      </alertTemplate>
    </document>`

  // Get the document
  return Presenter.getDocument(alertXMLString);
}
