#ifndef ____script_h__
#define ____script_h__

#include "HTTPPage.h"

namespace http {

   class __script : public HTTPPage {

      int page(HTTPParameters &p) override {

         p.data << "function serverSend(url, type, receiver, formData, callback) {"
                   "   var server = new XMLHttpRequest();"
                   "   server.onload = function() {"
                   "      if(server.readyState == 4 && server.status == 200)"
                   "         callback(server.responseText, receiver);"
                   "   };"
                   "   server.open(type, url, true);"
                   "   server.send(formData);"
                   "}"
                   "function getView(url, receiver) {"
                   "   serverSend(url, \"GET\", receiver, null, function(data, receiver) {"
                   "      insertAndExecute(receiver, data);"
                   "   });"
                   "}"
                   "function process(url, formName, receiver) {"
                   "   var formElement = document.querySelector(\"form[name='\" + formName + \"']\");"
                   "   var formData = new FormData(formElement);"
                   "   serverSend(url, \"POST\", receiver, formData, function(data, receiver) {"
                   "      insertAndExecute(receiver, data);"
                   "   });"
                   "}"
                   "function insertAndExecute(id, text) {"
                   "   idresolved = document.getElementById(id);"
                   "   idresolved.innerHTML = text;"
	               "   var scriptarr = idresolved.getElementsByTagName(\"script\");"
	               "   if(scriptarr.length > 0) {"
	               "      var script = document.createElement(\"script\");"
	               "      script.type = \"text/javascript\";"
	               "      script.src = scriptarr[0].src;"
                   "      document.getElementsByTagName(\"head\")[0].appendChild(script);"
	               "   }"
                   "}";

         p.httpRequest.response.addHeader(coreutils::IMFHeader("Content-Type", "text/javascript"));

         return true;
      }
   };
}

#endif
