(function () {
  _ArrayToString2 = function (cssarr) {
    var cssStr = "";
    if (typeof cssarr != "object") return "";
    // alert(cssarr);
    var trigkeys = Object.keys(cssarr);
    for (const key of trigkeys) {
      //	if (cssarr.hasOwnProperty(key)) {
      //var element = cssarr[key];
      if (typeof cssarr[key] == "object")
        cssarr[key] = JSON.stringify(cssarr[key]);
      cssStr += key + "=" + encodeURIComponent(cssarr[key]) + "&";
      //}
    }
    return cssStr;
  };

  allbbwa = {};
  //Manage slide animation
  bbwa = function (id) {
    var me = this;
    allbbwa[id] = this;
    // this.duration = param.Duration || 4; // in sec
    //get main banner
    this.Banner = document.getElementById(id);
    //get all bgs
    this.Bgs = this.Banner.getElementsByClassName("bbwa-banner");
    //get all bgs
    this.conts = this.Banner.getElementsByClassName("bbwa-indcont");
    //get all slant boxes
    this.rightdiv = this.Banner.getElementsByClassName("right-side")[0];
    console.log(this.rightdiv);

    this.maxlen =
      this.Bgs.length > this.conts.length ? this.Bgs.length : this.conts.length;
    this.current = this.maxlen;
    //controls

    //form all the ind
    this.Inds = this.Banner.getElementsByClassName("bbwa-anim-inds")[0];
    this.Inds.innerHTML = "";
    //alert(this.maxlen);
    if (this.maxlen > 0) {
      //add the prev btn
      this.Inds.insertAdjacentHTML(
        "beforeend",
        '<a href="#" class="bbwa-arrow-left w3-hide"><i class="fas fa-chevron-left"></i></a>'
      );

      for (var a = 0, lena = this.maxlen; a < lena; a++) {
        //document.getElementById().insertAdjacentElement
        var newind = document.createElement("div");
        newind.className = "bbwa-anim-ind card-1";
        let newindid = "bbwa-anim-ind" + a;
        newind.id = newindid;
        if (a == 0) newind.className += " active";
        newind.setAttribute("data-position", a);
        newind.setAttribute("data-owner", id);

        //newind.onclick = ;

        //  this.Inds.insertAdjacentHTML('beforeend','<div class="bbwa-anim-ind">&nbsp;</div>');
        // alert(this.Inds);
        if (document.insertAdjacentElement) {
          this.Inds.insertAdjacentElement("beforeend", newind);
        } else {
          var othtml = newind.outerHTML;
          this.Inds.insertAdjacentHTML("beforeend", othtml);
        }
        document.getElementById(newindid).addEventListener("click", () => {
          this.Start(
            document.getElementById(newindid).getAttribute("data-position")
          );
        });
      }
      this.Inds.insertAdjacentHTML(
        "beforeend",
        '<a href="#" class="bbwa-arrow-right w3-hide"><i class="fas fa-chevron-right"></i></a>'
      );
    }
    //alert(this.Banner.getElementsByClassName('bbwa-arrow-left').length)
    this.ctrLeft = this.Banner.getElementsByClassName("bbwa-arrow-left")[0];
    this.ctrRight = this.Banner.getElementsByClassName("bbwa-arrow-right")[0];
    this.ctrLeft.setAttribute("data-owner", id);
    this.ctrLeft.onclick = function () {
      allbbwa[this.getAttribute("data-owner")].Prev();
    };
    this.ctrRight.setAttribute("data-owner", id);
    this.ctrRight.onclick = function () {
      allbbwa[this.getAttribute("data-owner")].Start();
    };

    //overwrite Inds to just added indicators
    this.Inds = this.Banner.getElementsByClassName("bbwa-anim-ind");

    this.Prev = function () {
      //alert(me.current - 1);
      me.Start(me.current - 1);
    };

    this.Start = function (ind) {
      //alert(me.current);
      //clear the timmer
      clearTimeout(me.Timmer);
      var prev = me.current;
      //console.log("prev:"+me.current);
      me.current = typeof ind != "undefined" ? Number(ind) : me.current + 1;
      if (me.current >= me.maxlen) {
        me.current = 0;
      } else if (me.current < 0) {
        me.current = me.maxlen - 1;
      }

      //me.current = me.current >= me.maxlen?0:(me.current++);
      //console.log("cur:"+me.current);
      //console.log("----------------------");
      //bgs
      if (
        typeof me.Bgs[prev] != "undefined" &&
        typeof me.Bgs[me.current] != "undefined"
      ) {
        me.Bgs[prev].classList.remove("scalebannerup");
        me.Bgs[prev].classList.add("mfadeOut");
        //  me.Bgs[prev].classList.remove('fadeIn');
        me.Bgs[me.current].classList.remove("mfadeOut");
        // me.Bgs[me.current].classList.add('fadeIn');
        me.Bgs[me.current].classList.add("scalebannerup");
      } else {
        me.Bgs[me.current].classList.remove("mfadeOut");
        // me.Bgs[me.current].classList.add('fadeIn');
        me.Bgs[me.current].classList.add("scalebannerup");
      }
      //

      //contents
      if (
        typeof me.conts[prev] != "undefined" &&
        typeof me.conts[me.current] != "undefined"
      ) {
        me.conts[prev].classList.remove("shownow");
        me.conts[prev].classList.add("hidenow");
        setTimeout(() => {
          me.conts[prev].classList.add("w3-hide");
          //show the current
          me.conts[me.current].classList.remove("hidenow");
          me.conts[me.current].classList.add("shownow");
          me.conts[me.current].classList.remove("w3-hide");
        }, 1000);
      } else {
        me.conts[me.current].classList.remove("hidenow");
        me.conts[me.current].classList.add("shownow");
        me.conts[me.current].classList.remove("w3-hide");
      }

      //ind
      if (
        typeof me.Inds[prev] != "undefined" &&
        typeof me.Inds[me.current] != "undefined"
      ) {
        me.Inds[prev].classList.remove("active");
        me.Inds[me.current].classList.add("active");
      } else {
        me.Inds[me.current].classList.add("active");
      }

      //slant boxes animation
      me.rightdiv.classList.replace("shownew", "hidemenu");
      setTimeout(() => {
        me.rightdiv.classList.replace("hidemenu", "shownew");
      }, 800);

      //check if global interval is set

      //display next slide
      me.Timmer = setTimeout(
        me.Start,
        typeof transInterval != "undefined" ? transInterval * 1000 : 5000
      );
    };
  };
  MessageBox = {
    PopupTemp: `<div style="" class="w3-hide bbwa-popup fadeIn animated faster"  id="eppopup">
    <div class="w3-card w3-round zoomInShort2 faster animated bbwa-popupinner" style="" ></div></div>`,
    Popup: function (markup, icon, flat) {
      flat = flat || false;
      icon = icon || "fas fa-exclamation";
      var poppage = _("eppopup");

      if (poppage == null) {
        document.body.insertAdjacentHTML("afterbegin", MessageBox.PopupTemp);
        //alert(MessageBox.PopupTemp);
        poppage = _("eppopup");
        poppage.addEventListener("click", (t) => {
          if (t.target == poppage) {
            MessageBox.ClosePopup();
          }
        });
      }
      var popupcont = poppage.firstElementChild;

      if (!flat) {
        popupcont.classList.add("w3-padding-large");
        poppage.classList.remove("flatpop");
      } else {
        poppage.classList.add("flatpop");
      }

      popupcont.innerHTML = ` <div class="bbwa-popup-logo zoomInShort animated fast delay-0-2s card-2 appbgcolor"><i class=" ${icon} w3-xlarge zoomInShort2 animated fast delay-0-5s"></i></div>
      <button class="popclose-btn-small" onclick="MessageBox.ClosePopup()"><i class="fas fa-chevron-left"></i></button>
      <button class="popclose-btn" onclick="MessageBox.ClosePopup()"><i class="fas fa-times"></i></button>`;
      if (typeof markup == "string") {
        popupcont.innerHTML += markup;
      } else {
        //alert(markup);
        popupcont.appendChild(markup);
      }
      poppage.classList.remove("w3-hide");
    },
    ClosePopup: function () {
      var poppage = _("eppopup");

      if (poppage == null) return;
      poppage.classList.add("fadeOut");
      poppage.classList.remove("fadeIn");
      poppage.firstElementChild.classList.add("zoomOutShort2");
      poppage.firstElementChild.classList.remove("zoomInShort2");
      setTimeout(function () {
        poppage.classList.add("w3-hide");
        poppage.classList.add("fadeIn");
        poppage.classList.remove("fadeOut");
        poppage.firstElementChild.classList.add("zoomInShort2");
        poppage.firstElementChild.classList.remove("zoomOutShort2");
      }, 500);
    },
    CloseFuncs: {},
    HintTimmer: {},
    Show: function (text, logo, id, closefunc, hint) {
      if (typeof text == "undefined" || _Trim(text) == "") return;
      if (typeof closefunc == "undefined") closefunc = function () {};

      if (typeof id == "undefined" || _Trim(id) == "") {
        var dt = new Date();
        id = "alert" + dt.getTime() + "_" + Math.random() * 300000;
      }
      MessageBox.CloseFuncs[id] = closefunc;
      //check if message already displayed
      var obj = _(id);
      if (obj != null) {
        //if exist
        //clear timmer if it exist
        MessageBox.Close(obj);
      }
      var logomk = "";
      if (typeof logo != "undefined" && _Trim(logo) != "")
        logomk = '<i class="fas fa-' + logo + ' appcolor alert-logo"></i>';
      var msgdet =
        '<div id="' +
        id +
        '" class="ordersys-alert w3-card bounceInUp animate-normal"><div id="alertcont" class="alert-cont">' +
        logomk +
        '<span class="alert-txt">' +
        text +
        '<span></div><button onclick="MessageBox.Close(this.parentElement)" class="bbwa-btn smaller gen-text-shadow bbwa-icon-only w3-right" style="margin-top:0px"><i class="mbri-close fa-fw"></i></button> <div style="clear:both"></div> </div>';
      //display message
      _("alert-cover").insertAdjacentHTML("afterbegin", msgdet);
      if (typeof hint != "undefined" && hint == true) {
        MessageBox.HintTimmer[id] = setTimeout(
          'MessageBox.Close(_("' + id + '"))',
          6000
        );
      }
    },
    Hint: function (text, logo, id, cfunc) {
      if (typeof text == "undefined" || _Trim(text) == "") return;
      if (typeof id == "undefined" || _Trim(id) == "") {
        var dt = new Date();
        id = "alert" + dt.getTime + "_" + Math.random() * 300000;
      }
      MessageBox.Show(text, logo, id, cfunc, true);
    },
    Close: function (msgbx, dorun) {
      dorun = typeof dorun == _UND ? false : dorun;
      msgbx = typeof msgbx == "string" ? _(msgbx) : msgbx;
      if (msgbx == null) return;
      id = msgbx.id;
      if (!dorun) MessageBox.CloseFuncs[id]();
      //alert(MessageBox.CloseFuncs[id])
      if (msgbx.parentElement == null) return;
      msgbx.parentElement.removeChild(msgbx);
      if (typeof MessageBox.HintTimmer[id] != "undefined") {
        clearInterval(MessageBox.HintTimmer[id]);
        delete MessageBox.HintTimmer[id];
        //close it before adding a new one
      }
    },
    CheckNotifyAllowed: async () => {
      let granted = false;

      if (Notification.permission === "granted") {
        granted = true;
      } else if (Notification.permission !== "denied") {
        let permission = await Notification.requestPermission();
        granted = permission === "granted" ? true : false;
      }
      //console.log(granted);
      return granted;
    },
    Notify: async (msg, title, icon, delay) => {
      if (typeof msg == "undefined" || msg.trim() == "") return;
      title = title || "Message";
      icon = "./Files/UserImages/School/logo.png";
      delay = delay || 10000;
      if (MessageBox.CheckNotifyAllowed()) {
        // const notification = new Notification(msg);

        const notification = new Notification(title, {
          body: msg,
          icon: icon,
        });

        // close the notification after 10 seconds
        setTimeout(() => {
          notification.close();
        }, delay);

        // navigate to a URL when clicked
        notification.addEventListener("click", () => {
          //window.open('https://www.javascripttutorial.net/web-apis/javascript-notification/', '_blank');
        });
      } else {
        MessageBox.Show(msg);
      }
    },
  };

  //function to return the actual type of supplied object
  //----------------------------------------
  //main advantage is, it checks array and return as array type not conventional javascript object type

  //get the data attrribute of an object
  function GetDataAttr(obj, atr, value) {
    if (_IsArray(obj)) {
      var rstarr = new Array();
      for (var s = 0, lens = obj.length; s < lens; s++) {
        var objn = obj[s];
        //alert(obj.length);
        rstarr.push(GetDataAttr(objn, atr, value));
      }
      return rstarr;
    } else {
      if (typeof value == _UND) {
        var val = obj.getAttribute("data-" + atr);
        return val;
      } else {
        obj.setAttribute("data-" + atr, value);
        return value;
      }
    }
  }
  Object.prototype.Data = function (atr, val) {
    return GetDataAttr(this, atr, val);
  };
  Array.prototype.Data = function (atr, val) {
    return GetDataAttr(this, atr, val);
  };

  document.addEventListener("click", function (ev) {
    if (!ev.target.classList.contains("popup-menu-display-btn")) {
      document.body.classList.remove("menu-popup-drop");
      //handles calendar display in groupnox
      if (ev.target.classList.contains("Calendar")) {
        //get the parent group box
        //get the input group box
        var inputgrpbxid = ev.target.Data("GroupID");
        if (inputgrpbxid != null) {
          var grpb = _(inputgrpbxid);
          if (grpb != null && grpb.classList.contains("bbwa-groupbox")) {
            //get all group box
            var allgrpbx = document.getElementsByClassName("bbwa-groupbox");
            for (var gr = 0, lengr = allgrpbx.length; gr < lengr; gr++) {
              if (allgrpbx[gr] != grpb) {
                allgrpbx[gr].style.zIndex = "1";
              } else {
                allgrpbx[gr].style.zIndex = "2";
              }
            }
          }
        }

        //if in
        console.log(ev.target.parentElement.parentElement);
        if (
          ev.target.parentElement.parentElement.classList.contains(
            "spreadsheet_row"
          )
        ) {
          const spreadsheet =
            ev.target.parentElement.parentElement.parentElement;
          const alltb = spreadsheet.getElementsByClassName("bbwa-textbox");
          for (var gra = 0, lengra = alltb.length; gra < lengra; gra++) {
            if (alltb[gra] != ev.target.parentElement) {
              alltb[gra].style.zIndex = "1";
            } else {
              alltb[gra].style.zIndex = "2";
            }
          }
        }
      }
    }

    //mobile moreoption popup
    if (ev.target.classList.contains("Moreoptionclick")) {
    } else {
      //hide all moreoptions
      var allmorbx = document.getElementsByClassName("moreoptions");
      for (var gmr = 0, lengr = allmorbx.length; gmr < lengr; gmr++) {
        allmorbx[gmr].style.display = "none";
      }
    }
    /* if(ev.target.classList.contains("DatePicker")){
       //alert('aaa');
       return showDatePicker(ev.target.Data('input'),ev.target);
     }else{
      if(!ev.target.classList.contains("cntr")){
        removeCalender();        
      }
     } */
    //alert(ev.target.className);
  });

  /* document.addEventListener("load",function(){
    alert('loaded');
    
  }); */

  document.addEventListener(
    "DOMContentLoaded",
    function () {
      //Login.AutoOpenApply();
      /* var seslog = _('logSes');
    if(seslog != null && _Trim(seslog.value) != ""){
      //alert(seslog.value);
      Login.LoadMain();
    } */
      Login.LoadMain();

      //remove the reload marker for page waiting for reload
      localStorage.removeItem("Reload");

      // alert(_('menu_popup'));
      //Application.Activate(_('menu-popup'));

      //get all textbox
      //alert(encodeURIComponent('='))
    },
    false
  );

  window.onstorage = () => {
    //console.log('Changed');
    //get the change operation
    var operd = localStorage.getItem("PayFinish");
    if (operd != null && operd != "") {
      if (operd == "TRUE") {
        var paidcheck = _("paid_option");
        if (paidcheck != null) {
          paidcheck.click();
        }
        var paidcheck2 = _("paid_option_go");
        if (paidcheck2 != null) {
          paidcheck2.click();
        }

        var paidcheck3 = _("paid_option_go2");
        if (paidcheck3 != null) {
          paidcheck3.click();
        }
        localStorage.removeItem("Reload");
      }
    }
    var oper = localStorage.getItem("Reload");
    if (oper != null && oper != "") {
      //if(oper == "ReloadOnPaid"){
      //get all Page to be reloaded when paiment complete
      var payreloadpage = document.getElementsByClassName(oper);
      var PageDataArr = [];
      if (payreloadpage.length > 0) {
        //console.log(payreloadpage.length);
        for (var rl = 0, lenrl = payreloadpage.length; rl < lenrl; rl++) {
          //console.log(rl);
          //get the element
          reloadelem = payreloadpage[rl];
          //check if page form - submit the form
          if (reloadelem.tagName.toLowerCase() == "form") {
            reloadelem.submit();
            continue;
          }

          if (
            reloadelem.parentElement !=
            reloadelem.parentElement.parentElement.firstElementChild
          ) {
            continue;
          }
          //console.log(reloadelem.className);
          if (reloadelem.firstElementChild.classList.contains("PageData")) {
            pagedata = JSON.parse(reloadelem.firstElementChild.textContent);
            //console.log(pagedata.ApplyID+" , "+pagedata.ApplyGroupID);
            if (payreloadpage.length == 1) {
              Application.LoadPage(
                null,
                pagedata.ApplyID,
                pagedata.ApplyGroupID
              );
            } else {
              PageDataArr.push(pagedata);
            }
          }
        }
        if (PageDataArr.length > 0) {
          for (var rls = 0, lenrls = PageDataArr.length; rls < lenrls; rls++) {
            Application.LoadPage(
              null,
              PageDataArr[rls].ApplyID,
              PageDataArr[rls].ApplyGroupID
            );
          }
        }
      }
      //}
      localStorage.removeItem("Reload");
    }

    var pinfield = _("VerCode");

    if (pinfield != null) {
      var vercode = localStorage.getItem("VerCode");
      //alert(vercode);
      if (vercode != null) {
        pinfield.value = vercode;
      }
    }
  };
  //Popup -
  Popup = {};
  errorpw = function (param) {
    MessageBox.Hint(param.Error, "exclamation-triangle", "perr");
  };

  //Use to laod window content
  Application = {
    //switch dark/light mode
    SwitchMode: (inp) => {
      if (inp) {
        Application.SetMode(inp.checked);
      }
    },
    SetMode: (dark = true) => {
      if (!dark) {
        document.body.classList.add("light");
        localStorage.setItem("darkMode", "false");
      } else {
        document.body.classList.remove("light");
        localStorage.setItem("darkMode", "true");
       
      }
    },
    OpenExternalScript: (url) => {
      if (typeof url == _UND || _Trim(url) == "") return;
      //check if data available
      urlsplit = url.split("?");
      if (urlsplit.length > 0) {
        url += "&SubDir=" + encodeURIComponent(configdata["SubDir"]);
      } else {
        url += "?SubDir=" + encodeURIComponent(configdata["SubDir"]);
      }
      window.open(
        url,
        "newwin",
        "width=600,menubar=no,status=no,scrollbars=yes,location=no"
      );
    },
    CurrentActive: null,
    ResetDemension: function (epwin) {
      var popup = _GetDimension(epwin);
      epwin.style.transform = "none";
      epwin.style.width = popup.width + "px";
      epwin.style.height = popup.height + "px";
      epwin.style.top = popup.top + "px";
      epwin.style.left = popup.left + "px";
      epwin.style.position = "fixed";
    },
    HighestActive: 100,
    MakeActive: function (wind, from) {
      //if(wind.classList.contains('menu-popup-cont-active'))return;
      if (wind.style.zIndex == Application.HighestActive + "") return;
      //get all active window
      /* var allactive = document.getElementsByClassName('menu-popup-cont-active');
      if(allactive != null && allactive.length > 0){
        for(indwind of allactive){
          indwind.classList.remove('menu-popup-cont-active')
        }
      }
      wind.classList.add('menu-popup-cont-active'); */
      Application.HighestActive++;
      wind.style.zIndex = Application.HighestActive;
      Application.CurrentActive = wind;
      var wintn = _(wind.id + "_tn");
      //console.log(wintn.id);
      if (wintn != null) Application.MakeThumbNailActive(wintn);
      // alert(Application.CurentActive);
    },
    LoadByGroupID: function (GRPID) {},

    UnSetThumbNails: function () {
      var openpgs = _("openpgs");
      if (openpgs != null) {
        var alltn = openpgs.getElementsByClassName("appbordercolor");
        if (alltn != null && alltn.length > 0) {
          for (tn of alltn) {
            tn.classList.remove("appbordercolor");
          }
        }
      }
    },

    MakeThumbNailActive: function (thumbnail) {
      if (thumbnail.classList.contains("appbordercolor")) return;
      Application.UnSetThumbNails();
      thumbnail.classList.add("appbordercolor");
      thumbnail.scrollIntoView();
      //document.getElementById().scrollIntoView
    },

    AddThumbNail: function (wind) {
      var tnbx = _("openpgs");
      if (tnbx == null) return;
      var wintnid = wind.id + "_tn";
      var exist = _(wintnid);
      var logo = wind.Data("logo");

      if (exist == null) {
        Application.UnSetThumbNails();
        //add to tumbnail
        tnbx.insertAdjacentHTML(
          "beforeend",
          '<div id="' +
            wintnid +
            '" class="sideindbx w3-display-container appbordercolor" onclick="Application.Show(_(\'' +
            wind.id +
            '\'))"><i class="' +
            logo +
            ' w3-display-middle"></i></div>'
        );
      } else {
        Application.MakeThumbNailActive(exist);
      }
    },

    RemoveThumbNail: function (wind) {
      var tnbx = _("openpgs");
      if (tnbx == null) return;
      var wintnid = wind.id + "_tn";
      //alert(wintnid);
      var exist = _(wintnid);
      if (exist != null) {
        exist.parentElement.removeChild(exist);
      }
    },
    WindowAjax: {},
    Load: function (Data) {
      var meitem = event.currentTarget;
      var namobj = meitem.getElementsByClassName("maininfo");
      var name = namobj.length > 0 ? namobj[0].textContent : meitem.textContent;
      //var logo = meitem.getElementsByClassName('maininfo')[0].textContent;
      if (typeof Data["ApplyGID"] == _UND) return;
      if(Data["ApplyGID"] == 0){
        // MessageBox.Hint("Your Account is Suspended, Contact the ICT Team", "user-slash", "suspendAcc");
        MessageBox.Popup(`<div style="padding-top:40px;text-align:center">
        <img style="width:150px" src="${configdata["Core"]}images/General/ban.png" />
        <h2>Account Suspended</h2>
        <p>Contact the ICT Team</p>
        </div>`, "fas fa-user-slash");
        return;
      }
      //check if already opened
      var wind = _("menu-popup" + Data["ApplyGID"]);
      if (wind != null) {
        Application.Show(wind);
        return;
      }

      //************************************* */
      //check if Window Ajax not created already
      if (typeof Application.WindowAjax[Data["ApplyGID"]] == _UND)
        Application.WindowAjax[Data["ApplyGID"]] = new Ajax();
      if (typeof Data["OpenFrom"] == _UND) Data["OpenFrom"] = "open-from-home";
      if (typeof Data["Logo"] == _UND) Data["Logo"] = "mbri-browse";
      //get the window markup
      var res = _("ep-window-cont").innerHTML;
      //alert(res);
      //set page id
      res = res.replace(/{{PAGEID}}/g, Data["ApplyGID"]);
      res = res.replace(/{{OpenFrom}}/g, Data["OpenFrom"]);
      res = res.replace(/{{Name}}/g, name);
      res = res.replace(/{{Logo}}/g, Data["Logo"]);

      //autoload
      res = res.replace(
        /{{AutoLoad}}/g,
        typeof Data["AutoLoad"] == _UND || Data["AutoLoad"] != true
          ? "w3-hide"
          : ""
      );
      res = res.replace(
        /{{Home}}/g,
        typeof Data["Home"] == _UND || Data["Home"] != true ? "w3-hide" : ""
      );
      res = res.replace(
        /{{Login}}/g,
        typeof Data["Login"] == _UND || Data["Login"] != true ? "w3-hide" : ""
      );
      res = res.replace(
        /{{Logout}}/g,
        typeof Data["Logout"] == _UND || Data["Logout"] != true ? "w3-hide" : ""
      );
      res = res.replace(
        /{{favourite}}/g,
        typeof Data["Favourite"] == _UND || Data["Favourite"] != true
          ? ""
          : "checked"
      );
      const cmode = localStorage.getItem("darkMode");
      // res = res.replace(/{{darkmode}}/g, (typeof Data['DarkMode'] == _UND || Data['DarkMode'] == true) ? "checked" : "");
      res = res.replace(
        /{{darkmode}}/g,
        cmode && cmode == "true" ? "checked" : ""
      );

      /* Data['AutoLoad'] = (typeof Data['AutoLoad'] == _UND || Data['AutoLoad'] != true)?"w3-hide":"";
      Data['Home'] = (typeof Data['Home'] == _UND || Data['Home'] != true)?"w3-hide":"";
      Data['Login'] = (typeof Data['Login'] == _UND || Data['Login'] != true)?"w3-hide":"";
      Data['Logout'] = (typeof Data['Logout'] == _UND || Data['Logout'] != true)?"w3-hide":""; */

      //create the page
      var nwtop = -1;
      // var nwleft = -1;
      if (Application.CurrentActive != null) {
        nwdim = _GetDimension(Application.CurrentActive);
        nwtop = nwdim.top + 10;
        //nwleft = nwdim.left + 10;
      }
      //alert(res);
      window.setTimeout(() => {
        document.body.insertAdjacentHTML("afterbegin", res);
        var newwind = document.body.firstElementChild;
        if (nwtop > 0) {
          newwind.style.top = nwtop + "px";
          //document.body.firstElementChild.style.left = nwleft + "px";
        }
        Application.AddThumbNail(newwind);
        Application.MakeActive(newwind);
      }, 1);

      //ep-window-cont-{{PAGEID}}
      setTimeout(
        "Application.Activate(_('menu-popup" + Data["ApplyGID"] + "'))",
        1200
      );
      //setTimeout("Application.Activate(document.body.firstElementChild)",1200);
      //************************************* */
      //return;
      // MessageBox.Show("Loading Window ...",'cog fa-spin','load_win');

      Data["SubDir"] = configdata["SubDir"];
      //alert(JSON.stringify(Data));
      //start the laoding operation after 0.5s
      //console.log(wind);
      window.setTimeout(() => {
        _("menu-popup" + Data["ApplyGID"]).classList.remove("ph-pause");
      }, 1000);
      Application.WindowAjax[Data["ApplyGID"]].Post({
        Action: configdata["Core"] + "designs/window.php",
        Data: Data,
        OnComplete: function (res, url, param) {
          var cont = _("win-body-cont" + param["ApplyGID"]);
          //console.log(param);
          try {
            var err = JSON.parse(res);
            cont.innerHTML = err.Message;
            //MessageBox.Hint(err.Message,'exclamation-triangle',"load_win");
          } catch (e) {
            if (cont) cont.innerHTML = res;
            //console.log(JSON.stringify(Application.OpenList));
            //check if operation on queue
            if (typeof Application.OpenList[param["ApplyGID"]] != _UND) {
              var operts = Application.OpenList[param["ApplyGID"]];
              for (var ol = 0, olen = operts.length; ol < olen; ol++) {
                //{Obj:obj,Aid:id,AGid:appgrpid,OLF:onloadfunc,Pid:pageid,Pholder:placholder,AGLogo:appgrplogo}
                Application.LoadPage(
                  null,
                  operts[ol].Aid,
                  operts[ol].AGid,
                  null,
                  operts[ol].AGid,
                  operts[ol].Pholder,
                  operts[ol].AGLogo
                );
                Application.OpenList[param["ApplyGID"]] = [];
              }
            }
            /* var nwtop = -1;
           // var nwleft = -1;
            if(Application.CurrentActive != null){
              nwdim = _GetDimension(Application.CurrentActive);
              nwtop = nwdim.top + 10;
             //nwleft = nwdim.left + 10;
            }
            //alert(res);
            
            document.body.insertAdjacentHTML('afterbegin',res);
            var newwind = document.body.firstElementChild;
            if(nwtop > 0){
              newwind.style.top = nwtop + "px";
              //document.body.firstElementChild.style.left = nwleft + "px";
            }
            Application.AddThumbNail(newwind);
            //make it active
            Application.MakeActive(newwind);
            setTimeout("Application.Activate(document.body.firstElementChild)",1200); */
            // MessageBox.Close('load_win');
          }
        },
        OnError: function (res, url, param) {
          // _('bbwa_Page'+param['ApplyID']).innerHTML = res;
          MessageBox.Hint("Error: " + res, "exclamation-triangle", "hshshs");
        },
        OnAbort: function (res, url, param) {
          // _('bbwa_Page'+param['ApplyID']).innerHTML = res;
          MessageBox.Hint(
            "Loading Page Aborted",
            "exclamation-triangle",
            "sksksks"
          );
        },
      });
    },
    LastDim: null,
    Show: function (wind) {
      var pp = wind;
      //console.log("In .Show => "+wind.id);
      //pp.parentElement.insertBefore(pp, pp.parentElement.firstElementChild);
      pp.className = pp.className.replace(" close-popup", "");
      Application.MakeActive(pp);
    },
    Close: function (obj) {
      // obj.className += ' close-popup2';
      obj.className += " zoomOutShort2 animated faster";
      setTimeout("Application.RemoveWindow(_('" + obj.id + "'))", 600);
      if (Application.CurrentActive != null && Application.CurrentActive == obj)
        Application.CurrentActive = null;
      Application.RemoveThumbNail(obj);
    },
    RemoveWindow: function (nobj) {
      nobj.parentElement.removeChild(nobj);
    },
    Minimize: function (obj) {
      obj.className += " close-popup";
      if (Application.CurrentActive != null && Application.CurrentActive == obj)
        Application.CurrentActive = null;
      Application.UnSetThumbNails();
    },
    Maximize: function (popup) {
      // var popup = _('menu-popup');
      //var popup = _('menu-popup');
      if (
        typeof Application.LastDim != "undefined" &&
        Application.LastDim != null &&
        typeof Application.LastDim[popup.id] != "undefined" &&
        popup.style.width == "100vw" &&
        popup.style.height == "100vh" &&
        popup.style.left == "0px" &&
        popup.style.top == "0px"
      ) {
        popup.style.width = Application.LastDim[popup.id].width + "px";
        //popup.style.maxWidth = '1000px';
        popup.style.height = Application.LastDim[popup.id].height + "px";
        popup.style.top = Application.LastDim[popup.id].top + "px";
        popup.style.left = Application.LastDim[popup.id].left + "px";
        setTimeout(
          '_("' + popup.id + '").style.transition = "none"',
          0.3 * 1000
        );
        popup.classList.remove("maximized");
      } else {
        if (Application.LastDim == null) Application.LastDim = {};
        Application.LastDim[popup.id] = _GetDimension(popup);
        //Application.LastDim = _GetDimension(popup);
        popup.style.transform = "none";
        popup.style.width = "100vw";
        //popup.style.maxWidth = '100vw';
        popup.style.height = "100vh";
        popup.style.top = "0px";
        popup.style.left = "0px";

        popup.style.transition =
          "width 0.3s ease, height 0.3s ease, top 0.3s ease, left 0.3s ease";
        popup.classList.add("maximized");
        //setTimeout('_("'+popup.id+'").style.transform = "none"',0.3*1000);
        //popup.style.transform = "none";
      }
    },
    ActivateGroup: function (obj, bodyid) {
      if (obj.parentElement.firstElementChild != obj) {
        obj.parentElement.insertBefore(
          obj,
          obj.parentElement.firstElementChild
        );
        // var bodyd = _(bodyid);
        var bodyd =
          obj.parentElement.parentElement.parentElement.getElementsByClassName(
            "bdcont" + bodyid
          )[0];
        bodyd.parentElement.insertBefore(
          bodyd,
          bodyd.parentElement.firstElementChild
        );
        document.body.classList.remove("menu-popup-drop");
      }
    },
    CurrentActive: [],
    WorkingPages: {},
    LodingMk: "",
    Placholder: function (type) {
      if (Application.LodingMk == "")
        Application.LodingMk = _("ep-placeholder-cont").innerHTML;
      //console.log(type);
      if (typeof type != _UND && type != "")
        mk = Application.LodingMk.replace("ph-" + type, "");
      return mk;
    },
    RemovePlaceholders: (pagecont) => {
      //Process placeholder (remove place holders)
      var temps = pagecont.getElementsByClassName("ph-template");
      if (temps.length > 0) {
        for (var t = 0, lent = temps.length; t < lent; t++) {
          //if default loader template
          //if(temps[t].parentElement.id == "ep-placeholder-cont")continue;
          temps[t].parentElement.removeChild(temps[t]);
        }
      }
    },
    PageAjax: {},
    OpenList: {},
    BoxButton: `<div id="{{id}}" onclick="{{action}}"
    class="bbwa-textbox {{class}} w3-padding w3-round-small w3-display-container bbwa-boxbtn"
    style="display:inline-block;cursor: pointer;{{style}}" title="{{title}}"><i class="{{logo}} w3-large bxbtn-logo"
        style="vertical-align: middle;display:inline-block;width:20px"></i>&nbsp; <div
        style="vertical-align: middle;display: inline-block;max-width: calc(100% - 30px);">
        <div class="bbwa-boxbtn-title">{{title}}</div>
        <div class="bbwa-boxbtn-data">{{data}}</div>
        <div class="bbwa-checkbox-marker w3-padding-small appbgcolor w3-display-right w3-round w3-example zoomIn"
            id="{{id}}_Marker">{{marker}}</div>
    </div>&nbsp;<i class="mbri-arrow-next w3-display-right bbwa-boxbtn-hasaction appcolor"
        style="vertical-align: middle;right:10px"></i></div>`,
    LoadPagePre: function (
      obj,
      gid,
      appgrpid,
      onloadfunc,
      pageid,
      placholder,
      appgrplogo
    ) {
      placholder = placholder || "textbox";
      appgrplogo = appgrplogo || "mbri-features";
      //oo = oo || false;
      onloadfunc = typeof onloadfunc == "undefined" ? null : onloadfunc;
      pageid = typeof pageid == "undefined" ? "" : pageid;
      //get the subs
      const subsdet = _(gid + "_subs");

      try {
        const dets = JSON.parse(subsdet.textContent);
        if (dets.length == 1) {
          //just load the application
          Application.LoadPage(
            obj,
            dets[0]["ARID"],
            appgrpid,
            onloadfunc,
            pageid,
            placholder,
            appgrplogo
          );
        } else if (dets.length > 1) {
          /* <div class="bbwa-groupbox {{class}}" id="">
        <h1 class="bbwa-groupbox-title">{{title}}</h1>
        <_??_>
    </div> */
          //console.log(obj);
          let mk =
            `<div class="bbwa-groupbox" style="max-height:calc(100% - 20px)" id=""><div class="bbwa-textbox bbwa-listboxcont">
          <ul class="bbwa-listbox" id="${gid}_listsubs">` +
            dets
              .map((inddet) => {
                let nmk = Application.BoxButton;
                //const updatemap = {"id":inddet['ARID']+"_subbtn","action":"","class":"","style":"","title":inddet['AppRName'],"logo":inddet['AppRLogo'],"data":inddet['AppRDescr'],"marker":""};

                nmk = nmk.replace(/{{id}}/g, inddet["ARID"] + "_subbtn");
                nmk = nmk.replace(
                  /{{action}}/g,
                  `Application.LoadPage(_('${obj.id}'),${inddet["ARID"]},${appgrpid},null,${pageid},'${placholder}');MessageBox.ClosePopup();`
                );
                nmk = nmk.replace(/{{class}}/g, "");
                nmk = nmk.replace(/{{style}}/g, "");
                nmk = nmk.replace(/{{title}}/g, inddet["AppRName"]);
                nmk = nmk.replace(/{{logo}}/g, inddet["AppRLogo"]);
                nmk = nmk.replace(/{{data}}/g, inddet["AppRDescr"]);
                nmk = nmk.replace(/{{marker}}/g, "");
                return "<li>" + nmk + "</li>";
              })
              .join("") +
            `</ul></div>
      </div>`;

          //load popup
          MessageBox.Popup(mk, appgrplogo);
        } else {
          MessageBox.Hint(
            "No Application Setup Yet",
            "exclamation-triangle",
            "noappsetup"
          );
        }
      } catch (error) {
        MessageBox.Hint(
          "No Application Setup Yet",
          "exclamation-triangle",
          "noappsetup"
        );
      }
    },
    // PagesContainer:{}, //hold all page containers
    LoadPage: function (
      obj,
      id,
      appgrpid,
      onloadfunc,
      pageid,
      placholder,
      appgrplogo
    ) {
      // alert(pageid);
      placholder = placholder || "textbox";
      appgrplogo = appgrplogo || "mbri-features";
      //oo = oo || false;
      onloadfunc = typeof onloadfunc == "undefined" ? null : onloadfunc;
      pageid = typeof pageid == "undefined" ? "" : pageid;
      if (obj == null) {
        //get the obj
        var objc = _("appmenu" + id);
        //alert(objc);
        if (_IsArray(objc)) {
          obj = objc[0];
        } else {
          obj = objc;
        }
      }
      //obj.parentElement.parentElement.insertBefore(obj.parentElement, obj.parentElement.parentElement.firstElementChild);
      // var cont = _('id'+appgrpid);
      if (obj == null) {
        //if container not yet open
        //add to groupid queue list
        if (typeof Application.OpenList[appgrpid] == _UND)
          Application.OpenList[appgrpid] = [];
        Application.OpenList[appgrpid].push({
          Obj: obj,
          Aid: id,
          AGid: appgrpid,
          OLF: onloadfunc,
          Pid: pageid,
          Pholder: placholder,
          AGLogo: appgrplogo,
        });
        //open the window
        Application.Load({
          ApplyGID: appgrpid,
          AutoLoad: true,
          Home: false,
          Logout: true,
          Login: false,
          OpenFrom: "open-from-menu",
          Logo: appgrplogo,
        });
        return;
      }
      var cont = obj.parentElement.parentElement.parentElement;
      // alert(cont.id)
      //the popup general content div
      //alert(cont.parentElement.parentElement.id);
      var gencontdiv =
        cont.parentElement.parentElement.getElementsByClassName(
          "menu-bx-cont"
        )[0];
      //if()
      //check if Page Container already created
      //get the container

      var pgcont = gencontdiv.getElementsByClassName("bbwa_Page" + id);
      //alert(pgcont);
      if (pgcont == null || pgcont.length < 1) {
        //if not created
        var newcont = document.createElement("div");
        newcont.className = "menu-bx-ind-cont " + "bbwa_Page" + id;
        //newcont.id = 'bbwa_Page'+id;
        pgcont = gencontdiv.insertAdjacentElement("afterbegin", newcont);
        //newcont.innerHTML = Application.Placholder(placholder);
        //add to pages container for
        // console.log(newcont.id);
      } else {
        //pgcont = _IsArray(pgcont)?pgcont:[pgcont];
        //console.log(pgcont);
        for (var i = 0, leni = pgcont.length; i < leni; i++) {
          //take to the top to display it
          pgcont[i].parentElement.insertBefore(
            pgcont[i],
            pgcont[i].parentElement.firstElementChild
          );
        }
      }

      if (
        typeof Application.WorkingPages["bbwa_Page" + id] != "undefined" &&
        Application.WorkingPages["bbwa_Page" + id] == true
      ) {
        //if currently working - do nothing
      } else {
        /*pgcont = _IsArray(pgcont)?pgcont:[pgcont];

         for(var i=0,leni=pgcont.length;i<leni;i++){
        //insert the loading markup
        // pgcont[i].innerHTML = Application.LodingMk;
         
        } */
        Application.WorkingPages["bbwa_Page" + id] = false;
      }
      if (!cont.classList.contains("preview-mode")) {
        cont.classList.add("preview-mode");
        cont.parentElement.classList.add("preview-mode-parent");
        cont.parentElement.parentElement.classList.add("preview-mode-active");
      }
      if (!cont.parentElement.parentElement.classList.contains("previewed"))
        cont.parentElement.parentElement.classList.add("previewed");
      //Application.CurrentActive.length > 0 &&
      //alert(Application.CurrentActive[appgrpid]);
      /* if(typeof Application.CurrentActive[appgrpid] != "undefined" && Application.CurrentActive[appgrpid] != null && Application.CurrentActive[appgrpid] != obj){
        Application.CurrentActive[appgrpid].classList.remove("active");
      }
      Application.CurrentActive[appgrpid] = obj; */
      if (
        typeof Application.CurrentActive != "undefined" &&
        Application.CurrentActive != null &&
        Application.CurrentActive != obj
      ) {
        Application.CurrentActive.classList.remove("active");
      }
      Application.CurrentActive = obj;
      obj.classList.add("active");

      //load  markup form by the form builder
      if (Application.WorkingPages["bbwa_Page" + id] == false) {
        //alert(onloadfunc);
        //Application.PageAjax['bbwa_Page'+id] = new epapi();
        if (onloadfunc == null) {
          Application.LoadNextPage(id, 1, {}, placholder, appgrpid);

          //console.log("After LoadNextPage - "+id);
        } else {
          if (typeof DefaultAction != "undefined")
            Application.SaveLoadNextPage(
              null,
              DefaultAction.RID,
              DefaultAction.ApplyID,
              DefaultAction.PageNum,
              DefaultAction.Param,
              placholder,
              appgrpid
            );
        }
      }
      // alert(cont.id)
      cont.parentElement.classList.add("small-screen");

      //do beter
      var wind = _("menu-popup" + appgrpid);
      if (wind != null) {
        Application.Show(wind);
        return;
      }
      //_('main-body').classList.add('small-screen');
      //alert(obj);
      return id;
    },

    DisableButton: function (form, status) {
      status = typeof status == "undefined" ? true : false;
      //disable all buttons
      btns = form.getElementsByTagName("button");

      if (btns.length > 0) {
        for (let n = 0, l = btns.length; n < l; n++) {
          let rbtn = btns[n];
          rbtn.disabled = status;
        }
      }
    },
    SaveLoadNextPage(form, reqid, id, pageNum, param, placholder, appgrpid) {
      placholder = placholder || "textbox";
      var dataArr = [{}, {}];
      /*  if(form != null){
          dataArr = epapi.Utility.FormData(form,param);
         // alert(JSON.stringify(dataArr));
         if(typeof dataArr == "string"){
           MessageBox.Hint("Invalid Entering: "+dataArr,"exclamation-triangle",'gen_app_mssg');
           return;
         }
         
       }else{
         dataArr[0] = param;
       } */
      MessageBox.Show("Working...", "cog fa-spin", "gen_app_mssg");

      epapi.Utility.FormData(form, param)
        .then((dataArr) => {
          Application.DisableButton(form);
          //console.log(JSON.stringify(dataArr[0]));
          var files = dataArr[1];
          var blobs = dataArr[2];
          //dataArr["RequestID"] = reqid;
          //dataArr["Param"] = param;
          //alert(JSON.stringify(dataArr));
          if (sessionStorage.getItem("LoginName") != null) {
            dataArr[0]["LoginName"] = sessionStorage.getItem("LoginName");
            //pstr += "&LoginName="+escape();
          }
          dataArr[0]["ToPageNum"] = pageNum;
          var reqdet = { RequestID: reqid, Param: dataArr[0], ApplyID: id };
          if (files.length > 0) {
            for (var d = 0, lend = files.length; d < lend; d++) {
              reqdet[files[d]] = "?";
            }
          }

          if (blobs.length > 0) {
            for (const blobid of blobs) {
              reqdet[blobid] = "??";
            }
          }

          //console.log(reqdet);

          epapi.Request(reqdet, {
            OnComplete: function (res) {
              // alert('aaa')
              res = epapi.Responce(res); //proccess and get the responce
              if (epapi.IsError(res)) {
                //check if error
                //alert()

                var logo =
                  typeof res["Error"]["Logo"] != "undefined"
                    ? res["Error"]["Logo"]
                    : "exclamation-triangle";
                //Display error message
                if (res["Error"]["Code"] == "CE") {
                  MessageBox.Hint(
                    res["Error"]["Message"],
                    logo,
                    "gen_app_mssg"
                  );
                } else {
                  MessageBox.Hint(
                    res["Error"]["Code"] + " : " + res["Error"]["Message"],
                    logo,
                    "gen_app_mssg"
                  );
                }

                /*   var oppages = document.getElementsByName('bbwa_Page'+id);
                if(oppages != null && oppages.length > 0){
                  for(var o=0,leno=oppages.length;o<leno;o++){
                    if(oppages[o].firstElementChild.className == "loading-cont"){
                  
                      oppages[o].innerHTML = "";
                     // alert('sss');
                      var contd = _('id1');
                      contd.classList.remove('preview-mode');
                      contd.parentElement.classList.remove('preview-mode-parent')
                      contd.parentElement.parentElement.classList.remove('previewed');
                    }
                  }
                } */

                /* if(_('bbwa_Page'+id).firstElementChild.className == "loading-cont"){
                
                _('bbwa_Page'+id).innerHTML = "";
                var contd = _('id1');
                contd.classList.remove('preview-mode');
                contd.parentElement.classList.remove('preview-mode-parent')
                contd.parentElement.parentElement.classList.remove('previewed');
              } */

                // console.log(res);
              } else {
                //get the current applyid
                //var appid = _('ApplyID').value;
                // MessageBox.Hint("Page Data Saved Successfully","check",'gen_app_mssg');
                MessageBox.Close("gen_app_mssg");

                //merge returned data with param
                var objkeys = Object.keys(res);
                for (const reskey of objkeys) {
                  //if (res.hasOwnProperty(reskey)) {
                  param[reskey] = res[reskey];

                  // }
                }

                //console.log(JSON.stringify(param));
                pageNum =
                  typeof param["PageNum"] != _UND
                    ? Number(param["PageNum"])
                    : typeof param["NextPageNum"] != _UND
                    ? Number(param["NextPageNum"])
                    : pageNum;
                if (typeof param["__Notify__"] != "undefined") {
                  MessageBox.Notify(param["__Notify__"]);
                }
                //console.log(param);
                Application.LoadNextPage(
                  id,
                  pageNum,
                  param,
                  placholder,
                  appgrpid
                );
                //alert(JSON.stringify(res));
              }
              if (form != null) Application.DisableButton(form, false);

              //var win = window.open("../epconfig/GenScript/Payment/post.php?Ref="+escape(ref),"newwin","width=800,menubar=no,status=no,scrollbars=yes");
            },
          });
        })
        .catch((err) => {
          MessageBox.Hint(err, "exclamation-triangle", "gen_app_mssg");
          //console.log(form);
          Application.DisableButton(form, false);
        });

      //LoadPage(obj,id,appgrpid);
      //console.log(JSON.stringify(dataArr[0]));
      //return
    },
    PrintSlip: function (url) {
      // var win = window.open(url,"newwins","width=600,menubar=no,status=no,scrollbars=yes");
      var win = window.open(
        url,
        "newwins",
        "width=600,menubar=no,status=no,scrollbars=yes"
      );
    },
    LoadPrevPage: (backbtn) => {
      var mobilebtn = null;
      if (backbtn.classList.contains("menubtn")) {
        //if mobile button version
        mobilebtn = backbtn;
        //get the large screen button version
        backbtn = backbtn.parentElement.nextElementSibling.querySelector(
          ".back-btn .ind-menu-bx"
        );
      }
      var curdisplaypage =
        backbtn.parentElement.parentElement.nextElementSibling.firstElementChild
          .firstElementChild;
      //this.parentElement.nextElementSibling.classList.remove('preview-mode-parent');
      //this.parentElement.nextElementSibling.firstElementChild.classList.remove('preview-mode');
      //this.parentElement.parentElement.classList.remove('previewed');
      //check if the first element
      if (curdisplaypage.classList.contains("isfirst")) {
        //is the first element laod the module page
        var bodyelem = backbtn.parentElement.parentElement.parentElement;
        bodyelem.classList.remove("preview-mode");
        bodyelem.parentElement.classList.remove("preview-mode-parent");
        bodyelem.parentElement.parentElement.classList.remove(
          "preview-mode-active"
        );
        if (mobilebtn != null) {
          //if mobile button which is at the head section
          mobilebtn.parentElement.parentElement.classList.remove("previewed");
        }
        //clear all in the page
        var pg = curdisplaypage.parentElement;
        pg.innerHTML = "";
        //MessageBox.Hint("All Saved Pages Cleared",'trash','clearpage');
      } else {
        //load the previously cached page
        var cachetype = curdisplaypage.getAttribute("data-cache");
        const parentd = curdisplaypage.parentElement;

        if (cachetype != "both" && cachetype != "backward") {
          //console.log('ddda');
          curdisplaypage.parentElement.removeChild(curdisplaypage);
        } else {
          //if to be cached
          //remove the class inback to indicate that the page is in no more in back cache mode (it is in front), so that we can manage all cached page e.g css rule
          curdisplaypage.classList.remove("inback");
          curdisplaypage.parentElement.insertAdjacentElement(
            "beforeend",
            curdisplaypage
          );
          /* const pdata = Application.PageData(curdisplaypage);
          console.log(pdata);
          const curentttledis = Array.from(document.getElementsByClassName('curentdistxt' + pdata['ApplyGroupID']));
          if (curentttledis.length > 0) {
            curentttledis.forEach(dis => {
              dis.textContent = pdata.Name;
            })
          } */

          //distit = typeof pdata == 'undefined'?fchild.getAttribute("data-name"):pdata.Name;
        }
        //get the displayed page
        const dispage = parentd.firstElementChild;
        const pdata = Application.PageData(dispage);
        const curentttledis = Array.from(
          document.getElementsByClassName(
            "curentdistxt" + pdata["ApplyGroupID"]
          )
        );
        if (curentttledis.length > 0) {
          curentttledis.forEach((dis) => {
            dis.textContent = pdata.Name;
          });
        }
      }
    },
    PageData: (page) => {
      const pobj = page.getElementsByClassName("PageData")[0];
      try {
        pagedata = JSON.parse(pobj.textContent);
        return pagedata;
      } catch (error) {
        return [];
      }
    },
    LoadNextPage: function (id, pageNum, param, placeh, appgrpid) {
      placeh = placeh || "textbox";
      var pg = _("bbwa_Page" + id);
      let distit = "";
      // console.log("LoadNext:"+"indpage_"+appgrpid+"_"+id+"_"+pageNum);
      //1. check if loading page already exist
      pageNum = parseInt(pageNum);
      pageNum = isNaN(pageNum) || pageNum == 0 ? 1 : pageNum;
      //LoadPrevPage
      const curentttledis = Array.from(
        document.getElementsByClassName("curentdistxt" + appgrpid)
      );
      const grpledis = document.getElementsByClassName(
        "groupdistxt" + appgrpid
      )[0];
      distit = grpledis.textContent;
      // console.log('curentdistxt' + appgrpid)

      var laodingpage = _("indpage_" + appgrpid + "_" + id + "_" + pageNum);
      // console.log("indpage_"+appgrpid+"_"+id+"_"+pageNum);
      if (laodingpage != null) {
        if (laodingpage == laodingpage.parentElement.firstElementChild) return;
        //get the page that is currently displayed and get its cachetype
        var curdispage = laodingpage.parentElement.firstElementChild;
        var cachetype = curdispage.getAttribute("data-cache");

        //before displaying the page remove the inback class
        laodingpage.classList.remove("inback");
        const pdata = Application.PageData(laodingpage);
        distit =
          typeof pdata == "undefined"
            ? laodingpage.getAttribute("data-name")
            : pdata.Name;
        if (curentttledis.length > 0) {
          curentttledis.forEach((dis) => {
            dis.textContent = distit;
          });
        }

        //bring to front to display it
        laodingpage.parentElement.insertBefore(laodingpage, curdispage);
        //check if last display page is not to be cache
        if (cachetype != "both" && cachetype != "forward") {
          curdispage.parentElement.removeChild(curdispage);
        } else {
          //if to be cached
          //set the class inback to indicate that the page is in cache mode, so that we can manage all cached page e.g css rule
          curdispage.classList.add("inback");
        }
        return;
      }

      if (curentttledis.length > 0) {
        curentttledis.forEach((dis) => {
          dis.textContent = "...";
        });
      }

      //get the
      var curdispage = pg.firstElementChild;

      // alert(_);
      // MessageBox.Show("Loading Next Page ...","cog fa-spin",'bbwa_Page'+id+"_mss");
      // pg.innerHTML = Application.Placholder(placeh);
      //console.log(pg);
      pg.insertAdjacentHTML("afterbegin", Application.Placholder(placeh));
      //console.log(Application.Placholder(placeh));
      pageNum = typeof pageNum == "undefined" ? 1 : pageNum;
      // var pstr = "ApplyID="+id+"&PageNum="+pageNum+"&ApplyGroupID="+appgrpid;

      param["ApplyID"] = id;
      param["PageNum"] = pageNum;
      param["ApplyGroupID"] = appgrpid;
      if (sessionStorage.getItem("LoginName") != null) {
        // pstr += "&LoginName="+escape(localStorage.getItem("LoginName"));
        param["LoginName"] = sessionStorage.getItem("LoginName");
      }
      /* if(typeof param != "undefined"){
        //alert(JSON.stringify(param));
        param = _ArrayToString2(param);
        pstr += "&"+param;
      } */
      //console.log(param);

      param["SubDir"] = configdata["SubDir"];
      param["Core"] = configdata["Core"];
      //alert(param);
      //encodeURIComponent
      //console.log(JSON.stringify(param));
      if (typeof Application.PageAjax["bbwa_Page" + id] == _UND)
        Application.PageAjax["bbwa_Page" + id] = new Ajax();
      //console.log(configdata['Core'] + "epapi/formbuilder.php")
      Application.PageAjax["bbwa_Page" + id].Post({
        Action: configdata["Core"] + "epapi/formbuilder.php",
        Data: { Param: encodeURIComponent(JSON.stringify(param)) },
        OnComplete: function (res, url, param) {
          //console.log(res);
          //get the markup and other infos
          let detarr = res.split("@@!!~~#@");
          if (detarr.length > 1) {
            res = detarr[0];
            let others = detarr[1];
            try {
              var info = JSON.parse(others);
              if (typeof info.Alert != _UND) {
                MessageBox.Hint(info.Alert, "info-circle", "alertbxx");
              }

              if (typeof info["__Notify__"] != "undefined") {
                // console.log(info['__Notify__']);
                MessageBox.Notify(
                  info["__Notify__"]["Msg"],
                  info["__Notify__"]["Title"]
                );
              }
              // console.log(info);
              //cont.innerHTML = err.Message;
              //MessageBox.Hint(err.Message,'exclamation-triangle',"load_win");
            } catch (e) {
              //MessageBox.Hint("System Error occur while processing Page",'exclamation-triangle',"load_wine");
            }
          }

          if (typeof _Trim(res) == "") {
            res = "";
          } else {
            //res = info.Markup;
            if (typeof info != "undefined") {
              //check if page already exist
              var laodingpagenow = _(
                "indpage_" +
                  info.ApplyGroupID +
                  "_" +
                  info.ApplyID +
                  "_" +
                  info.NowPageNum
              );
              if (laodingpagenow != null) {
                //remove it
                laodingpagenow.parentElement.removeChild(laodingpagenow);
              }
            }
          }
          param = JSON.parse(decodeURIComponent(param["Param"]));
          //console.log(param);
          //var pg = _('bbwa_Page'+param['ApplyID']);
          pg = _IsArray(pg) ? pg : [pg];
          //alert(pg.length);
          //return;
          for (var p = 0, lenp = pg.length; p < lenp; p++) {
            //pg[p].innerHTML = res;
            var npage = pg[p];
            //Get the total number of pages already loaded (cached)
            // var totlaoded = pg[p].getElementsByClassName('indpage').length;
            var isfirstNotCache = false; //determine if the current Display is first and not cache

            if (curdispage != null) {
              //if there is currently display page
              //get the current Display Page
              //var curdispage = npage.firstElementChild;
              //Get the cache type
              var cachetype = curdispage.getAttribute("data-cache");
              //check if page is not to be cache
              if (cachetype != "both" && cachetype != "forward") {
                if (curdispage.classList.contains("isfirst")) {
                  //the current display is first and it will be remove,
                  //i.e - transfer the isfirst class to the next added page
                  isfirstNotCache = true;
                }
                //console.log(curdispage.parentElement);
                if (curdispage.parentElement != null) {
                  //remove the page
                  curdispage.parentElement.removeChild(curdispage);
                }
              } else {
                //if to be cached
                //set the class inback to indicate that the page is in cache mode, so that we can manage all cached page e.g css rule
                curdispage.classList.add("inback");
              }
            }

            //check if an error sent from backend
            try {
              const errDet = JSON.parse(res);
              if (errDet && errDet.Error) {
                res = errDet.Error.Markup
                  ? errDet.Error.Markup
                  : errDet.Error.Message;
              }
            } catch (error) {}

            //Add the New Page
            npage.insertAdjacentHTML("afterbegin", res);
            //Get the new page
            var fchild = npage.firstElementChild;
            //chek if the cache is to be cleared data-name
            var clearcache = fchild.getAttribute("data-clear");
            //console.log(fchild)

            const pdata = Application.PageData(fchild);
            distit =
              typeof pdata == "undefined"
                ? fchild.getAttribute("data-name")
                : pdata.Name;

            if (clearcache != null && clearcache != "") {
              var q = "";
              if (clearcache == "all") {
                q = ".indpage";
              } else {
                let allpageid = clearcache.split(",");
                if (allpageid.length > 0) {
                  q = allpageid
                    .map((pid) => {
                      return "#indpage_" + appgrpid + "_" + id + "_" + pid;
                    })
                    .join(",");
                }
              }

              if (q != "") {
                //if query formed
                var allnpage = npage.querySelectorAll(q);
                //console.log(allnpage.length);
                //remove all from cache
                if (allnpage.length > 0) {
                  for (var cp = 0, lencp = allnpage.length; cp < lencp; cp++) {
                    let cachpg = allnpage[cp];
                    if (cachpg != fchild) {
                      //check if page to remove is first page, give the new page the first page
                      if (
                        isfirstNotCache == false &&
                        cachpg.classList.contains("isfirst")
                      ) {
                        isfirstNotCache = true;
                      }
                      //remove it
                      npage.removeChild(cachpg);
                    }
                  }
                }
              }
            }
            //if the first added set it as isFirst
            if (curdispage == null || isfirstNotCache)
              fchild.classList.add("isfirst");
            //initialize the controls and elements of the page
            window.setTimeout(() => {
              ProcessPage(fchild);
            }, 1);
            window.setTimeout(() => {
              Application.RemovePlaceholders(npage);
            });
          }

          curentttledis.forEach((dis) => {
            dis.textContent = distit;
          });

          /*  pg.innerHTML = res;
           ProcessPage(pg); */

          //MessageBox.Close('bbwa_Page'+param['ApplyID']+"_mss");
        },
        OnError: function (res, url, param) {
          pg.innerHTML = res;
          //MessageBox.Hint("Error: "+res,'exclamation-triangle','bbwa_Page'+param['ApplyID']+"_mss");
        },
        OnAbort: function (res, url, param) {
          pg.innerHTML = res;
          // MessageBox.Hint("Loading Page Aborted",'exclamation-triangle','bbwa_Page'+param['ApplyID']+"_mss");
        },
      });
      //console.log("Finish LoadNextPage - "+id);
    },
    //payment page
    FormRequest: function (form, reqid, NextPageNum, inData) {
      //alert(form);
      //alert(JSON.stringify(inData));
      inData = inData || {};
      //alert(JSON.stringify(inData));
      /* var dataArr = epapi.Utility.FormData(form);
     // alert(JSON.stringify(dataArr));
      
      if(typeof dataArr == "string"){
          MessageBox.Hint("Invalid Entering: "+dataArr,"exclamation-triangle",'pay_app_mssg');
          return;
        } */
      MessageBox.Show("Working ...", "cog fa-spin", "pay_app_mssg");
      epapi.Utility.FormData(form)
        .then((dataArr) => {
          dataArr[0] = _MergeObj(dataArr[0], inData);
          //alert(JSON.stringify(dataArr));
          if (
            dataArr[0]["NotPaid"] == 1 &&
            (_Trim(dataArr[0]["PayeeFullName"]) == "" ||
              _Trim(dataArr[0]["PayeeEmail"]) == "")
          ) {
            MessageBox.Hint(
              "To make Payment, your Fullname, Email Address and Phone Number is compulsary",
              "exclamation-triangle",
              "pay_app_mssg"
            );
            return;
          }
          dataArr[0]["NextPageNum"] = NextPageNum || 0;

          //if initialization
          if (dataArr[0]["NotPaid"] == 1) {
            MessageBox.Show(
              "Initializing Payment ...",
              "cog fa-spin",
              "pay_app_mssg"
            );
            if (sessionStorage.getItem("LoginName") != null) {
              dataArr[0]["LoginName"] = sessionStorage.getItem("LoginName");
              //pstr += "&LoginName="+escape();
            }

            var reqdet = { RequestID: "R008", Param: dataArr[0] };
            epapi.Request(reqdet, {
              OnComplete: function (res) {
                //console.log(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,
                    "pay_app_mssg"
                  );
                } else {
                  console.log(res["Redirect"]);
                  if (typeof res["PayRef"] != "undefined") {
                    MessageBox.Hint(
                      "Payment Initialized Successfully, Continue in the Popup",
                      "exclamation-triangle",
                      "pay_app_mssg"
                    );
                    if (res["PayOption"] == 2) {
                      var win = window.open(
                        res["Redirect"],
                        "newwin",
                        "width=600,menubar=no,status=no,scrollbars=yes"
                      );
                    } else if (res["PayOption"] == 3) {
                      MessageBox.Hint(
                        "Wallet Payment Not Enabled",
                        "exclamation-triangle",
                        "wallpd"
                      );
                    } else {
                      _Printer.Load({ Src: res["Redirect"], Data: "" });
                    }
                    //
                  } else {
                    MessageBox.Hint(
                      "Uknown Error",
                      "exclamation-triangle",
                      "pay_app_mssg"
                    );
                  }
                }

                //var win = window.open("../epconfig/GenScript/Payment/post.php?Ref="+escape(ref),"newwin","width=800,menubar=no,status=no,scrollbars=yes");
              },
            });
          } else {
            // alert(JSON.stringify(dataArr[0]));
            MessageBox.Show(
              "Please Wait, we are verifying your Payment ...",
              "cog fa-spin",
              "pay_app_mssg"
            );
            reqid = reqid != "" && reqid != "R008" ? "R009," + reqid : "R009";
            if (sessionStorage.getItem("LoginName") != null) {
              dataArr[0]["LoginName"] = sessionStorage.getItem("LoginName");
              //pstr += "&LoginName="+escape();
            }
            var reqdet = { RequestID: reqid, Param: dataArr[0] };
            epapi.Request(reqdet, {
              OnComplete: function (res) {
                //alert(res);
                res = epapi.Responce(res); //proccess and get the responce
                if (epapi.IsError(res)) {
                  //check if error
                  //alert()
                  var logo =
                    typeof res["Error"]["Logo"] != "undefined"
                      ? res["Error"]["Logo"]
                      : "exclamation-triangle";
                  //Display error message
                  MessageBox.Hint(
                    res["Error"]["Message"],
                    logo,
                    "pay_app_mssg"
                  );
                  //console.log(res["Error"]["Message"]);
                } else {
                  //get the current applyid
                  var appid = _("ApplyID").value;
                  var appgrpid = _("ApplyGroupID").value;

                  MessageBox.Hint(
                    "Payment Verified Successfully",
                    "check-circle",
                    "pay_app_mssg"
                  );
                  //alert(JSON.stringify(res));
                  //if(typeof res["Prog"] == "undefined" || res["Prog"] == null || _Trim(res["Prog"]) == ""){
                  /* if(typeof res['NextPageNum'] == _UND && typeof res["R009"]['NextPageNum'] != _UND)res['NextPageNum'] = res["R009"]['NextPageNum'];
                if(typeof res['RegLevel'] == _UND && typeof res["R009"]['RegLevel'] != _UND)res['RegLevel'] = res["R009"]['RegLevel']; */
                  //merarge data
                  var reqidarr = reqid.split(",");
                  var newres = res;
                  if (reqidarr.length > 1) {
                    for (var s = 0, lens = reqidarr.length; s < lens; s++) {
                      reqrid = reqidarr[s];
                      if (typeof res[reqrid] != _UND) {
                        var objkeys = Object.keys(res[reqrid]);
                        for (const key of objkeys) {
                          //if (res[reqrid].hasOwnProperty(key)) {
                          newres[key] = res[reqrid][key];
                          // }
                        }
                      }
                    }
                  }
                  res = newres;
                  if (Number(res["NextPageNum"]) < 1) {
                    if (res["RegLevel"] < 2) {
                      res["RegLevel"] = 2;
                    } else {
                      res["RegLevel"] += 1;
                    }
                  } else {
                    res["RegLevel"] = res["NextPageNum"];
                  }

                  // return;
                  if (typeof res["__Notify__"] != "undefined") {
                    MessageBox.Notify(res["__Notify__"]);
                  }
                  Application.LoadNextPage(
                    appid,
                    res["RegLevel"],
                    res,
                    "",
                    appgrpid
                  );
                  //}else{
                  // Application.LoadNextPage(appid,7,res);
                  // }

                  //alert(JSON.stringify(res));
                }

                //var win = window.open("../epconfig/GenScript/Payment/post.php?Ref="+escape(ref),"newwin","width=800,menubar=no,status=no,scrollbars=yes");
              },
            });
          }
        })
        .catch((err) => {
          MessageBox.Hint(
            "Invalid Entering: " + err,
            "exclamation-triangle",
            "pay_app_mssg"
          );
        });
    },
    Activate: function (epwin) {
      //epwin.style.transform = "none";
      _Drag.Element(epwin, {
        Handle: epwin.getElementsByClassName("headwin")[0],
        OnStart: function () {
          document.body.classList.add("noselection");
        },
        OnFinish: function () {
          document.body.classList.remove("noselection");
        },
        OnDrag: function (e) {
          //calculate the font size as user drags the slider (minimum value = 5, maximum value = 40)
          //NB: the max drag left value of slider is 210
          //_('aim-printpdf-fontsize').textContent = Math.floor((e.Left / 210) * 37) + 5;
        },
        OnFinish: function () {
          //perform the printer refresh after fontsize set (drag ends)
          //reset the Font size and refresh printer
        },
      });

      DragStartDim = {};

      //handle top resizing
      _Drag.Element(epwin, {
        Handle: epwin.getElementsByClassName("Top")[0],
        Direction: "Y",
        OnStart: function (e) {
          document.body.classList.add("noselection");
          //var pelem = e.Element.parentElement;
          var dim = _GetDimension(e.Element);
          var botomelem = e.Element.getElementsByClassName("Bottom")[0];
          var bottomdimdim = _GetDimension(botomelem);
          bottomdimdim.BottomElement = botomelem;
          dim.BottomLine = bottomdimdim;
          DragStartDim[_GetId(e.Element)] = dim;
        },
        OnFinish: function () {
          document.body.classList.remove("noselection");
        },
        OnDrag: function (e) {
          //calculate the font size as user drags the slider (minimum value = 5, maximum value = 40)

          var elemstartdim = DragStartDim[_GetId(e.Element)];
          var dim = _GetDimension(e.Element);
          var curhe = elemstartdim.height - (dim.top - elemstartdim.top);
          e.Element.style.height = curhe + "px";
          //Re calculate the position of the bottom line
          elemstartdim.BottomLine.BottomElement.style.top = curhe - 8 + "px";
          //pelem.style.top = (elemstartdim.top + e.Top) + 'px';
        },
      });

      //handles bottom resizing
      //alert(epwin.outerHTML);
      _Drag.Element(epwin.getElementsByClassName("Bottom")[0], {
        Direction: "Y",
        OnStart: function (e) {
          document.body.classList.add("noselection");
          //var pelem = e.Element.parentElement;
          var dim = _GetDimension(e.Element);
          var dimparent = _GetDimension(e.Element.parentElement);
          dim.Parent = dimparent;
          DragStartDim[_GetId(e.Element)] = dim;
        },
        OnFinish: function () {
          document.body.classList.remove("noselection");
        },
        OnDrag: function (e) {
          //calculate the font size as user drags the slider (minimum value = 5, maximum value = 40)

          var elemstartdim = DragStartDim[_GetId(e.Element)];
          var dim = _GetDimension(e.Element);
          // var topdif = -(dim.top - elemstartdim.top);
          e.Element.parentElement.style.height =
            elemstartdim.Parent.height + (dim.top - elemstartdim.top) + "px";
          //pelem.style.top = (elemstartdim.top + e.Top) + 'px';
        },
      });

      //handle left resizing
      _Drag.Element(epwin, {
        Handle: epwin.getElementsByClassName("Left")[0],
        Direction: "X",
        OnStart: function (e) {
          document.body.classList.add("noselection");
          //var pelem = e.Element.parentElement;
          e.Element.style.transform = "none";
          // e.Element.style.transform = "translate3d(0%,4vh,0px) scale3d(1,1,1)";

          e.Element.style.left = e.ClientX + "px";

          var dim = _GetDimension(e.Element);
          e.Element.style.top = dim.top + "px";
          //var botomelem = e.Element.getElementsByClassName('Bottom')[0];
          //var bottomdimdim = _GetDimension(botomelem);
          //bottomdimdim.BottomElement = botomelem;
          //dim.BottomLine = bottomdimdim;
          DragStartDim[_GetId(e.Element)] = dim;
        },
        OnFinish: function () {
          document.body.classList.remove("noselection");
        },
        OnDrag: function (e) {
          //calculate the font size as user drags the slider (minimum value = 5, maximum value = 40)

          var elemstartdim = DragStartDim[_GetId(e.Element)];
          var dim = _GetDimension(e.Element);
          var curhe = elemstartdim.width - (dim.left - elemstartdim.left);
          //console.log("El ID: "+e.Element.id);
          //console.log("Left Moved: "+(dim.left));
          //console.log("Now Width: "+(elemstartdim.width - (dim.left - elemstartdim.left)));
          //console.log(dim.left);
          //console.log(elemstartdim.left);
          e.Element.style.left = dim.left + "px";
          e.Element.style.width = curhe + "px";
          _("Right").style.left = curhe - 2 + "px";
          //Re calculate the position of the bottom line
          //elemstartdim.BottomLine.BottomElement.style.top = (curhe - 8) + 'px';
          //pelem.style.top = (elemstartdim.top + e.Top) + 'px';
        },
      });

      //handles right resizing
      _Drag.Element(epwin.getElementsByClassName("Right")[0], {
        Direction: "X",
        OnStart: function (e) {
          document.body.classList.add("noselection");
          //var pelem = e.Element.parentElement;
          var dim = _GetDimension(e.Element);
          var dimparent = _GetDimension(e.Element.parentElement);
          dim.Parent = dimparent;
          e.Element.parentElement.style.transform = "none";
          // e.Element.parentElement.style.transform = "translate3d(0%,4vh,0px) scale3d(1,1,1)";
          e.Element.parentElement.style.top = dimparent.top + "px";
          e.Element.parentElement.style.left =
            e.ClientX - dimparent.width + "px";
          DragStartDim[_GetId(e.Element)] = dim;
        },
        OnFinish: function () {
          document.body.classList.remove("noselection");
        },
        OnDrag: function (e) {
          //calculate the font size as user drags the slider (minimum value = 5, maximum value = 40)

          var elemstartdim = DragStartDim[_GetId(e.Element)];
          var dim = _GetDimension(e.Element);
          // var topdif = -(dim.top - elemstartdim.top);
          e.Element.parentElement.style.width =
            elemstartdim.Parent.width + (dim.left - elemstartdim.left) + "px";
          //pelem.style.top = (elemstartdim.top + e.Top) + 'px';
        },
      });
      Application.ResetDemension(epwin);
    },
  };

  // Login Processes
  Login = {
    SetAutoOpenApply: function (obj) {
      if (obj.checked == true) {
        Cookie.Set("AutoOpenApply", "1", 2390000099889900);
      } else {
        Cookie.Set("AutoOpenApply", "0", 2390000099889900);
      }
    },
    AutoOpenApply: function () {
      if (typeof DefaultAction != "undefined" && DefaultAction != null) {
        Application.Show();
        // alert(_('appmenu'+DefaultAction.ApplyID).className);
        Application.LoadPage(
          _("appmenu" + DefaultAction.ApplyID),
          DefaultAction.ApplyID,
          1,
          "global"
        );
      } else {
        var autoop = Cookie.Get("AutoOpenApply");

        var oa = _("autoopenapply");
        if (autoop == "1") {
          Application.Load({
            ApplyGID: "2_1",
            AutoLoad: "true",
            Home: "true",
            Logout: "false",
            Guest: "true",
            AutoLoadStatus: "true",
          });
          //oa.checked = true
        } else {
          // oa.checked = false;
        }
      }
    },
    Request: null,
    Working: false,
    SID: null,
    Open: function () {
      document.body.className += " bbwa-login";
      _("main-uname").focus();
    },
    AbortVerify: function () {
      //alert(Login.Request);
      if (Login.Request != null) {
        Login.Request.Ajax.Abort();
      }
    },
    Close: function () {
      //alert('close')
      Login.Reset();
      document.body.className = document.body.className.replace(
        " bbwa-login",
        ""
      );
    },
    Reset: function () {
      var unamtb = _("main-uname");
      if (Login.Working) {
        Login.AbortVerify();
        // loginbx.className = loginbx.className.replace(" password-level","");
      } else {
        //enable texboxes and butons

        unamtb.disabled = false;
        _("main-passw").disabled = false;
        var btn = _("login-ver-btn");
        btn.disabled = false;
        //Login.Working = false; //indicate verification ends
        btn.className = btn.className.replace(" w3-animate-fading", ""); //stop the animation on the verify button
        Login.Request = null; // Reset the request object

        // loginbx.className = loginbx.className.replace(" password-level","");
      }
      var loginbx = _("login-main-bx");
      loginbx.className = loginbx.className.replace(" password-level", "");
      Login.SID = null;
      var unamedisplay = _("usnme");
      unamedisplay.textContent = "";
      var regnodisplay = _("regno");
      regnodisplay.textContent = "";
      var studpassp = _("stud-passp");
      studpassp.style.backgroundImage =
        "url(" + configdata["Core"] + "images/bbwa/logo.png)";
      unamtb.focus();
    },
    CurrentRegNo: "",
    //Verify RegNo and Accesscode
    Verify: function (btn) {
      //Login.SID will hold the Student DB ID after Email Verification
      var tb = Login.SID == null ? "main-uname" : "main-passw"; //help determine which input element to validate
      //get the user supplied username
      var unmtb = _(tb); //get the input element
      if (_Trim(unmtb.value) == "") {
        //if nothing entered
        MessageBox.Hint(
          "Opps, Nothing Supplied!!!.",
          "exclamation-triangle",
          "loginverify"
        );
        return;
      }
      var unamedisplay = _("usnme"); //unamedisplay.textContent = "";
      var regnodisplay = _("regno"); //regnodisplay.textContent = "";
      var studpassp = _("stud-passp"); //studpassp.style.backgroundImage = 'url(images/bbwa/logo.png)';
      Login.Working = true; //indicate verification starts
      unmtb.disabled = true; //disable the input elemet
      btn.disabled = true; //disable the verify button
      btn.className += " w3-animate-fading"; //animate the button to fade in and fadeout
      //set message to display on message box based on the verification type
      var pver =
        Login.SID == null
          ? "Please Wait!! while we verify your Reg. Number"
          : "Please Wait!! while we verify your Access-code";
      MessageBox.Show(pver, "cog fa-spin", "loginverify", Login.AbortVerify); //displFay the verification in progress message and set the abort function
      //Request verification based on the verification type (RegNo or access code)
      var requestdet =
        Login.SID == null
          ? { RequestID: "R002", Param: { LoginName: unmtb.value } }
          : {
              RequestID: "R003",
              Param: {
                AccessCode: unmtb.value,
                LRegNo: sessionStorage.getItem("LRegNo"),
              },
            };
      Login.Request = epapi.Request(requestdet, {
        OnComplete: function (res) {
          //response from api

          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, "loginverify");

            //enable texboxes and butons
            unmtb.disabled = false;
            btn.disabled = false;
            Login.Working = false; //indicate verification ends
            btn.className = btn.className.replace(" w3-animate-fading", ""); //stop the animation on the verify button
            Login.Request = null; // Reset the request object
            unmtb.focus();
          } else {
            //if no error occures
            //alert(JSON.stringify(res));
            if (Login.SID == null) {
              //if verification is RegNo
              unamedisplay.textContent =
                res.SurName + " " + res.FirstName + " " + res.OtherNames; //set the student names display
              regnodisplay.textContent = res.RegNo; //set the student regno
              Login.CurrentRegNo = res.RegNo;
              //alert(res.Image);
              //console.log(JSON.stringify(res));
              // studpassp.style.backgroundImage = _Trim(res.Image) == ""?'url(images/bbwa/logo.png)':'url('+res.Image+')';
              studpassp.style.cssText =
                _Trim(res.DataUrIImage) == ""
                  ? "background-image:url(" +
                    configdata["Core"] +
                    "images/bbwa/logo.png)"
                  : "background-image:url('" + res.DataUrIImage + "')";
              //alert(res.Image);
              //alert(_Trim(res.Image) == ""?'url(images/bbwa/logo.png)':'url('+res.Image+')');
              //alert(res.Image);
              //display success message
              //MessageBox.Hint("Registration Number Verified Successfuly. Please Supply your Access Code","check",'loginverify');
              MessageBox.Close("loginverify", true);
              //set the class to animate in all the student display design
              _("login-main-bx").className += " password-level";
              Login.SID = res.id; //set the Login.SID to indicate a RegNo verification done
              //set password to have focus
              _("main-passw").focus();
              //keep the regno in a sessionstorage
              sessionStorage.setItem("LRegNo", res.RegNo);
            } else {
              //if password verifcation
              //Display the success message and perform the Home Page Loading
              //MessageBox.Hint("You have logged in Successfuly. Loading the Home Page ...","check",'loginverify');
              MessageBox.Close("loginverify", true);
              //reset login elemets
              //reset to RegNo Verification
              _("login-main-bx").className = _(
                "login-main-bx"
              ).className.replace(" password-level", "");
              Login.SID = null;
              //keep the login user in localstorage
              sessionStorage.setItem(
                "LoginName",
                sessionStorage.getItem("LRegNo")
              );
              sessionStorage.removeItem("LRegNo");
              //load main page
              Login.LoadMain();
              //clear the password field
              unmtb.value = "";
            }

            //enable buttons and textboxes
            unmtb.disabled = false;
            btn.disabled = false;
            //stop the animation on button
            btn.className = btn.className.replace(" w3-animate-fading", "");
            Login.Working = false; //indicates verification operation has ended
            //Reset the request object
            Login.Request = null;
          }
        },
        OnAbort: function (res) {
          //alert('aborted');
          MessageBox.Hint(
            "Account Verification Canceled !!!",
            "ban",
            "loginverify"
          );
          unmtb.disabled = false;
          btn.disabled = false;
          btn.className = btn.className.replace(" w3-animate-fading", "");
          Login.Working = false;
          //MessageBox.Close('loginverify');
          Login.Request = null;
        },
      });
    },

    LoadMain: function () {
      if (sessionStorage.getItem("LoginName") == null) return;

      MessageBox.Show(
        "Please wait while we prepare your Dashboard ...",
        "cog fa-spin",
        "mainpageloading"
      );
      let setStruc =
        localStorage.getItem("DispStruc") == null
          ? "liststruc"
          : localStorage.getItem("DispStruc");
      document.body.classList.add(setStruc);
      //load the main page.
      var MainPajeAjax = epapi.Ajax.Post({
        Action: configdata["Core"] + "designs/main.php",
        Data: {
          LoginName: sessionStorage.getItem("LoginName"),
          Config: encodeURIComponent(JSON.stringify(configdata)),
        },
        OnComplete: function (res, url, param) {
          if (_Trim(res) == "#") {
            MessageBox.Close("mainpageloading");
            return;
          }

          var logid = _("bbwa-login-bx");

          logid.className += " fadeOut ";
          //the right side
          let rightsde = _("bbwa-main-2");
          rightsde.classList.add("hideevery");
          //console.log(logid.className);
          var footr = _("screen-footer");
          footr.className += " fadeOut ";
          if (!document.body.classList.contains("bbwa-login"))
            document.body.className += " bbwa-login";
          document.body.insertAdjacentHTML("afterbegin", res);
          //var pg = _('bbwa_Page'+param['ApplyID'])
          // pg.innerHTML = res;
          //ProcessPage(pg);
          MessageBox.Close("mainpageloading");
          //Set the onclick event of addin link
          let linkbtn = document.getElementById("addnewmenu");
          //alert(linkbtn);
          if (linkbtn) {
            linkbtn.addEventListener("click", (e) => {
              var addlinkcont = Login.TemplateContent("addlink");
              if (addlinkcont) {
                //
                //  alert(addlinkcont);
                addlinkcont.firstElementChild.classList.remove("w3-hide");
                MessageBox.Popup(addlinkcont);
              }
              // var markup = ``;
              //  MessageBox.Popup(markup);
            });
          }

          //add event handler to structure buttons
          let btns = document.getElementsByClassName("strucbtn");
          Array.from(btns).forEach((btn) => {
            btn.addEventListener("click", (ev) => {
              if (btn.classList.contains("struclist")) {
                document.body.classList.remove("gridstruc", "grid2struc");
                document.body.classList.add("liststruc");
                localStorage.setItem("DispStruc", "liststruc");
              } else if (btn.classList.contains("strucgrid")) {
                document.body.classList.remove("liststruc", "grid2struc");
                document.body.classList.add("gridstruc");
                localStorage.setItem("DispStruc", "gridstruc");
              } else {
                document.body.classList.remove("liststruc", "gridstruc");
                document.body.classList.add("grid2struc");
                localStorage.setItem("DispStruc", "grid2struc");
              }
            });
          });
        },
        OnError: function (res, url, param) {
          MessageBox.Hint(
            "Error: " + res,
            "exclamation-triangle",
            "mainpageloading"
          );
        },
        OnAbort: function (res, url, param) {
          // _('bbwa_Page'+param['ApplyID']).innerHTML = res;
          MessageBox.Hint(
            "Error: " + res,
            "exclamation-triangle",
            "mainpageloading"
          );
        },
      });
    },
    TemplateContent: function (templid) {
      var cont = null;
      var templ = document.getElementById(templid);
      if (templ) {
        if (document.createElement("template").content) {
          cont = templ.content.cloneNode(true);
        } else {
          cont = templ.cloneNode(true);
        }
      }
      return cont;
    },
    Logout: function () {
      /* var requestdet = {RequestID:"R025",Param:{}};
      MessageBox.Show("Logging out ...","cog fa-spin",'logoutrrrr');
      epapi.Request(requestdet, 
        {OnComplete:function (res) {
          window.location = "?l="+(111111 * Math.random());
        }
      }
      ); */
      MessageBox.Show("Logging out ...", "cog fa-spin", "logoutrrrr");
      sessionStorage.removeItem("LoginName");
      window.location = "?l=" + 111111 * Math.random();
    },
  };

  LoadLGA = function (selElmnt) {
    //alert(selElmnt.options[selElmnt.selectedIndex].value);
    epapi.Utility.LoadMarkup(
      _("LGA_Cand"),
      "R012",
      { StateID: selElmnt.options[selElmnt.selectedIndex].value },
      '<option value="{{LGAID}}">{{LGAName}}</option>'
    );
  };
  LoadSelect = function (loadElemet, RID, param, keys) {
    if (loadElemet) {
      MessageBox.Show(
        "Loading " + loadElemet.title,
        "cog fa-spin",
        "markuploading"
      );
      var mdefault = "";
      if (typeof loadElemet.title != _UND)
        mdefault = '<option value="0">' + loadElemet.title + "</option>";
      epapi.Utility.LoadMarkup(
        loadElemet,
        RID,
        param,
        '<option value="{{' + keys.Value + '}}">{{' + keys.Text + "}}</option>",
        mdefault
      );
    }
  };

  AddElement = function (Elem) {
    var newElem = _Cloner(Elem, true, true);
    Elem.parentElement.insertAdjacentElement("beforeend", newElem);
  };

  //app installation Prompt
  let deferredPrompt;
  //const addBtn = document.querySelector('.add-button');
  //addBtn.style.display = 'none';

  window.addEventListener("beforeinstallprompt", (e) => {
    // Prevent Chrome 67 and earlier from automatically showing the prompt
    e.preventDefault();
    // Stash the event so it can be triggered later.
    deferredPrompt = e;
    // Update UI to notify the user they can add to home screen
    //addBtn.style.display = 'block';
    var markup =
      '<h1 class="appcolor">Welcome !!!</h1><p>This Application is available for your device.</p><p class="w3-center"> INSTALL our APP and CARRY YOUR SCHOOL EVERY WHERE YOU GO</p><div class="w3-center w3-xxlarge"><i class="fas fa-globe" style="margin:0px 5px"></i> <i class=" fab fa-windows" style="margin:0px 5px"></i> <i class=" fab fa-android" style="margin:0px 5px"></i> <i class=" fab fa-apple" style="margin:0px 5px"></i></div><button class="bbwa-button tooltip" id="maininstalbtn"  tooltip="Install"><i class="mbri-sign-out"></i><span>Install Now</span></button>';
    MessageBox.Popup(markup);
    addBtn = document.getElementById("maininstalbtn");
    addBtn.addEventListener("click", (e) => {
      // hide our user interface that shows our A2HS button
      MessageBox.ClosePopup();
      // addBtn.style.display = 'none';
      // Show the prompt
      deferredPrompt.prompt();
      // Wait for the user to respond to the prompt
      deferredPrompt.userChoice.then((choiceResult) => {
        if (choiceResult.outcome === "accepted") {
          //console.log('User accepted the A2HS prompt');
        } else {
          //console.log('User dismissed the A2HS prompt');
        }
        deferredPrompt = null;
      });
    });
  });
})();

nbbwa = new bbwa("bbwa-main-1");
nbbwa.Start();
onDOMReady(() => {
  //set the color mode
  let cMode = localStorage.getItem("darkMode");
  cMode = cMode && cMode === 'false'?cMode:'true';
  Application.SetMode(cMode == "true");
  //get all banner imahes deiv
  var banners = document.getElementsByClassName("bbwa-banner");
  var blen = banners.length;

  if (blen > 0) {
    for (var b = 0; b < blen; b++) {
      let elem = banners[b];
      let realimage = elem.getAttribute("data-bg-image");

      if (realimage != null && _Trim(realimage) != "") {
        //create an image and set the src
        let crimg = new Image();

        crimg.onload = (obj) => {
          elem.style.backgroundImage = "url('" + realimage + "')";
          elem.classList.remove("unloaded");
          //console.log(realimage);
        };
        crimg.src = realimage;
      }
    }
  }

  //the start btn clc event handler
  document
    .getElementsByClassName("new-explore-btn")[0]
    .addEventListener("click", () => {
      const btn = document.getElementById("startmk").innerHTML;
      MessageBox.Popup(btn, "fas fa-user-shield", true);
    });

  document.body.addEventListener("click", (t) => {
    const side1 = _("sidebox1");
    if (side1 != null && !t.target.classList.contains("maimmenuctr"))
      side1.classList.remove("open");
  });

  //
});
