// Taqua Ajax
(function () {
  epapi = function (conStr) {
    this.ConnectionString = conStr;
    this.Ajax = new Ajax();

    this.RequestDelayMemory = [];
    /* this.ReRequest = function(me){
			if(me.RequestDelayMemory == null){alert("-3=>Request Failed");return}
			me.Request(me.RequestDelayMemory.param,me.RequestDelayMemory.OnComplete,me.RequestDelayMemory.OnProgress,me.RequestDelayMemory.OnError,me.RequestDelayMemory.OnAbort)
		} */

    this.Request = function (param, Handlers) {
      //this.RequestDelayMemory = null;
      //console.log(JSON.stringify(param) + " => "+this.Working);

      if (typeof Handlers.OnComplete == "undefined")
        Handlers.OnComplete = function () {};
      if (typeof Handlers.OnProgress == "undefined")
        Handlers.OnProgress = function () {};
      if (typeof Handlers.OnError == "undefined")
        Handlers.OnError = function () {};
      if (typeof Handlers.OnAbort == "undefined")
        Handlers.OnAbort = function () {};
      if (this.Working == true) {
        //register it in memory
        // this.RequestDelayMemory[this.RequestDelayMemory.length] = { param: param, OnProgress: OnProgress, OnComplete: OnComplete, OnError: OnError, OnAbort: OnAbort }
        this.RequestDelayMemory[this.RequestDelayMemory.length] = {
          param: param,
          OnProgress: Handlers.OnProgress,
          OnComplete: Handlers.OnComplete,
          OnError: Handlers.OnError,
          OnAbort: Handlers.OnAbort,
        };
        //setTimeout(this.ReRequest,200,this);
        return;
      }

      if (typeof this.ConnectionObject == "undefined") {
        console.log("-2=>Api Config File Not Found");
        return;
      }
      param =
        typeof param == "undefined"
          ? {}
          : typeof param == "string"
          ? { RequestID: param }
          : param;
      //eduporta version
      var EpVersion =
        typeof this.ConnectionObject["Version"] == "undefined" ||
        this.ConnectionObject["Version"] == ""
          ? ""
          : this.ConnectionObject["Version"] + "/";
      //api version
      param["Version"] =
        typeof param["Version"] == "undefined" || _Trim(param["Version"]) == ""
          ? "v1"
          : param["Version"];
      if (typeof param["Param"] != "undefined") {
        //if user defined parameters is set
        param["Param"] =
          typeof param["Param"] == "string"
            ? param["Param"]
            : JSON.stringify(param["Param"]);
      }
      //console.log(param['Param']);
      var server =
        typeof this.ConnectionObject["Server"] == "undefined" ||
        this.ConnectionObject["Server"] == ""
          ? "../../"
          : _Trim(this.ConnectionObject["Server"]);
      var lchar = server.substr(server.length - 1, 1);
      server = lchar == "/" ? server : server + "/";

      param["Config"] = JSON.stringify(this.ConnectionObject);

      //exit($this->Server);
      //console.log(server + EpVersion + 'epcore/api/engine/request.php');

      this.Ajax.Post({
        Action: server + EpVersion + "epcore/api/engine/request.php",
        Data: param,
        OnProgress: Handlers.OnProgress,
        OnComplete: Handlers.OnComplete,
        OnError: Handlers.OnError,
        OnAbort: Handlers.OnAbort,
      });
      return this;
    };

    this.Responce = function (reqrst) {
      if (_Trim(reqrst) == "") {
        return { Error: { Code: -2, Message: "Empty Request Responce" } };
      }
      try {
        reqobj = JSON.parse(reqrst);

        return reqobj;
      } catch (e) {
        console.log(e);
        return {
          Error: { Code: -2, Message: "Invalid Request Responce :" + reqrst },
        };
      }
    };

    this.OnErrorRedirect = function (reqobj) {
      var errorurl =
        typeof this.ConnectionObject["ErrorRedirectURL"] != "undefined" &&
        _Trim(this.ConnectionObject["ErrorRedirectURL"]) != ""
          ? this.ConnectionObject["ErrorRedirectURL"]
          : "";

      if (typeof reqobj["Error"] != "undefined") {
        if (errorurl == "") {
          alert(
            "Error_Code=" +
              reqobj["Error"]["Code"] +
              "&Error_Message=" +
              reqobj["Error"]["Message"]
          );
        } else {
          window.location =
            this.ConnectionObject["ErrorRedirectURL"] +
            "?Error_Code=" +
            reqobj["Error"]["Code"] +
            "&Error_Message=" +
            reqobj["Error"]["Message"];
          return;
        }
      }
    };

    this.IsError = function (resobj) {
      return typeof resobj["Error"] != "undefined" ? true : false;
    };

    this.Utility = {
      SetValue: function (DataArray, ids, val) {
        for (var i = 0; i < ids.length; i++) {
          var rid = _Trim(ids[i]);
          if (rid == "") continue;
          if (typeof DataArray[rid] == "undefined") {
            DataArray[rid] = val;
          } else {
            if (
              typeof DataArray[rid] == "string" ||
              typeof DataArray[rid] == "number"
            ) {
              DataArray[rid] = [DataArray[rid], val];
            } else {
              //console.log(rid);
              DataArray[rid].push(val);
            }
          }
          // DataArray[rid] = val;
        }
        return DataArray;
      },
      FormData: (form, DataArray) => {
        //console.log(this);
        //var epapiutil = this.Utility;
        return new Promise((resolve, reject) => {
          //console.log(this);
          if (form == null) return resolve([DataArray, {}]);
          var Files = [];
          var Blobs = [];
          //var Mapping = [];
          //get all input element
          var allinput = form.getElementsByTagName("input");
          DataArray = typeof DataArray == "undefined" ? {} : DataArray;
          //including the epmapping
          DataArray["__EPAPI_MAPPING__"] = [];
          for (var s = 0; s < allinput.length; s++) {
            var element = allinput[s];
            if (_Trim(element.id) == "") {
              let elemdataid = element.Data("id");
              if (elemdataid == null) continue;
              element.id = elemdataid;
            }

            elementids = element.id.split(" ");

            if (element.type == "radio" || element.type == "checkbox") {
              //DataArray[element.id] = element.checked ? 1 : 0;
              var val = element.checked ? 1 : 0;
              if (element.classList.contains("checked-only") && val == 0)
                continue;
              DataArray = this.Utility.SetValue(DataArray, elementids, val);
            } else if (element.type == "file") {
              DataArray = this.Utility.SetValue(DataArray, elementids, "?");
              //DataArray[element.id] = "?";
              for (var fe = 0; fe < elementids.length; fe++) {
                if (_Trim(elementids[fe]) == "") continue;
                Files[Files.length] = elementids[fe];
              }
            } else {
              if (
                typeof element.required != "undefined" &&
                element.required == true &&
                _Trim(element.value) == ""
              ) {
                element.classList.add("errInline");
                //return "";
                //console.log(element);
                return reject(Error(element.title + " (Required Field)"));
              }
              //validation
              //if(element.classList.contains('is-phone')){
              //alert(element.className);
              //check if it is a Camera data (blob)
              if (
                element.classList.contains("cameraPhoto") &&
                element.type.toLowerCase() == "hidden"
              ) {
                DataArray = this.Utility.SetValue(DataArray, elementids, "??"); //cameraPhoto
                for (var fe = 0; fe < elementids.length; fe++) {
                  if (_Trim(elementids[fe]) == "") continue;
                  Blobs[Blobs.length] = elementids[fe];
                }
              } else {
                //normal text box
                if (
                  element.classList.contains("is-phone") &&
                  _Trim(element.value) != "" &&
                  !_ChkPhoneNum(element.value)
                ) {
                  element.classList.add("errInline");
                  //return "Invalid Phone Number Supplied";
                  return reject(Error("Invalid Phone Number Supplied"));
                }
                if (
                  element.classList.contains("is-email") &&
                  _Trim(element.value) != "" &&
                  !_ChkEmail(element.value)
                ) {
                  element.classList.add("errInline");
                  //return "Invalid Email Address Supplied";
                  return reject(Error("Invalid Email Address Supplied"));
                }
                //}
                DataArray = this.Utility.SetValue(
                  DataArray,
                  elementids,
                  element.value
                );
                element.classList.remove("errInline");
              }

              /* if (typeof DataArray[element.id] == "undefined") {
								DataArray[element.id] = element.value;
							} else {
								if (typeof DataArray[element.id] == "string") {
									DataArray[element.id] = [DataArray[element.id], element.value];
								} else {
									DataArray[element.id].push(element.value);
								}
							} */
            }

            //alert(element.type + " ; value="+element.value+ " ; id="+element.id);
          }

          //get textareas
          var allinput = form.getElementsByTagName("textarea");
          for (var s = 0; s < allinput.length; s++) {
            var element = allinput[s];
            if (
              typeof element.required != "undefined" &&
              element.required == true &&
              _Trim(element.value) == ""
            ) {
              element.classList.add("errInline");
              //return "";
              return reject(Error(element.title + " (Required Field)"));
            }
            DataArray[element.id] = element.value;
            element.classList.remove("errInline");
          }

          //get all select element
          var allinput = form.getElementsByTagName("select");
          for (var s = 0; s < allinput.length; s++) {
            //alert(allinput[s].required);
            if (
              Number(allinput[s].options[allinput[s].selectedIndex].value) ==
                0 &&
              allinput[s].required
            ) {
              allinput[s].classList.add("errInline");

              //return allinput[s].options[allinput[s].selectedIndex].textContent;
              return reject(
                allinput[s].options[allinput[s].selectedIndex].textContent +
                  " is Required"
              );
            }
            DataArray[allinput[s].id] =
              allinput[s].options[allinput[s].selectedIndex].value;
            allinput[s].classList.remove("errInline");
          }

          //get all spreatsheet
          var allsp = form.getElementsByClassName("bbwa-spreadsheet");
         // console.log(allsp);
          for (var sp = 0; sp < allsp.length; sp++) {
            var spelem = allsp[sp];
            //	console.log(spelem.tagName);
            if (spelem.tagName.toLowerCase() == "table") {
              //if a table

              //get all the rows
              var sprws = spelem.rows;
              var tbdata = [];
              //console.log(spelem.id + " = "+sprws.length);
              for (asa = 0; asa < sprws.length; asa++) {
                var rwdata = {};
                spcells = sprws[asa].cells;
                for (var ce = 0; ce < spcells.length; ce++) {
                  var curcell = spcells[ce];
                  //get the input element data
                  rwdata["col" + (ce + 1)] =
                    curcell.getElementsByTagName("input")[0].value;
                }
                tbdata[tbdata.length] = rwdata;
              }
            } else if (spelem.classList.contains("spreadsheet")) {
              //if new spread sheet
              //get all rows

              const sprws = spelem.getElementsByClassName("spreadsheet_row");
              console.log(sprws);
              var tbdata = [];
              //console.log(spelem.id + " = "+sprws.length);
              for (asa = 0; asa < sprws.length; asa++) {
                var rwdata = {};
                spcells = sprws[asa].getElementsByClassName("bbwa-textbox");
                for (var ce = 0; ce < spcells.length; ce++) {
                  var curcell = spcells[ce];
                  //get the input element data
                  rwdata["col" + (ce + 1)] =
                    curcell.getElementsByTagName("input")[0].value;
                }
                tbdata[tbdata.length] = rwdata;
              }
            }
            DataArray[spelem.id] = tbdata;
          }

          //get all file button to check reqired attr
          var formbtns = form.getElementsByClassName("form-file-btn");
          if (formbtns.length > 0) {
            for (ar = 0; ar < formbtns.length; ar++) {
              var rbtn = formbtns[ar];
              var req = rbtn.Data("required");
              //alert(req);
              if (req != null && req != "") {
                var fileid = rbtn.Data("file-id");
                //check if require exist in DataArray
                if (
                  req == "true" &&
                  fileid != null &&
                  fileid != "" &&
                  typeof DataArray[fileid] == "undefined"
                ) {
                  //return "Upload Required File";
                  return reject(Error("Upload Required File"));
                }
              }
            }
          }

          //get listbox data
          var listboxdata = form.getElementsByClassName("bbwa-listbox");
          if (listboxdata.length > 0) {
            for (lb = 0; lb < listboxdata.length; lb++) {
              var lbx = listboxdata[lb];
              //get the id
              //generate id
              id = _GetId(lbx);
              DataArray[id] = Control.ListBox.Package(id);
              //console.log(DataArray[id]);
            }
          }

          //DataArray[] =
          return resolve([DataArray, Files, Blobs]);
        });
      },
      LoadMarkup: function (elem, RequID, Param, Mk, DMK) {
        DMK = DMK || "";
        Mk = Mk;
        var reqdet = { RequestID: RequID, Param: Param };
        //alert(JSON.stringify(reqdet));
        epapi.Request(reqdet, {
          OnComplete: function (res) {
            //alert(res);
            res = epapi.Responce(res); //proccess and get the responce
            if (epapi.IsError(res)) {
              //check if error
              var logo =
                typeof res["Error"]["Logo"] != "undefined"
                  ? res["Error"]["Logo"]
                  : "exclamation-triangle";
              //Display error message
              MessageBox.Hint(res["Error"]["Message"], logo, "markuploading");
              return;
            }
            var allm = DMK;
            //console.log(res);
            var objkeys = Object.keys(res);
            for (const key of objkeys) {
              //if (res.hasOwnProperty(key)) {
              var keypre = key.substr(0, 2);
              if (keypre == "__") continue;
              //if (key == "__Root__" || key == "__Logo__") continue;
              var nwmk = Mk;
              var element = res[key];
              var objkeys2 = Object.keys(element);
              for (const ikey of objkeys2) {
                //if (element.hasOwnProperty(ikey)) {
                var ielement = element[ikey];
                nwmk = nwmk.replace("{{" + ikey + "}}", ielement);
                //}
              }
              allm += nwmk;
              //	}
            }
            elem.innerHTML = allm;
            ProcessPage(elem.parentElement.parentElement);
            MessageBox.Close("markuploading");
          },
        });
      },
    };
    this.ConnectionObject = configdata;
    this.FilterListBox = (input) => {
      const li = input.parentElement.parentElement;
      const ul = li.parentElement;
      //get the input value
      const val = input.value;
      for (const item of ul.children) {
        if (
          _Trim(val) != "" &&
          item != li &&
          !item.textContent.toLowerCase().includes(val.toLowerCase())
        ) {
          item.style.display = "none";
        } else {
          item.style.display = "block";
        }
      }
      //get all li in the lis
    };
    /* this.Working = true;
		myapi = this;
		//this.OnReady = function(readyscript)
		this.Ajax.Post({
			Action: conStr,
			OnComplete: function (res) {
				myapi.ConnectionObject = JSON.parse(res);
				myapi.Working = false;
				//run all waiting request
				if (myapi.RequestDelayMemory.length > 0) {
					for (var a = 0; a < myapi.RequestDelayMemory.length; a++) {
						var reqdet = myapi.RequestDelayMemory[a];
						
						myapi.Request(reqdet.param, {OnComplete:reqdet.OnComplete, OnProgress:reqdet.OnProgress, OnError:reqdet.OnError, OnAbort:reqdet.OnAbort});
						
					}
				}
				//Request the Printer markup


				//alert(this.ConnectionObject);
			}, OnError: function (res) {
				console.log("-2=>Api Config File Not Found: " + res);
				myapi.Working = false;
			}
		}); */
  };
})();

(function () {
  Cookie = new (function () {
    this.Set = function (name, value, expires) {
      //alert();function adjustDate() {  }
      var currdat = new Date();
      var currGMT = currdat.getTime() - Cookie.AjustmentTime();
      expires = currGMT + expires;
      expires = new Date(expires);
      document.cookie =
        name +
        "=" +
        escape(value) +
        (expires ? "; expires=" + expires.toGMTString() : "");
      //alert(expires.toGMTString());
    };

    this.AjustmentTime = function () {
      var base = new Date();
      var testDate = base;
      testDate = testDate.toLocaleString();
      testDate = new Date(testDate);
      return testDate.getTime() - base.getTime();
    };

    this.Get = function (labelName) {
      labelName = labelName + "=";
      var labelLen = labelName.length; // read cookie property only once for speed
      var cookieData = document.cookie;
      var cLen = cookieData.length;
      var i = 0;
      var cEnd;
      while (i < cLen) {
        var j = i + labelLen;
        if (cookieData.substring(i, j) == labelName) {
          cEnd = cookieData.indexOf(";", j);
          if (cEnd == -1) {
            cEnd = cookieData.length;
          }
          return unescape(cookieData.substring(j, cEnd));
        }
        i++;
      }
      return "";
    };
  })();
  //Create and add a stylesheet to the document loading aim

  AddCssRule = function (sheet, selector, rules, index) {
    if ("insertRule" in sheet) {
      index = typeof index == _.UND ? sheet.cssRules.length : index;
      return sheet.insertRule(selector + "{" + rules + "}", index);
    } else if ("addRule" in sheet) {
      return sheet.addRule(selector, rules, index);
    }
  };
})();

var epapi = new epapi("epapi/config.json");

document.addEventListener(
  "DOMContentLoaded",
  function () {
    StyleSheet = (function () {
      // Create the <style> tag
      var style = document.createElement("style");
      // WebKit hack :(
      //style.appendChild(document.createTextNode(""));
      // Add the <style> element to the page
      document.head.appendChild(style);
      //style.sheet.insertRule("body::before{content:'Loading...';position:absolute;width:100%;height:100%;z-index:10000;background-color:#EEE;font-size:1.3em;left: 0px; top: 0px; display: block}");
      return style.sheet;
    })();

    var LoadPrinterAjax = new Ajax();
    var configstr = JSON.stringify(configdata);
    LoadPrinterAjax.Post({
      Action: configdata["Core"] + "epapi/api.php",
      Data: { PDFMarkup: "true", Config: encodeURIComponent(configstr) },
      OnComplete: function (res) {
        //alert(res);
        document.body.insertAdjacentHTML("afterbegin", res);
        AddCssRule(
          StyleSheet,
          "#aim-printpdf-margin-box div strong::after",
          "content: 'mm';color: rgb(141, 137, 137);padding-left:3px;font-size:0.7em"
        );
        AddCssRule(
          StyleSheet,
          "#aim-printpdf-fontsize::after",
          "content: 'pt';color: rgb(141, 137, 137)"
        );
        _Printer.Init();
      },
      OnError: function (res) {
        alert("Error Loading PDF Printer");
      },
    });
  },
  false
);

//New Ajax Structure
/*
		 Ajax.Post({
				Action:"",
				PostData:"",
				OnProgress:function(delta){
				   delta = Math.floor(delta*100);
					if(delta < 100){
						MessageBox.Progress.HintTo(delta,null,"Loading",'Ajax.abort()');
					}else{
						MessageBox.Progress.HintTo(-1,"Loading ...","Loading",'Ajax.abort()');
					}
				},
				OnComplete:function(res,url,param){
				  MessageBox.CloseHint();

				},
				OnAbort:function(){

				},
				OnError:function(res){
				  MessageBox.CloseHint();

				}
			});
*/
