/* ============================================================
   1. ANIMATED BLOCKS
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.animatedBlock = {
    init: function() {
      $(".vlt-animated-block").each(function() {
        var block = $(this);
        VLTJS.window.on("vlt.change-slide", function() {
          block.removeClass("animated");
          if (block.parents(".vlt-section").hasClass("active")) {
            block.addClass("animated");
          }
        });
      });
    }
  };
  VLTJS.animatedBlock.init();
}(jQuery);

/* ============================================================
   2. CONTACT FORM
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.contactForm = {
    init: function() {
      if (typeof $.fn.validate !== "undefined") {
        $(".vlt-contact-form").each(function() {
          var form = $(this),
              successMsg = form.find(".message.success"),
              errorMsg = form.find(".message.danger");
          
          form.validate({
            errorClass: "error",
            submitHandler: function(formElement) {
              $.ajax({
                type: "POST",
                url: "contact.php",
                data: new FormData(formElement),
                cache: false,
                contentType: false,
                processData: false,
                success: function() {
                  successMsg.fadeIn();
                  setTimeout(function() { successMsg.fadeOut(); }, 5000);
                },
                error: function() {
                  errorMsg.fadeIn();
                  setTimeout(function() { errorMsg.fadeOut(); }, 5000);
                }
              });
            }
          });
        });
      }
    }
  };
  VLTJS.contactForm.init();
}(jQuery);

/* ============================================================
   3. COUNTER UP
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.counterUp = {
    init: function() {
      if (typeof $.fn.numerator !== "undefined") {
        $(".vlt-counter-up, .vlt-counter-up-small").each(function() {
          var counter = $(this),
              speed = counter.data("animation-speed") || 1000,
              target = counter.data("ending-number") || 0,
              delimiter = counter.data("delimiter") || false;

          VLTJS.window.on("vlt.change-slide", function() {
            if (counter.parents(".vlt-section").hasClass("active")) {
              var el = counter.find(".counter").html("0");
              setTimeout(function() {
                el.numerator({
                  easing: "linear",
                  duration: speed,
                  delimiter: delimiter,
                  toValue: target
                });
              }, 500);
            }
          });
        });
      }
    }
  };
  VLTJS.counterUp.init();
}(jQuery);

/* ============================================================
   4. CUSTOM CURSOR
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.customCursor = {
    init: function() {
      if ($(".vlt-is--custom-cursor").length) {
        VLTJS.body.append('<div class="vlt-custom-cursor"><div class="circle"><span></span></div></div>');
        var circle = $(".vlt-custom-cursor .circle"),
            pos = { x: 0, y: 0 },
            mouse = { x: 0, y: 0 };

        if (typeof gsap !== "undefined") {
          gsap.set(circle, { xPercent: -50, yPercent: -50 });

          VLTJS.document.on("mousemove", function(e) {
            var scrollY = window.pageYOffset || document.documentElement.scrollTop;
            mouse.x = e.pageX;
            mouse.y = e.pageY - scrollY;
          });

          gsap.ticker.add(function() {
            pos.x += 0.25 * (mouse.x - pos.x);
            pos.y += 0.25 * (mouse.y - pos.y);
            gsap.set(circle, { x: pos.x, y: pos.y });
          });

          // Mouse interactions
          VLTJS.document
            .on("mousedown", function() { gsap.to(circle, 0.3, { scale: 0.7 }); })
            .on("mouseup", function() { gsap.to(circle, 0.3, { scale: 1 }); });

          // Hide cursor on inputs
          VLTJS.document
            .on("mouseenter", "input, textarea, select, .vlt-video-button > a", function() {
              gsap.to(circle, 0.3, { scale: 0, opacity: 0 });
            })
            .on("mouseleave", "input, textarea, select, .vlt-video-button > a", function() {
              gsap.to(circle, 0.3, { scale: 1, opacity: 0.1 });
            });

          // Expand on hover links
          VLTJS.document
            .on("mouseenter", 'a, button, [role="button"]', function() {
              gsap.to(circle, 0.3, { height: 60, width: 60 });
            })
            .on("mouseleave blur", 'a, button, [role="button"]', function() {
              gsap.to(circle, 0.3, { height: 15, width: 15 });
            });

          // Dynamic data-cursor text
          VLTJS.document
            .on("mouseenter", "[data-cursor]", function() {
              var el = $(this);
              gsap.to(circle, 0.3, {
                height: 80,
                width: 80,
                opacity: 1,
                onStart: function() {
                  circle.find("span").html(el.attr("data-cursor"));
                }
              });
            })
            .on("mouseleave", "[data-cursor]", function() {
              gsap.to(circle, 0.3, {
                height: 15,
                width: 15,
                opacity: 0.1,
                onStart: function() {
                  circle.find("span").html("");
                }
              });
            });
        }
      }
    }
  };
  if (!VLTJS.isMobile.any()) VLTJS.customCursor.init();
}(jQuery);

/* ============================================================
   5. FULLPAGE SLIDER
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.fullpageSlider = {
    init: function() {
      if (typeof $.fn.pagepiling === "undefined") return;

      var slider = $(".vlt-fullpage-slider"),
          bar = slider.find(".vlt-fullpage-slider-progress-bar"),
          numbers = slider.find(".vlt-fullpage-slider-numbers"),
          loopTop = !!slider.data("loop-top"),
          loopBottom = !!slider.data("loop-bottom"),
          speed = slider.data("speed") || 200,
          anchors = [];

      function toggleNavbar() {
        slider.find(".pp-section.active").scrollTop() > 0 ?
          $(".vlt-navbar").addClass("vlt-navbar--solid") :
          $(".vlt-navbar").removeClass("vlt-navbar--solid");
      }

      function updateTheme() {
        switch (slider.find(".vlt-section.active").data("brightness")) {
          case "light":
            VLTJS.html.removeClass("is-light").addClass("is-dark");
            break;
          case "dark":
            VLTJS.html.removeClass("is-dark").addClass("is-light");
        }
      }

      function updateNumbers() {
        var index = slider.find(".vlt-section.active").index();
        numbers.html(
          index === 0
            ? '<a href="#"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"></line><polyline points="19 12 12 19 5 12"></polyline></svg></a>'
            : VLTJS.addLedingZero(index + 1)
        );
      }

      slider.find("[data-anchor]").each(function() {
        anchors.push($(this).data("anchor"));
      });

      $("body, html").css("overflow", "hidden");
      toggleNavbar();

      slider.pagepiling({
        menu: ".vlt-offcanvas-menu ul.sf-menu, .vlt-fullpage-slider-progress-bar",
        scrollingSpeed: speed,
        loopTop: loopTop,
        loopBottom: loopBottom,
        anchors: anchors,
        sectionSelector: ".vlt-section",
        navigation: false,
        afterRender: function() {
          bar.find("li:first-child").addClass("active").end().addClass("is-show");
          updateTheme();
          updateNumbers();
          VLTJS.window.trigger("vlt.change-slide");
        },
        onLeave: function(_, index, direction) {
          updateTheme();
          if (direction === "down") bar.find("li:nth-child(" + index + ")").prevAll().addClass("prev");
          if (direction === "up") bar.find("li:nth-child(" + index + ")").removeClass("prev");
          updateNumbers();
          VLTJS.window.trigger("vlt.change-slide");
        },
        afterLoad: function() {
          bar.find("li.active").prevAll().addClass("prev");
          toggleNavbar();
        }
      });

      numbers.on("click", ">a", function(e) {
        e.preventDefault();
        $.fn.pagepiling.moveSectionDown();
      });

      slider.find(".pp-scrollable").on("scroll", function() {
        $(this).scrollTop() > 0
          ? $(".vlt-navbar").addClass("vlt-navbar--solid")
          : $(".vlt-navbar").removeClass("vlt-navbar--solid");
      });
    }
  };
  VLTJS.fullpageSlider.init();
}(jQuery);

/* ============================================================
   6. MENU OFFCANVAS
   ============================================================ */
!function($) {
  "use strict";
  var isOpen = false;
  VLTJS.menuOffcanvas = {
    config: { easing: "power2.out" },
    init: function() {
      var menu = $(".vlt-offcanvas-menu"),
          items = menu.find("ul.sf-menu > li"),
          header = $(".vlt-offcanvas-menu__header"),
          footer = $(".vlt-offcanvas-menu__footer > div"),
          openBtn = $(".js-offcanvas-menu-open"),
          closeBtn = $(".js-offcanvas-menu-close"),
          overlay = $(".vlt-site-overlay");

      if (typeof $.fn.superclick !== "undefined")
        menu.find("ul.sf-menu").superclick({
          delay: 300,
          cssArrows: false,
          animation: { opacity: "show", height: "show" },
          animationOut: { opacity: "hide", height: "hide" }
        });

      openBtn.on("click", function(e) {
        e.preventDefault();
        if (!isOpen) VLTJS.menuOffcanvas.open(menu, overlay, items, header, footer);
      });

      closeBtn.on("click", function(e) {
        e.preventDefault();
        if (isOpen) VLTJS.menuOffcanvas.close(menu, overlay, items, header, footer);
      });

      overlay.on("click", function(e) {
        e.preventDefault();
        if (isOpen) VLTJS.menuOffcanvas.close(menu, overlay, items, header, footer);
      });

      $(document).keyup(function(e) {
        if (e.keyCode === 27 && isOpen) {
          e.preventDefault();
          VLTJS.menuOffcanvas.close(menu, overlay, items, header, footer);
        }
      });

      items.filter("[data-menuanchor]").on("click", "a", function() {
        if (isOpen) VLTJS.menuOffcanvas.close(menu, overlay, items, header, footer);
      });
    },
    open: function(menu, overlay, items, header, footer) {
      isOpen = true;
      if (typeof gsap !== "undefined") {
        gsap.timeline({ defaults: { ease: this.config.easing } })
          .set(VLTJS.html, { overflow: "hidden" })
          .to(overlay, 0.3, { autoAlpha: 1 })
          .fromTo(menu, 0.6, { x: "100%" }, { x: 0, visibility: "visible" }, "-=.3")
          .fromTo(header, 0.3, { x: 50, autoAlpha: 0 }, { x: 0, autoAlpha: 1 }, "-=.3")
          .fromTo(items, 0.3, { x: 50, autoAlpha: 0 }, { x: 0, autoAlpha: 1, stagger: { each: .1 } }, "-=.15")
          .fromTo(footer, 0.3, { x: 50, autoAlpha: 0 }, { x: 0, autoAlpha: 1, stagger: { each: .1 } }, "-=.15");
      }
    },
    close: function(menu, overlay, items, header, footer) {
      isOpen = false;
      if (typeof gsap !== "undefined") {
        gsap.timeline({ defaults: { ease: this.config.easing } })
          .set(VLTJS.html, { overflow: "inherit" })
          .to(footer, 0.3, { x: 50, autoAlpha: 0, stagger: { each: .1 } })
          .to(items, 0.3, { x: 50, autoAlpha: 0, stagger: { each: .1 } }, "-=.15")
          .to(header, 0.3, { x: 50, autoAlpha: 0 }, "-=.15")
          .to(menu, 0.6, { x: "100%" }, "-=.15")
          .set(menu, { visibility: "hidden" })
          .to(overlay, 0.3, { autoAlpha: 0 }, "-=.6");
      }
    }
  };
  VLTJS.menuOffcanvas.init();
}(jQuery);

/* ============================================================
   7. FAST CLICK
   ============================================================ */
!function($) {
  "use strict";
  if (typeof FastClick === "function") FastClick.attach(document.body);
}(jQuery);

/* ============================================================
   8. ANIMSITION (Page Transitions)
   ============================================================ */
!function($) {
  "use strict";
  if (typeof $.fn.animsition !== "undefined") {
    var animsitionEl = $(".animsition");
    animsitionEl.animsition({
      inDuration: 500,
      outDuration: 500,
      linkElement: 'a:not([target="_blank"]):not([href^="#"]):not([rel="nofollow"]):not([href~="#"]):not([href^=mailto]):not([href^=tel]):not(.sf-with-ul)',
      loadingClass: "animsition-loading-2",
      loadingInner: '<div class="spinner"><span class="double-bounce-one"></span><span class="double-bounce-two"></span></div>'
    });
    animsitionEl.on("animsition.inEnd", function() {
      VLTJS.window.trigger("vlt.preloader_done");
      VLTJS.html.addClass("vlt-is-page-loaded");
    });
  }
}(jQuery);

/* ============================================================
   9. PROGRESS BAR
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.progressBar = {
    init: function() {
      if (typeof gsap !== "undefined") {
        $(".vlt-progress-bar").each(function() {
          var bar = $(this),
              finalValue = bar.data("final-value") || 0,
              speed = bar.data("animation-speed") || 0,
              counter = { count: 0 };

          VLTJS.window.on("vlt.change-slide", function() {
            if (bar.parents(".vlt-section").hasClass("active")) {
              counter.count = 0;
              bar.find(".vlt-progress-bar__title > .counter").text(0);
              gsap.set(bar.find(".vlt-progress-bar__bar > span"), { width: 0 });

              gsap.to(counter, speed / 1000 / 2, {
                count: finalValue,
                delay: .5,
                onUpdate: function() {
                  bar.find(".vlt-progress-bar__title > .counter").text(Math.round(counter.count));
                }
              });

              gsap.to(bar.find(".vlt-progress-bar__bar > span"), speed / 1000, {
                width: finalValue + "%",
                delay: .5
              });
            }
          });
        });
      }
    }
  };
  VLTJS.progressBar.init();
}(jQuery);

/* ============================================================
   10. PROJECT SHOWCASE
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.projectShowcase = {
    initSlider: function() {
      if (typeof Swiper !== "undefined") {
        var container = $(".vlt-project-showcase-slider .swiper-container");
        new Swiper(container, {
          speed: 1000,
          spaceBetween: 30,
          grabCursor: true,
          slidesPerView: 1,
          breakpoints: { 575: { slidesPerView: 2 } }
        });
      }
    },
    initParallax: function() {
      if (typeof gsap !== "undefined") {
        var showcase = $(".vlt-project-showcase"),
            itemsWrap = showcase.find(".vlt-project-showcase__items"),
            items = itemsWrap.find(".vlt-project-showcase__item"),
            imagesWrap = showcase.find(".vlt-project-showcase__images"),
            images = imagesWrap.find(".vlt-project-showcase__image"),
            showcaseWidth = showcase.outerWidth(true),
            imgWidth = imagesWrap.outerWidth(true),
            itemsWidth = itemsWrap.outerWidth(),
            ratio = (showcaseWidth - imgWidth) / showcaseWidth;

        items.on("mouseenter", function() {
          items.removeClass("is-active");
          images.removeClass("is-active");
          $(this).addClass("is-active");
          images.eq($(this).index()).addClass("is-active");
        });
        items.eq(0).trigger("mouseenter");

        var mouseX;
        VLTJS.window.on("mousemove", function(e) {
          mouseX = e.pageX - showcase.offset().left;
        });

        gsap.ticker.add(function() {
          gsap.set(itemsWrap, { x: mouseX * ((showcaseWidth - itemsWidth) / showcaseWidth), ease: "power3.out" });
          gsap.set(imagesWrap, { right: mouseX * ratio, ease: "power3.out" });
        });
      }
    }
  };
  VLTJS.projectShowcase.initSlider();
  VLTJS.projectShowcase.initParallax();
  VLTJS.debounceResize(function() {
    VLTJS.projectShowcase.initParallax();
  });
}(jQuery);

/* ============================================================
   11. TESTIMONIAL SLIDER
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.testimonialSlider = {
    init: function() {
      if (typeof Swiper !== "undefined") {
        $(".vlt-testimonial-slider .swiper-container").each(function() {
          $(this).find(".swiper-wrapper > *").wrap('<div class="swiper-slide">');
          new Swiper(this, {
            speed: 1000,
            spaceBetween: 30,
            grabCursor: true,
            effect: "coverflow",
            slidesPerView: 1,
            navigation: {
              nextEl: $(".vlt-testimonial-slider-controls .next"),
              prevEl: $(".vlt-testimonial-slider-controls .prev")
            },
            pagination: {
              el: $(".vlt-testimonial-slider-controls .pagination"),
              clickable: false,
              type: "fraction",
              renderFraction: function(current, total) {
                return `<span class="${current}"></span><span class="sep">/</span><span class="${total}"></span>`;
              }
            }
          });
        });
      }
    }
  };
  VLTJS.testimonialSlider.init();
}(jQuery);

/* ============================================================
   12. TIMELINE SLIDER
   ============================================================ */
!function($) {
  "use strict";
  VLTJS.timelineSlider = {
    init: function() {
      if (typeof Swiper !== "undefined") {
        $(".vlt-timeline-slider .swiper-container").each(function() {
          $(this).find(".swiper-wrapper > *").wrap('<div class="swiper-slide">');
          new Swiper(this, {
            speed: 1000,
            spaceBetween: 0,
            grabCursor: true,
            slidesPerView: 1,
            navigation: {
              nextEl: $(".vlt-timeline-slider-controls .next"),
              prevEl: $(".vlt-timeline-slider-controls .prev")
            },
            pagination: {
              el: $(".vlt-timeline-slider-controls .pagination"),
              clickable: false,
              type: "fraction",
              renderFraction: function(current, total) {
                return `<span class="${current}"></span><span class="sep">/</span><span class="${total}"></span>`;
              }
            }
          });
        });
      }
    }
  };
  VLTJS.timelineSlider.init();
}(jQuery);
