var endLength =
  window.location.href.indexOf("#") != -1
    ? window.location.href.indexOf("#")
    : window.location.href.length;
history.replaceState(
  {},
  document.title,
  window.location.href.substr(0, endLength) +
    "#" +
    $("#form-register .ftr-steps__step:first-of-type").attr("id")
);
$("#password").strength({ type: "app" });

var info = $("#login-message-info").data("info");

if (info.success != "") {
  notificationMsg(info.success, "success");
}
if (info.error != "") {
  notificationMsg(info.error, "warning");
}

function datePickerInit(id) {
  var hideDatePicker = function() {
    $("#mddtp-picker__date").addClass("mddtp-picker--inactive");
    $(".ftr-main").removeClass("overlay");
  };

  datePicker.trigger = document.getElementById(id);
  document.getElementById(id).addEventListener("click", function() {
    datePicker.show();
    $(".ftr-main").addClass("overlay");
    // datePicker._switchToDateView(datePicker._sDialog.years, datePicker); // inicia com a escolha do ano
    onClickOut(
      $("#mddtp-picker__date"),
      null,
      hideDatePicker,
      null,
      true,
      true
    );
  });
  document.getElementById(id).addEventListener("onOk", function() {
    $(this)
      .find(".ftr-js-field__entry")
      .val(datePicker.time.format("DD/MM/YYYY"))
      .addClass("on");
    $(this)
      .find("input[type=hidden]")
      .val(datePicker.time.format("DD/MM/YYYY"));
    $(".ftr-main").removeClass("overlay");
  });
}

moment.locale('pt-BR');

if ($("#data_nascimento").length > 0) {
  var datePicker = new mdDateTimePicker.default({
    type: "date",
    init: moment(),
    orientation: "PORTRAIT",
    future: moment(),
    past: moment().subtract(150, "years"),
    autoClose: true
  });
  datePickerInit("data_nascimento");
}

//=========================== Formulário de registro ===========================
if (
  $("#form-register .ftr-field__error, #form-register .ftr-check-label__error")
    .length > 0
) {
  var varLeft = $(
    "#form-register .ftr-field__error, #form-register .ftr-check-label__error"
  )
    .closest(".ftr-steps__step")
    .offset().left;
  $("#form-register").css({ left: "-" + varLeft + "px" });
}

function exibeContent() {
  $(
    ".ftr-js-pessoa-" +
      $("#juridica, #fisica")
        .filter(":checked")
        .attr("id")
  )
    .prop("disable", false)
    .show();
  $(
    ".ftr-js-pessoa-" +
      $("#juridica, #fisica")
        .filter(":not(:checked)")
        .attr("id")
  )
    .hide()
    .find("#cpf, #rg, #cnpj, #razao_social, #inscricao_estadual")
    .prop("disable", true)
    .val("");
}

exibeContent();
$("#juridica, #fisica").on("change", function() {
  exibeContent();
});

$("#form-register").validate({
  ignore: ":hidden:not(.ftr-js-select__value, .ftr-check, .ftr-radio)",
  onkeyup: function(element) {
    if ($(element).valid()) {
      $(element)
        .closest("div[class|=ftr], label[class|=ftr]")
        .removeClass("error");
      $(element)
        .siblings(".ftr-field__error")
        .remove();
    }
  },
  onsubmit: true,
  showErrors: function(errorMap, errorList) {
    $.each(errorList, function() {
      var $fieldError = $($(this)[0].element);

      if ($fieldError.hasClass("ftr-check")) {
        $fieldError
          .next(".ftr-check-label")
          .find(".ftr-check-label__error")
          .remove();
        $fieldError.next(".ftr-check-label").append(
          $("<span>")
            .addClass("ftr-check-label__error")
            .text($(this)[0].message)
        );
        $fieldError.one("click", function() {
          $(this)
            .next(".ftr-check-label")
            .find(".ftr-check-label__error")
            .remove();
        });
      } else if ($fieldError.hasClass("ftr-radio")) {
        $fieldError
          .closest(
            "div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]"
          )
          .find(".ftr-radio-label__error")
          .remove();
        $fieldError
          .closest(
            "div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]"
          )
          .prepend(
            $("<span>")
              .addClass("ftr-radio-label__error")
              .attr("style", "position:relative;margin-top:0")
              .text($(this)[0].message)
          );
        $fieldError.one("click", function() {
          $(this)
            .closest(
              "div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]"
            )
            .find(".ftr-radio-label__error")
            .remove();
        });
      } else {
        $fieldError
          .closest(
            "div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]"
          )
          .addClass("error")
          .find(".ftr-field__error")
          .remove();
        $fieldError
          .closest(
            "div[class^=ftr], label[class^=ftr], div[class*=ftr], label[class*=ftr]"
          )
          .append(
            $("<span>")
              .addClass("ftr-field__error")
              .text($(this)[0].message)
          );
      }
    });
  },
  rules: {
    celular: {
      celular: true
    },
    cpf: {
      cpfBR: true
    },
    cnpj: {
      cnpj: true
    },
    postcode: {
      postalcodeBR: true
    },
    confirm: {
      equalTo: "#password"
    },
    email: {
      checkemail: true
    }
  },
  messages: {
    confirm: {
      equalTo: "As senhas não conferem."
    }
  }
});

$("#form-register .ftr-steps__step").each(function(index) {
  if ($(this).find('.ftr-steps__button').length === 0) {
    var p = $("<p>"),
      button = $("<button>"),
      container = $("<div>");

    p.text(
      "Etapa " +
        (index + 1) +
        " de " +
        $("#form-register .ftr-steps__step").length
    );
    p.addClass("ftr-text--grey ftr-text--xs ftr-text--center ftr-in-space--m");
    button.attr("type", "button");
    button.addClass(
      "ftr-steps__button ftr-btn ftr-background--primary ftr-js-ripple-effect ftr-h--full"
    );
    button.text("Próxima etapa");
    container.append(p, button);

    $(this).find(".ftr-steps__content").append(container);
  }
});

var prevLocation = window.location.href;
window.displayStep = function($step) {
  $("#form-register.ftr-steps").css({
    left: "-" + $step.prevAll(".ftr-steps__step").length * 100 + "vw"
  });
};

$("#form-register .ftr-steps__step:last-child .ftr-steps__button")
  .attr("type", "submit")
  .text("Concluir");
$("#form-register .ftr-steps__button[type=button]").on("click", function() {
  $(".g-recaptcha-bubble-arrow")
    .parent()
    .css({
      transform: "scale(.8)",
      "-webkit-transform": "scale(.8)",
      "transform-origin": "0 0",
      "-webkit-transform-origin": "0 0"
    });

  if (
    $(this)
      .closest(".ftr-steps__step")
      .find("input")
      .valid()
  ) {
    var $step = $(this)
      .closest(".ftr-steps__step")
      .next(".ftr-steps__step");
    var endLength =
      window.location.href.indexOf("#") != -1
        ? window.location.href.indexOf("#")
        : window.location.href.length;
    history.pushState(
      {},
      document.title,
      window.location.href.substr(0, endLength) + "#" + $step.attr("id")
    );
    displayStep($step);
  } else {
    var topValue =
      document.querySelector(".error").offsetTop - $(window).height() / 2 + 36;
    $("#form-register .ftr-steps__content").animate(
      { scrollTop: topValue },
      300
    );
    notificationMsg(
      "Alguns campos não foram preenchidos de forma correta, corrija antes de prosseguir!",
      "error"
    );
  }
});

$("#form-register input").keypress(function(e) {
  var code = null;
  code = e.keyCode ? e.keyCode : e.which;
  return code == 13 ? false : true;
});

$(".ftr-js-privacy-policy").one("click", function(event) {
  event.preventDefault();
  $(".ftr-loading-bar").removeClass("ftr-none");
  $.ajax({
    url: $(this).attr("href"),
    dataType: "html"
  })
    .done(function(data) {
      $(".ftr-js-privacy-policy-container").append(data);
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      $(".ftr-loading-bar").addClass("ftr-none");
    });
});
$("#address_1, #city").on("focus", function() {
  $("#error-postcode-search")
    .closest(".ftr-field")
    .removeClass("error");
  $("#error-postcode-search").remove();
});

const checkWhatsStatus = document.getElementById("feedback_whatsapp_status"),
  inputWhatsNumber = document.getElementById("feedback_whatsapp_number");

if (checkWhatsStatus && inputWhatsNumber) {
  checkWhatsStatus.addEventListener("change", function() {
    if (this.checked) {
      inputWhatsNumber.required = true;
    } else {
      inputWhatsNumber.required = false;
      inputWhatsNumber.dispatchEvent(new Event("keyup", { bubbles: true }));
    }
  });
}
