

var MultipageFunc = {
  stepperEl: null,
  mpTarget: '[UNIQUE_STRING]',
  allowSubmission: '[ALLOW_SUBMISSION]',
  currentPageIdx: 0,
  stepper: null,
  nextBtn: null,
  prevBtn: null,
  submitBtn: null,
  formElement: null,
  totalPage: 0,
  builtInNav:true,
  hasEditor:false,
  init: function () {
    this.stepperEl = document.querySelector('.bs-stepper-[UNIQUE_STRING]');
    this.formElement = document.getElementById('formea_form_[UNIQUE_STRING]');
    this.stepper = new Stepper(this.stepperEl);
    this.nextBtn = this.formElement.querySelectorAll('[data-formea-btn-next]');
    this.prevBtn = this.formElement.querySelectorAll('[data-formea-btn-prev]');
    this.submitBtn = this.formElement.querySelectorAll('[type=submit]');
    if(Joomla.editors !== undefined && Joomla.editors !== null){
      this.hasEditor = true;
    }

    this.stepperEl.addEventListener('shown.bs-stepper', function (event) {
      this.currentPageIdx = event.detail.indexStep;
      this.determineButton();
    }.bind(this));
    if(this.builtInNav){
      var totalSubmitBtns = this.submitBtn.length;
      for (let i = 0; i < totalSubmitBtns; i++) {
        if(!this.submitBtn[i].hasAttribute('data-formea-btn-submit')){
          this.submitBtn[i].parentElement.remove();
        }
      }
      this.submitBtn = this.formElement.querySelectorAll('[type=submit]');
    }

    this.determineSubmitButton(false);
    this.determineButton();

    if (this.nextBtn !== undefined) {
      this.nextBtn.forEach(function (nextBtn) {
        nextBtn.addEventListener('click', () => {
         this.goToNext(false);
        });
      }.bind(this));
    }
    if (this.submitBtn !== undefined) {
      this.submitBtn.forEach(function (submitBtn) {
        submitBtn.setAttribute('type','button');
        submitBtn.addEventListener('click', () => {
          this.goToNext(true);
        });
      }.bind(this));
    }
    if (this.prevBtn !== undefined) {
      this.prevBtn.forEach(function (prevBtn) {
        prevBtn.addEventListener('click', () => {
          this.stepper.previous();
        });
      }.bind(this));
    }
  },

  goToNext:function(final){
    if(this.hasEditor){
      let formea_editors = this.formElement.querySelectorAll('.editor');
      formea_editors.forEach(editorWrapper =>{
        const inp = editorWrapper.querySelector('textarea');
        if(inp !== null && inp !== undefined){
          const v = Joomla.editors.instances[inp.getAttribute('id')].getValue();
          if(v !== undefined && v !== null){
            inp.value = v;
          }
        }
      });
    }
    let data = new FormData();
    let taskInput = this.formElement.querySelector('[name=task]');
    let originalTask = '';
    if(this.allowSubmission > 0){
      originalTask = taskInput.value;
      taskInput.value = 'validateform.page';
      data = new FormData(this.formElement);
    }

    if(this.allowSubmission < 1){
      taskInput = document.createElement('input');
      taskInput.type = 'hidden';
      const _formElements = this.formElement.querySelectorAll('input, textarea, select');
      _formElements.forEach(function(element) {
        data.append(element.name, element.value);
      });
      data.append('task','validateform.page')
      data.append('option','com_formea')
      data.append('fomToken',this.mpTarget);
      data.append(FormeaOption.oid,'1');
    }

    data.append('current_page', this.currentPageIdx);
    data.append('format', 'json');
    data.append('view', 'validateform');

    this.validateMultipage(data, function () {
      if(final){
        if(this.allowSubmission > 0){
          taskInput.value = originalTask;
          this.formElement.submit();
        }
      }else{
        this.stepper.next();
        if(this.allowSubmission > 0){
          taskInput.value = originalTask;
        }
      }
    }.bind(this), function (response) {
      var feedbackEl = document.querySelector('.fm_page_feedback_' + response.submission.page_id);
      if (feedbackEl !== undefined && feedbackEl !== null) {
        if (response.submission.classes.page_feedback_element.length > 0) {
          feedbackEl.classList.replace(response.submission.classes.page_feedback_element, response.submission.error_classes.page_feedback_element);
        } else {
          feedbackEl.classList.add(response.submission.error_classes.page_feedback_element);
          feedbackEl.innerHTML = response.submissionMsgs.global_error_msg;
        }
      }
      var totalElements = response.elements.length;
      for (let i = 0; i < totalElements; i++) {
        if (response.elements[i].validation_error) {
          if(response.elements[i].group_id > 0){
            var tgt;
            //grouped element fm_grouped_element_13_2
            var tgtGroup = document.querySelector('.fm_grouped_element_' + response.submission.form_id + '_' + response.elements[i].group_id);
            if(tgtGroup !== undefined && tgtGroup !== null){
              //gp_fm_3
              if(response.elements[i].group_type== 1){
                tgt = tgtGroup.querySelector('.gp_fm_'+response.elements[i].group_id);
              }else{
                tgt = tgtGroup.querySelector('.fm_element_' + response.submission.form_id + '_' + response.elements[i].element_id);
              }
            }
          }else{
             tgt = document.querySelector('.fm_element_' + response.submission.form_id + '_' + response.elements[i].element_id);
          }

          if (tgt !== undefined && tgt !== null) {
            tgt.classList.add('has-error');
            var containerErrorClass = response.elements[i].error_classes.element_container;
            var containerClass = response.elements[i].classes.element_container;
            if (containerErrorClass.length > 0) {
              if (containerClass.length > 0) {
                tgt.classList.replace(containerClass, containerErrorClass);
              } else {
                tgt.classList.add(containerErrorClass);
              }
            }
            var tgtInput;
            if(response.elements[i].group_id > 0){
              var _selector = '[name^="formea[group_'+this.mpTarget+']['+response.elements[i].group_id+']['+response.elements[i].setIndex+'][' + response.elements[i].alias + '"]';
               tgtInput = tgt.querySelectorAll(_selector);
            }else{
               tgtInput = tgt.querySelectorAll('[name^="formea[' + response.elements[i].alias + '"]');
            }

            if(tgtInput !== undefined && tgtInput !== null){
              var inputErrorClass = response.elements[i].error_classes.input;
              var inputClass = response.elements[i].classes.input;
              var totalTgtInputs = tgtInput.length;
              if (inputErrorClass.length > 0) {
                for (let j = 0; j < totalTgtInputs; j++) {
                  tgtInput[j].classList.add(inputErrorClass);
                  tgtInput[j].classList.remove(inputClass);
                }
              }


              var elementFeedback = tgt.getElementsByClassName('fm_feedback_el');

              var errorMsgs = [];
              var totalValidation = response.elements[i].validation_result.result.length;
              for (let j = 0; j < totalValidation; j++) {
                if(response.elements[i].validation_result.result[j].result.result.msg.length > 0){
                  errorMsgs.push(response.elements[i].validation_result.result[j].result.result.msg);
                }
              }
              if (elementFeedback !== undefined && elementFeedback !== null) {
                var targetFeedback = elementFeedback.length - 1 ;


                var elementFeedBackErrorClass = response.elements[i].error_classes.feedback_container;
                var elementFeedBackClass = response.elements[i].classes.feedback_container;
                if (elementFeedBackErrorClass.length > 0) {
                  elementFeedback[targetFeedback].classList.add(elementFeedBackErrorClass);
                }
                if (elementFeedBackClass.length > 0) {
                  elementFeedback[targetFeedback].classList.remove(elementFeedBackClass);
                }
                elementFeedback[targetFeedback].innerHTML = errorMsgs.join('<br/>');
              }
            }
          }
        }
        //fm_element_3_1
      }
    }.bind(this));
  },

  determineButton: function () {
    if (this.currentPageIdx === 0) {
      if (this.prevBtn !== undefined) {
        this.prevBtn.forEach(function (prevBtn) {
          prevBtn.style.display = 'none';
        }.bind(this));
      }
      this.determineSubmitButton(false);
    } else {
      if (this.currentPageIdx === (this.totalPage - 1)) {
        /*last page*/
        this.determineSubmitButton(true);
      }else{
        this.determineSubmitButton(false);
      }
      if (this.prevBtn !== undefined) {
        this.prevBtn.forEach(function (prevBtn) {
          prevBtn.style.display = '';
        }.bind(this));
      }
    }
  },

  determineSubmitButton: function (show) {
    if (this.submitBtn !== undefined) {
      this.submitBtn.forEach(function (submitBtn) {
        if(show){
          submitBtn.style.display = '';
        }else{
          submitBtn.style.display = 'none';
        }
      }.bind(this));
    }
    if(this.nextBtn !== undefined){
      this.nextBtn.forEach(function (nextBtn) {
        if(show){
          nextBtn.style.display = 'none';
        }else{
          nextBtn.style.display = '';
        }
      }.bind(this));
    }
  },

  validateMultipage: function (fd, fn = null, validationFailedFn = null) {
    const hostUrl = window.location.origin;
    fetch(hostUrl, {
      method: 'POST',
      body: fd
    })
      .then(response => {
        return response.json();
      })
      .then(data => {
        if (data.success) {
          if (fn !== undefined && fn !== null) {
            fn();
          }
        } else {
          if (validationFailedFn !== undefined && validationFailedFn !== null) {
            validationFailedFn(data.data);
          }
        }
      })
      .catch(error => console.error(error));
  }
};
