/**
 * Wdes backend menu extension
 *
 * @author WHMCSDES
 */

(function ($, w) {
  "use strict";

  var WdesMegaMenu = function () {
    this.navMenuList = w.wpNavMenu.menuList;

    this.iconPicker();

    this.updataitems();
    this.navMenuList.on("sortstop", this.update.bind(this));

    var superRegisterChange = wpNavMenu.addItemToMenu,
        that = this;
    wpNavMenu.addItemToMenu = function (menuItem, procesMethod, callback) {
      if (callback) {
        var _callback = callback;
        callback = function () {
          _callback();
          that.updataitems(true);
        };
      }

      that.updataitems();
      return superRegisterChange.call(this, menuItem, procesMethod, callback);
    };
  };

  //initialize
  var instance;
  WdesMegaMenu.init = function () {
    if (instance) {
      return instance;
    } else {
      return (instance = new WdesMegaMenu());
    }
  };

  var proto = WdesMegaMenu.prototype;

  proto.updataitems = function (newItems) {
    this.navMenuList.find(".menu-item").each(
        function (index, item) {
          var $item = $(item);
          if (newItems) {
            if (!$item.data("notNew")) {
              this.menuitem.apply(this, arguments);
              this.iconPickerInit(item);
              $item.data("notNew", true);
            }
          } else {
            this.iconPickerInit(item);
            this.menuitem.apply(this, arguments);
          }
        }.bind(this)
    );
  };

  proto.update = function (event, data) {
    var $item = data.item;
    setTimeout(
        function () {
          this.menuitem(0, $item, true);
        }.bind(this),
        10
    );
  };

  proto.menuitem = function (index, item, checkChildren, values) {
    var $item = $(item),
        depth,
        parentType;

    depth = parseInt($item[0].className.match(/-depth-(\d+)/)[1]);

    if (depth > 0) {
      parentType = $item
          .prevAll(".menu-item-depth-" + (depth - 1))
          .first()
          .data("type");
    }

    $item
        .find("p[class*=wdes-mega-setting]")
        .each(this.checkOption.bind(this, depth));

    $item.find(".wdes-mega-setting-mega_widgets").css("display", "none");
    $item.find(".wdes-mega-setting-sec_text").css("display", "none");

    $item.data("type", "classic");

    switch (depth) {
      case 0:
        var $megaCheckbox = $item.find(
                '.wdes-mega-setting-mega  input[type="checkbox"]'
            ),
            $megaType = $item.find(".wdes-mega-setting-mega_type  select");

        if ($megaCheckbox.length) {
          if (!$megaCheckbox.data("eventAdded")) {
            $megaCheckbox
                .on(
                    "change",
                    function () {
                      this.menuitem(0, $item, true);
                    }.bind(this)
                )
                .data("eventAdded", true);
          }

          if ($megaType.length) {
            values = $megaType[0].value;
            if (!$megaType.data("eventAdded")) {
              $megaType
                  .on(
                      "change",
                      function () {
                        this.menuitem(0, $item, true, $megaType[0].value);
                      }.bind(this)
                  )
                  .data("eventAdded", true);
            }
          }

          if ($megaCheckbox[0].checked) {
            $item.find(".wdes-mega-setting-mega_type").css("display", "");
            $item.find(".wdes-mega-setting-col_num").css("display", "none");
            $item
                .find(".wdes-mega-setting-mega_template")
                .css("display", "none");
            $item.data("type", "mega");

            if (values === "template") {
              $item.find(".wdes-mega-setting-mega_template").css("display", "");
              $item.find(".wdes-mega-setting-col_num").css("display", "none");
              $item.data("type", "template");
            } else if (values === "with_widget") {
              $item.find(".wdes-mega-setting-col_num").css("display", "");
              $item
                  .find(".wdes-mega-setting-mega_template")
                  .css("display", "none");
              $item.data("type", "widget");
            } else {
              $item.find(".wdes-mega-setting-col_num").css("display", "");
              $item
                  .find(".wdes-mega-setting-mega_template")
                  .css("display", "none");
            }
          } else {
            $item.find(".wdes-mega-setting-mega_type").css("display", "none");
            $item.find(".wdes-mega-setting-col_num").css("display", "none");
            $item
                .find(".wdes-mega-setting-mega_template")
                .css("display", "none");
          }
        }
        break;
      case 1:
        if (parentType === "widget") {
          $item.find(".wdes-mega-setting-mega_widgets").css("display", "");
        }

        if (parentType === "mega") {
          $item.find(".wdes-mega-setting-sec_text").css("display", "");
        }
        break;
    }

    if (checkChildren) {
      $.each($item.childMenuItems(), this.menuitem.bind(this));
    }

    menu_color_picker(item);
  };

  proto.checkOption = function (depth, index, options) {
    var $option = $(options),
        minDepth = $option.data("depth").min,
        maxDepth = $option.data("depth").max;
    $option.css(
        "display",
        depth <= maxDepth && depth >= minDepth ? "" : "none"
    );
  };

  proto.iconPickerInit = function (target) {

    window.activeIconInputID = '';

    $(target).find( "> .menu-item-settings > .wdes-mega-setting-icon > label > .wdes-iconpicker-input").on('click', function (e){
      let inputOffset = $(this).offset(),
          top  = parseInt(inputOffset.top) + 20,
          left = parseInt(inputOffset.left);

      $('#wdes-menu-iconpicker').css('display', 'block');
      $('#wdes-menu-iconpicker').css('top', top);
      $('#wdes-menu-iconpicker').css('left', left);
      $('#wdes-menu-iconpicker').css('z-index', 999);

      window.activeIconInputID = $(this).attr('id');

    });

  };

  proto.iconPicker = function (){

    $('#wdes-menu-iconpicker a').on('click', function (){

      let IconInputID = "#" + window.activeIconInputID,
          iconName =$(this).attr('title');

      $(IconInputID).val(iconName);

      $("label[for='"+window.activeIconInputID+"']").find('i').attr('class', iconName);

      $('#wdes-menu-iconpicker').css('display', 'none');

      resetSearch();

    });

    //Filter
    $("#wdes-iconpicker-search").on("keyup", function() {
      var value = $(this).val().toLowerCase();
      $("#wdes-menu-iconpicker a").filter(function() {
        $(this).toggle($(this).data('search-terms').toLowerCase().indexOf(value) > -1)
      });
    });

    $(document).mouseup(function(e) {
      var container = $("#wdes-menu-iconpicker");

      // if the target of the click isn't the container nor a descendant of the container
      if (!container.is(e.target) && container.has(e.target).length === 0)
      {
        $('#wdes-menu-iconpicker').css('display', 'none');
        resetSearch();
      }

    });

    let resetSearch = function (){

    $('#wdes-iconpicker-search').val('');

    $("#wdes-menu-iconpicker a").map(function() {
      $(this).show();
    });

    }

  }

  //init after Dom get ready
  $(function () {
    WdesMegaMenu.init();
  });
})(jQuery, window);
