global.gfiWebforms = (function () {
  return {
    goTo: function () {
      $("#captchaimg").click(function () {
        initCaptcha();
        return false;
      });
      this.initDatepicker();
      this.initCaptcha();

      // FeedbackForm
      var relatedContentId = $("#feedbackRelatedId").data("related-id");
      if (relatedContentId !== undefined) {
        $('input[name="relatedDocumentId"]').val(relatedContentId);
      }


      // this.removeMyWebformsDetailText();

      var keepAliveUrl = $(".mwf-form").data("keepalive-url");
      if (keepAliveUrl !== undefined) {
        setInterval(function () {
          $.ajax({url: keepAliveUrl})
        }, 120000); // 2 Minuten
      }
      var errorMessageDiv = $('.mwf-error');
      if (errorMessageDiv.length > 0) {
        $('html, body').animate({scrollTop: $('.mwf-error').first().offset().top - 200}, 1000);
        errorMessageDiv.parent().find("input").addClass("mwf-error-input");
      }

      $("input.mwf-error-input").change(function () {
        var currentElement = $(this);
        currentElement.removeClass("mwf-error-input");
        if (currentElement.hasClass("mwf-checkbox") || currentElement.hasClass("mwf-radio")) {
          currentElement.parents("fieldset").find("input").removeClass("mwf-error-input");
        }
      });

      $("a[title='externer Link']").addClass("extern");
    },

    initCaptcha: function () {
      var self = gfiWebforms;
      self.refreshCaptcha("-barrier-free");
      self.refreshCaptcha("");

      $("#refresh-captcha").click(function () {
        self.refreshCaptcha("");
        return false;
      });

      $("#refresh-captcha-barrier-free").click(function () {
        self.refreshCaptcha("-barrier-free");
        return false;
      });

      $('#tabs > ul a').on('click', function (e) {
        e.preventDefault();
        const a = $(this);
        a.parent('li').addClass('active').siblings().removeClass('active');
        $(a.attr('href')).addClass('active').siblings('.active').removeClass('active');
        if (a.text() === "Zeichencode") {
          $('#captchaSolution').prop('title', 'Beliebiger Text');
          $('#captchaSolution').prop('pattern', '.*');
          $('#captchaId').val($('#captchaId-img').val());
        } else if (a.text() === "Rechenaufgabe") {
          $('#captchaSolution').prop('title', 'Bitte nur Ziffern eingeben');
          $('#captchaSolution').prop('pattern', '[0-9][0-9]*');
          $('#captchaId').val($('#captchaId-calc').val());
        }
      }).first().trigger('click');


      /**
       * IHK-4797: Captcha-Probleme - falls der Inhalt von captchaId und captchaId-img (bzw. captchaId-calc)
       *   aus irgendwelchen Gruenden nicht uebereinstimmen sollte, wird captchaId korrigiert.
       *   (Das geschieht z.B wenn man den Back-Button drueckt)
       */
      $('#rw-security').submit(function () {
        let valmain = $("#captchaId").val();
        const valimg = $("#captchaId-img").val();
        const visimg = $("#tabs-1");
        const valcalc = $("#captchaId-calc").val();
        const viscalc = $("#tabs-2");

        if ((visimg.css("visibility") !== "hidden") && (valimg !== valmain)) {
          $("#captchaId").val(valimg);
        } else if ((viscalc.css("visibility") !== "hidden") && (valcalc !== valmain)) {
          $("#captchaId").val(valcalc);
        }
        return true;
      });

      /*
      $("#tabs").tabs();
      $(".ui-tabs-anchor").click(function () {
        var hiddenCaptchaId = $("#captchaId");
        var captchaId = "";
        if ($(this).text() === "Zeichencode") {
          captchaId = $("#captchaId-img").attr("value");
          $('#captchaSolution').prop('title', 'Beliebiger Text');
          $('#captchaSolution').prop('pattern', '.*');
        } else {
          captchaId = $("#captchaId-calc").attr("value");
          $('#captchaSolution').prop('title', 'Bitte nur Ziffern eingeben');
          $('#captchaSolution').prop('pattern', '[0-9][0-9]*');
        }
        hiddenCaptchaId.attr('value', captchaId);
      });
      */
    },

    refreshCaptcha: function (barrierFree) {
      var self = gfiWebforms;
      var hiddenCaptchaId = $("#captchaId");
      var captchaIdField = $("#captchaId-img");
      var jsonCaptchaSrc = hiddenCaptchaId.data("captcha-url");

      if (jsonCaptchaSrc !== undefined) {
        if (barrierFree == "-barrier-free") {
          captchaIdField = $("#captchaId-calc");
          jsonCaptchaSrc += "&barrierFree=true";
        }

        $.ajax(
          {
            url: jsonCaptchaSrc,
            type: 'get',
            dataType: "json",
            xhrFields: {withCredentials: true}
          }
        ).done(function (data) {
          hiddenCaptchaId.attr('value', data.id);
          captchaIdField.attr('value', data.id);
          self.showCaptcha(data, barrierFree);
        });
        // $.getJSON(jsonCaptchaSrc, function(data) {
        //   hiddenCaptchaId.attr('value', data.id);
        //   captchaIdField.attr('value', data.id);
        //   self.showCaptcha(data, barrierFree);
        // });
      }
    },

    showCaptcha: function (data, barrierFree) {
      if (barrierFree === "") {
        $("#captcha-code").attr('src', 'data:image/jpg;base64,' + data.challenge).attr('alt', 'Geben sie die im Bild dargestellte Zeichenfolge in das ein');
      } else {
        $("#captcha-code-barrier-free").html(data.challenge);//.attr('alt', 'Lösen Sie die im Bild gestellte Rechenaufgabe und geben Sie die Lösung in Zahlen ein');
      }
    },


    removeMyWebformsDetailText: function () {

      var detailText = $("#webformsDetailText");
      if (detailText === null) {
        return;
      }

      $("#webformsDetailText").show();

      var pageCounter = $("#webformsPageCounter");
      if (pageCounter === null) {
        return;
      }

      var currentPage = pageCounter.data("page-number");
      if (currentPage !== undefined && currentPage < 2) {
        return;
      }

      $("#webformsDetailText").hide();
      $(".anchorlinks").hide();
      $(".text.initial").hide();
      $(window).scrollTop(0);
    },

    initDatepicker: function () {
      [].forEach.call(document.querySelectorAll('[data-format-datepicker]'), function (datepickerElement) {
        var self = gfiWebforms;
        var dateOptions = datepickerElement.dataset.formatDatepicker;
        var minDateVal = datepickerElement.dataset.mindateDatepicker;
        var maxDateVal = datepickerElement.dataset.maxdateDatepicker;

        if (dateOptions === "keine Auswahl") {
          self.validDateValues(datepickerElement, 'dd.mm.yy', minDateVal, maxDateVal);
        }
        if (dateOptions === "dd.MM.yyyy") {
          self.validDateValues(datepickerElement, 'dd.mm.yy', minDateVal, maxDateVal);
        }
        if (dateOptions === "yyyy-MM-dd") {
          self.validDateValues(datepickerElement, 'yy-mm-dd', minDateVal, maxDateVal);
        }
        if (dateOptions === "MM/dd/yy") {
          self.validDateValues(datepickerElement, 'mm/dd/y', minDateVal, maxDateVal);
        }
      });
    },

    validDateValues: function (datepickerElementVal, dateFormatVal, minDateVal, maxDateVal) {
      if ((minDateVal === undefined) && (maxDateVal === undefined)) {
        $(datepickerElementVal).datepicker({dateFormat: dateFormatVal, changeYear: true, changeMonth: true});
      }

      if ((minDateVal !== undefined) && (maxDateVal === undefined)) {
        $(datepickerElementVal).datepicker({
          dateFormat: dateFormatVal,
          minDate: new Date(minDateVal),
          changeYear: true,
          changeMonth: true
        });
      }

      if ((minDateVal === undefined) && (maxDateVal !== undefined)) {
        $(datepickerElementVal).datepicker({
          dateFormat: dateFormatVal,
          maxDate: new Date(maxDateVal),
          changeYear: true,
          changeMonth: true
        });
      }

      if ((minDateVal !== undefined) && (maxDateVal !== undefined)) {
        $(datepickerElementVal).datepicker({
          dateFormat: dateFormatVal,
          minDate: new Date(minDateVal),
          maxDate: new Date(maxDateVal),
          changeYear: true,
          changeMonth: true
        });
      }
    }

  }
})();

