/*
     $Revision$
     $Id$

     File:          res_ruimte.js
*/

$(function() {
  /* De spinner in FcltJquery is alleen voor POST's, dus hier even onze eigen; */
  $(document).on("ajaxSend", function(event, xhr, options) {
    if (options.type.toUpperCase() === "GET" && options.url?.startsWith("res_ruimte_extern_sync.asp")) {
        options.fcltindex = Math.random().toString(36).slice(2);
        var $body = $("body");
        var overlay = setTimeout(function() {
            if (!$body.find("div.busyoverlay").length) {
                $body.prepend("<div class='busyoverlay'></div>");
            }
        }, 500);

        var spinner = setTimeout(function() {
            if (!$body.find("div.busyloading").length) {
                $body.prepend("<div class='busyloading'>" + I("fa-fclt-spinner fa-4x") + "</div>");
            }
        }, 2000);
        window.ajaxBusy[options.fcltindex] = [overlay, spinner];
    }
  }).on("ajaxComplete", function(event, xhr, options) {
    if (options.type.toUpperCase() === "GET" && options.url?.startsWith("res_ruimte_extern_sync.asp")) {
        if ("fcltindex" in options && options.fcltindex in window.ajaxBusy) {
            for (var i = 0; i < window.ajaxBusy[options.fcltindex].length; i++) {
                clearTimeout(window.ajaxBusy[options.fcltindex][i]);
            }
            delete window.ajaxBusy[options.fcltindex];
        }
        if (Object.keys(window.ajaxBusy).length === 0) { // Niets meer 'busy'
            $(".busyoverlay").remove();
            $(".busyloading").remove();
        }
    }
  });
});

function sync_outlook(key) {
  return new Promise((resolve, reject) => {
      $.when($.get("res_ruimte_extern_sync.asp?res_ruimte_key=" + key, null, FcltCallbackRefresh, "json"))
              .then((data, textStatus, jqXHR) => {
        resolve(jqXHR.status != 200); // False want we hoeven niet te refreshen, dus enablen we nu de button weer
      }).fail((response) => {
        reject("Failed GET from 'res_ruimte_extern_sync.asp' => " + response.statusText + " (" + response.status + ")");
      });
  }).catch((errmsg) => {
    console.error(errmsg);
  });
}

function qrcode(key, title) {
  var url = "../fac/fac_print_qrcode.asp?title=" + encodeURIComponent(title)
                                      + "&text=" + encodeURIComponent("/?u=res_ruimte&k=" + key);
  FcltMgr.openModalDetail(url, { titel: L("lcl_make_qrc_title2") });
}