if (typeof STRB_DEBUG === "undefined") var STRB_DEBUG = false;
(function ($) {
  "use strict";
  /**
   * Set the Cookie
   *
   * @param name string cookie name
   * @param value string cookie value
   * @return void
   */
  $.strb_setCookie = function (name, value) {
    value = value.toString().replace(new RegExp("\\\\", "g"), "");

    document.cookie =
      name +
      "=" +
      encodeURIComponent(value) +
      "; expires=" +
      60 * 24 +
      "; path=/";
  };

  /**
   * Get the Cookie
   *
   * @param name string cookie name
   * @return void
   */
  $.strb_getCookie = function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == " ") c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0)
        return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
  };

  $.strb_getHashParam = function (key) {
    var urlparts = location.href.split("#");

    if (urlparts.length >= 2) {
      urlparts.shift();
      var queryString = urlparts.join("#"); //join it back up
      var results = new RegExp("[\\?&#]*" + key + "=([^&#]*)").exec(
        queryString
      );
      if (results) {
        return results[1] || 0;
      }
    }

    return false;
  };

  $.strb_setHashParam = function (key, val) {
    var urlparts = location.href.split("#");

    if (urlparts.length >= 2) {
      var add = true;
      var urlBase = urlparts.shift(); //get first part, and remove from array
      var queryString = urlparts.join("#"); //join it back up

      var prefix = encodeURIComponent(key) + "=";
      var pars = queryString.split(/[&;]/g);
      for (var i = pars.length; i-- > 0; ) {
        //reverse iteration as may be destructive
        if (pars[i].lastIndexOf(prefix, 0) !== -1 || pars[i] === "") {
          pars[i] = pars[i].replace(pars[i], prefix + val);
          add = false;
          break;
        }
      }

      add && pars.push(prefix + val);

      location.href = urlBase + "#" + pars.join("&");
    } else {
      location.href += "#" + key + "=" + val;
    }
  };

  $.strb_getParam = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
      sURLVariables = sPageURL.split("&"),
      sParameterName,
      i;

    for (i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split("=");

      if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined
          ? true
          : decodeURIComponent(sParameterName[1]);
      }
    }

    return false;
  };

  /**
   * Load google chart
   * @param div
   */
  $.strb_loadChart = function (div) {
    new Chart(div, {
      type: "bar",
      data: {
        labels: ["", "", "", "", "", "", ""],
        datasets: [
          {
            data: div.data("values").split(","),
            borderWidth: 0,
          },
        ],
      },
      options: {
        tooltips: { enabled: false },
        legend: { display: false },
        layout: {
          padding: {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
          },
        },
        title: { display: false },
        scales: {
          yAxes: [
            {
              display: false,
              ticks: {
                beginAtZero: true,
                min: 0,
                max: 1,
              },
            },
          ],
          xAxes: [
            {
              display: false,
              ticks: { beginAtZero: true },
            },
          ],
        },
      },
    });
  };

  $.strb_showMessage = function (text, time) {
    $(".strb_alert").remove();
    if (text.indexOf("<div>") == -1) {
      text = $(
        '<div class="strb_alert position-fixed fixed-top text-center text-white bg-success m-0 p-3 border border-white sq-position-fixed sq-fixed-top sq-text-center sq-text-white sq-bg-success sq-m-0 sq-p-4 sq-border sq-border-white">' +
          text +
          "</div>"
      );
    }
    $("body").prepend(text);

    if (typeof time === "undefined") {
      time = 2000;
    }

    setTimeout(function () {
      text.remove();
    }, time);

    return text;
  };

  /**
   * Add keyword to briefcase
   * @param keyword
   */
  $.fn.strb_addBriefcase = function () {
    var $this = this;

    $this.addClass("strb_minloading");
    $.post(sqQuery.ajaxurl, {
      action: "strb_briefcase_addkeyword",
      keyword: $this.data("keyword"),
      doserp: parseInt($this.data("doserp")),
      hidden: parseInt($this.data("hidden")),
      strb_nonce: sqQuery.nonce,
    })
      .done(function (response) {
        $this.removeClass("strb_minloading");
        if (typeof response.message !== "undefined") {
          $.strb_showMessage(response.message).addClass("strb_success");

          $this.closest("tr").addClass("bg-briefcase");
          $this.closest("tr").find(".strb_research_add_briefcase").hide();
        } else if (typeof response.error !== "undefined") {
          $.strb_showMessage(response.error);
          $this.removeClass("strb_minloading");
        } else {
          $this.removeClass("strb_minloading");
          location.reload();
        }
      })
      .fail(function () {
        $this.removeClass("strb_minloading");
      });
  };

  /**
   * Listen if the call is made as ajax
   * @param obj
   */
  $.fn.strb_ajaxCallListen = function () {
    var $this = this;

    //Set params
    var $input = $("#" + $this.data("input"));
    var $confirm = $this.data("confirm");
    var $action = $this.data("action");
    var $redirect = $this.data("redirect");
    var $javascript = $this.data("javascript");
    var $name = $this.data("name");
    var $value = $this.data("value");

    //if the input doesn't exist
    if (!$input.length) {
      $input = $this; //set the current object as input
    }
    if (typeof $confirm !== "undefined") {
      if (!confirm($confirm)) return;
    }

    if ($input.is("input") && $input.attr("type") === "checkbox") {
      if ($input.is(":checked")) {
        $value = $input.val();
      }
    } else {
      if ($input.is("select")) {
        $value = $input.find("option:selected").val();
      } else {
        if ($input.is("input") && $input.val() !== "") {
          $value = $input.val();
        }
      }
    }

    $this.addClass("strb_minloading");

    if ($action !== "" && $value !== "") {
      return $.post(sqQuery.ajaxurl, {
        action: $action,
        input: $name,
        value: $value,
        referal: location.href,
        strb_nonce: sqQuery.nonce,
      })
        .done(function (response) {
          if (typeof response.data !== "undefined") {
            if (response.data === "") {
              $("#wpbody-content").prepend("Saved");
            } else {
              $("#wpbody-content").prepend(response.data);
            }

            //Add the assistant in the right side
            if (response.assistant !== "" && response.assistant_dest) {
              var show_url = $(".strb_assistant").find("ul:visible").attr("id");
              $(response.assistant_dest).html(response.assistant);
              if (show_url) $("#" + show_url).show();
            }

            setTimeout(function () {
              $this.removeClass("strb_minloading");

              if (typeof $javascript !== "undefined") {
                eval($javascript);
              } else if (typeof $redirect !== "undefined") {
                window.open($redirect, "_blank");
              } else {
                location.reload();
              }
            }, 1000);
          } else if (typeof response.error !== "undefined") {
            $.strb_showMessage(response.error);
            $this.removeClass("strb_minloading");
          } else {
            $this.removeClass("strb_minloading");
            location.reload();
          }
        })
        .fail(function () {
          $this.removeClass("strb_minloading");
        }, "json");
    }
  };

  /**
   * Get the User Account Info
   */
  $.fn.strb_getAccount = function () {
    var $this = this;

    $this.addClass("strb_minloading");

    $.post(sqQuery.ajaxurl, {
      action: "strb_ajax_account_getaccount",
      strb_nonce: sqQuery.nonce,
    })
      .done(function (response) {
        if (typeof response !== "undefined") {
          if (typeof response.html !== "undefined") {
            $this.html(response.html);

            $this.find(".strb_account_info_avatar").on("click", function () {
              $this.find(".strb_account_info_content").toggle();
            });
          }
        }

        $this.removeClass("strb_minloading");
      })
      .fail(function () {
        $this.removeClass("strb_minloading");
      }, "json");
  };

  $.fn.strb_clearCache = function () {
    $.post(sqQuery.ajaxurl, {
      action: "strb_seosettings_clear_cache",
      strb_nonce: sqQuery.nonce,
    });
  };

  //Add the Listener for Settings
  $.fn.hmwp_subMenuListen = function () {
    //set $this as #hmwp_wrap
    var $this = this;
    //init settings as saved
    var unsaved = false;

    //listen the SubMenu click
    $this.find(".strb_sub_nav_item").on("click", function (ev) {
      ev.preventDefault();

      $this.find(".tab-panel").hide();
      if ($this.find("#" + $(this).data("tab")).length > 0) {
        $this.find("#" + $(this).data("tab")).show();
        $this.find("." + $(this).data("tab")).show();
        $.strb_setHashParam("tab", $(this).data("tab"));
      }
      $this.find(".strb_sub_nav_item").removeClass("active");
      $this
        .find(".strb_sub_nav_item[data-tab=" + $(this).data("tab") + "]")
        .addClass("active");
    });

    if ($.strb_getHashParam("tab")) {
      var $current = $.strb_getHashParam("tab");

      $this.find(".tab-panel").hide();
      $this.find(".strb_sub_nav_item").removeClass("active");
      $this.find("#" + $current).show();
      $this.find("." + $current).show();
      $this
        .find(".strb_sub_nav_item[data-tab=" + $current + "]")
        .addClass("active");
    } else {
      $this.find("a.hmwp_nav_item:first").addClass("active");
      $this.find("a.hmwp_nav_item:first").trigger("click");
    }

    //Open suboptions for an option if exists
    $this
      .find("input.sq-switch")
      .not(".nopopup")
      .change(function () {
        if ($("div." + $(this).attr("name")).length) {
          if ($(this).prop("checked")) {
            $("div." + $(this).attr("name")).show();
          } else {
            $("div." + $(this).attr("name")).hide();
          }
        }
      });

    $this.find("input.sq-switch").each(function () {
      if (!$(this).prop("checked")) {
        if ($("div." + $(this).attr("name")).length) {
          $("div." + $(this).attr("name")).hide();
        }
      }
    });
  };

  $(document).ready(function () {
    //SQ_DEBUG && console.log("strb_GlobalInit");

    //Get the account info in the account div
    if ($(".strb_account_info").length > 0) {
      $(".strb_account_info").strb_getAccount();
    }

    //Listen the Submenu
    $("#strb_wrap").hmwp_subMenuListen();

    //listen the Ajax Calls input fields
    if ($(".strb_save_ajax").length > 0) {
      $(".strb_save_ajax")
        .find("input")
        .on("change", function () {
          $(this).strb_ajaxCallListen();
        });
      $(".strb_save_ajax")
        .find("input[type=image]")
        .on("click", function () {
          $(this).strb_ajaxCallListen();
        });
      $(".strb_save_ajax")
        .find("button")
        .on("click", function () {
          $(this).strb_ajaxCallListen();
        });
    }

    //listen the hide show advanced options button
    $("button.show_advanced").on("click", function () {
      $(".strb_advanced").show();

      $("button.show_advanced").hide();
      $("button.hide_advanced").show();
    });
    $("button.hide_advanced").on("click", function () {
      $(".strb_advanced").hide();

      $("button.hide_advanced").hide();
      $("button.show_advanced").show();
    });

    $("button[type=submit]")
      .not(".noloading")
      .on("click", function () {
        $(this).addClass("strb_minloading");
      });

    $("form#strb_register").on("submit", function () {
      $(this).find("button[type=submit]").addClass("strb_minloading");
    });
  });
})(jQuery);
