const foldingMenu = $("#foldingMenu"),
  toggler = $("li:last-child", foldingMenu),
  steps = 10,
  animationTime = 400,
  perspective = 1000,
  degree = 90,
  classNames = {
    animatingUp: "animating-up",
    animatingDown: "animating-down",
    unfolded: "unfolded",
    folded: "folded"
  };
(() =>
 foldingMenu.each(() => {
  const evenChild = foldingMenu.children(":even").not(toggler),
        oddChild = foldingMenu.children(":odd").not(toggler),
        listItems = $('li', foldingMenu),
        firstItemHeight = $('li', foldingMenu).eq(0).outerHeight(),
        degreePerStep = degree / steps;
  let counter = 0;

  changeStatus = (callBack) => {
    (applyTransform = () => {
      let angle = 90 - (foldingMenu.hasClass(classNames.unfolded) ? --counter : ++counter) * degreePerStep,
          currentHeight = 0,
          itemTop = 0;
      evenChild.css("transform", `perspective(${perspective}px) rotate3d(1, 0, 0, -${angle}deg)`);
      oddChild.css("transform", `perspective(${perspective}px) rotate3d(1, 0, 0,${angle}deg)`);
      currentHeight = (counter >= 0) ? parseInt(listItems[0].getBoundingClientRect().height) : 0;
      for (let i = 0; i < listItems.length; i++) {
        itemTop = (1 === i % 2) ? currentHeight * (i + 1) - firstItemHeight : currentHeight * i;
        listItems[i].style.top = itemTop + "px";
      }
      (counter === steps || 0 === counter) ? callBack() : setTimeout(applyTransform, animationTime / steps);
    })();
  };
  toggler.on("click", e => {
    foldingMenu.hasClass(classNames.animatingUp) ||
      (foldingMenu.hasClass(classNames.unfolded) ? (foldingMenu.addClass(classNames.animatingUp),
                                                    changeStatus(() => foldingMenu.removeClass(`${classNames.animatingUp} ${classNames.unfolded}`))
                                                   )
       : (foldingMenu.addClass(classNames.animatingUp, classNames.animatingDown),
          changeStatus(() => {
      foldingMenu.removeClass(`${classNames.animatingUp} ${classNames.animatingDown}`);
      foldingMenu.addClass(classNames.unfolded);
    })));
    e.preventDefault();
  });
})
)(jQuery);
