"use strict";

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

  var $window = $(w);
  w.happyParallaxEffects = function (element, settings) {
    var self = this,
      $el = $(element),
      scrolls = $el.data("scrolls"),
      elementSettings = settings,
      elType = elementSettings.elType,
      elOffset = $el.offset();

    //Check if Horizontal Scroll Widget
    var isHScrollWidget = $el.closest(".premium-hscroll-temp").length;
    self.elementRules = {};
    self.init = function () {
      if (scrolls || 'SECTION' === elType) {
        if (!elementSettings.effects.length) {
          return;
        }
        self.setDefaults();
        elementorFrontend.elements.$window.on('scroll load', self.initScroll);
      } else {
        elementorFrontend.elements.$window.off('scroll load', self.initScroll);
        return;
      }
    };
    self.setDefaults = function () {
      elementSettings.defaults = {};
      elementSettings.defaults.axis = 'y';
    };
    self.transform = function (action, percents, data) {
      if ("down" === data.direction) {
        percents = 100 - percents;
      }
      if (data.range) {
        if (data.range.start > percents && !isHScrollWidget) {
          percents = data.range.start;
        }
        if (data.range.end < percents && !isHScrollWidget) {
          percents = data.range.end;
        }
      }
      if ('rotate' === action) {
        elementSettings.defaults.unit = 'deg';
      } else {
        elementSettings.defaults.unit = 'px';
      }
      self.updateElement('transform', action, self.getStep(percents, data) + elementSettings.defaults.unit);
    };
    self.getPercents = function () {
      var dimensions = self.getDimensions();
      var startOffset = innerHeight;
      if (isHScrollWidget) startOffset = 0;
      elementTopWindowPoint = dimensions.elementTop - pageYOffset, elementEntrancePoint = elementTopWindowPoint - startOffset;
      passedRangePercents = 100 / dimensions.range * (elementEntrancePoint * -1);
      return passedRangePercents;
    };
    self.initScroll = function () {
      if (elementSettings.effects.includes('translateY')) {
        self.initVScroll();
      }
      if (elementSettings.effects.includes('translateX')) {
        self.initHScroll();
      }
    };
    self.initVScroll = function () {
      var percents = self.getPercents();
      self.transform('translateY', percents, elementSettings.vscroll);
    };
    self.initHScroll = function () {
      var percents = self.getPercents();
      self.transform('translateX', percents, elementSettings.hscroll);
    };
    self.getDimensions = function () {
      var elementOffset = $el.offset();
      var dimensions = {
        elementHeight: $el.outerHeight(),
        elementWidth: $el.outerWidth(),
        elementTop: elementOffset.top,
        elementLeft: elementOffset.left
      };
      dimensions.range = dimensions.elementHeight + innerHeight;
      return dimensions;
    };
    self.getStep = function (percents, options) {
      return -(percents - 50) * options.speed;
    };
    self.getEffectMovePoint = function (percents, effect, range) {
      var point = 0;
      if (percents < range.start) {
        if ("down" === effect) {
          point = 0;
        } else {
          point = 100;
        }
      } else if (percents < range.end) {
        point = self.getPointFromPercents(range.end - range.start, percents - range.start);
        if ("up" === effect) {
          point = 100 - point;
        }
      } else if ("up" === effect) {
        point = 0;
      } else if ("down" === effect) {
        point = 100;
      }
      return point;
    };
    self.getEffectValueFromMovePoint = function (level, movePoint) {
      return level * movePoint / 100;
    };
    self.getPointFromPercents = function (movableRange, percents) {
      var movePoint = percents / movableRange * 100;
      return +movePoint.toFixed(2);
    };
    self.updateElement = function (propName, key, value) {
      if (!self.elementRules[propName]) {
        self.elementRules[propName] = {};
      }
      if (!self.elementRules[propName][key]) {
        self.elementRules[propName][key] = true;
        self.updateElementRule(propName);
      }
      var cssVarKey = '--' + key;
      element.style.setProperty(cssVarKey, value);
    };
    self.updateElementRule = function (rule) {
      var cssValue = '';
      $.each(self.elementRules[rule], function (variableKey) {
        cssValue += variableKey + '(var(--' + variableKey + '))';
      });
      $el.css(rule, cssValue);
    };
  };
  $window.on("elementor/frontend/init", function () {
    var MultiLayerParallaxHandler = function MultiLayerParallaxHandler($scope) {
      if (!$scope.hasClass("ha-multi-layer-parallax--yes")) return;
      var target = $scope,
        widget_id = target.data("id"),
        editor_target = target.find('#ha-multi-layer-parallax--' + widget_id),
        editMode = elementorFrontend.isEditMode() && editor_target.length > 0,
        target_dom = editMode ? editor_target : target;
      var layerSettings = target_dom.data("ha-multi-layer-parallax");
      if (!layerSettings && 0 == Object.keys(layerSettings).length && !layerSettings["items"]) {
        return false;
      }
      var currentDevice = elementorFrontend.getCurrentDeviceMode();
      generateMultiLayers(currentDevice);
      if (false && editMode) {
        var layerSettings = {
            repeater: 'ha_multi_layer_parallax_list',
            item: '.ha-multi-layer-parallax',
            hor: 'ha_multi_layer_parallax_hor_pos',
            ver: 'ha_multi_layer_parallax_ver_pos',
            width: 'ha_multi_layer_parallax_width',
            tab: 'section_premium_parallax',
            offset: 0,
            widgets: ["drag", "resize"]
          },
          instance = null;
        instance = new premiumEditorBehavior(target, layerSettings); // this class is diclared in premium-addon.js [ path= C:\laragon\www\happy-test\wp-content\plugins\premium-addons-pro\assets\frontend\js\premium-addons.js]
        instance.init();
      }
      function generateMultiLayers(currentDevice) {
        var mouseParallax = "",
          deviceSuffix = 'desktop' === currentDevice ? '' : '_' + currentDevice,
          mouseRate = "";
        target.find(".ha-multi-layer-parallax").remove();
        $.each(layerSettings.items, function (index, layout) {
          if (!layout.show_layer_on.includes(currentDevice)) return;
          var layerHTML = getLayerHTML(layout);
          if ('' == layerHTML) return;
          var layerID = 'ha-multi-layer-parallax-' + layout._id,
            layerPosition = ' ha-multi-layer-parallax-' + layout.ha_multi_layer_parallax_hor + ' ha-multi-layer-parallax-' + layout.ha_multi_layer_parallax_ver,
            layerType = ' ha-multi-layer-parallax-' + layout.layer_type;
          if ("yes" === layout.ha_multi_layer_parallax_mouse && "" !== layout.ha_multi_layer_parallax_rate) {
            mouseParallax = ' data-parallax="true" ';
            mouseRate = ' data-rate="' + layout.ha_multi_layer_parallax_rate + '" ';
          } else {
            mouseParallax = ' data-parallax="false" ';
          }
          if ('img' === layout.layer_type) var width = 'undefined' != typeof layout["ha_multi_layer_parallax_width" + deviceSuffix] ? layout["ha_multi_layer_parallax_width" + deviceSuffix].size : layout["ha_multi_layer_parallax_width"].size;
          $('<div id="' + layerID + '"' + mouseParallax + mouseRate + ' class="ha-multi-layer-parallax elementor-repeater-item-' + layout._id + layerPosition + layerType + '">' + layerHTML + '</div>').prependTo(target).css({
            "z-index": layout["ha_multi_layer_parallax_z_index"],
            "background-size": layout["ha_multi_layer_parallax_back_size"],
            "width": 'img' === layout.layer_type ? width + "%" : "auto"
          });
          var $layer = target.find('#' + layerID);
          if ('custom' === layout.ha_multi_layer_parallax_hor) {
            var left = 'undefined' != typeof layout["ha_multi_layer_parallax_hor_pos" + deviceSuffix] ? layout["ha_multi_layer_parallax_hor_pos" + deviceSuffix].size : layout["ha_multi_layer_parallax_hor_pos"].size;
            $layer.css('left', left + '%');
          }
          if ('custom' === layout.ha_multi_layer_parallax_ver) {
            var top = 'undefined' != typeof layout["ha_multi_layer_parallax_ver_pos" + deviceSuffix] ? layout["ha_multi_layer_parallax_ver_pos" + deviceSuffix].size : layout["ha_multi_layer_parallax_ver_pos"].size;
            $layer.css('top', top + '%');
          }
          if (layerSettings.devices.includes(currentDevice)) {
            if ('yes' === layout['ha_multi_layer_parallax_scroll']) {
              if ('yes' === layout['ha_multi_layer_parallax_scroll_hor']) {
                $layer.attr({
                  'data-parallax-scroll': 'yes',
                  'data-parallax-hscroll': 'yes',
                  'data-parallax-hscroll_speed': layout['ha_multi_layer_parallax_speed_hor']['size'],
                  'data-parallax-hscroll_start': layout['ha_multi_layer_parallax_view_hor']['sizes']['start'],
                  'data-parallax-hscroll_end': layout['ha_multi_layer_parallax_view_hor']['sizes']['end'],
                  'data-parallax-hscroll_direction': layout['ha_multi_layer_parallax_direction_hor']
                });
              }
              if ('yes' === layout['ha_multi_layer_parallax_scroll_ver']) {
                $layer.attr({
                  'data-parallax-scroll': 'yes',
                  'data-parallax-vscroll': 'yes',
                  'data-parallax-speed': layout['ha_multi_layer_parallax_speed']['size'],
                  'data-parallax-start': layout['ha_multi_layer_parallax_view']['sizes']['start'],
                  'data-parallax-end': layout['ha_multi_layer_parallax_view']['sizes']['end'],
                  'data-parallax-direction': layout['ha_multi_layer_parallax_direction']
                });
              }
            }
          }
        });

        // target.imagesLoaded().done(function () {
        //     target.trigger("paParallaxLoaded");
        // });

        // window.PremiumSvgDrawerHandler(target, $, layerSettings.speed);

        function getLayerHTML(layer) {
          var html = '',
            imgID = '' != layer.ha_multi_layer_parallax_id ? 'id="' + layer.ha_multi_layer_parallax_id + '"' : '';
          if ('img' === layer.layer_type) {
            if (null !== layer["ha_multi_layer_parallax_image"]["url"] && "" !== layer["ha_multi_layer_parallax_image"]["url"]) {
              var backgroundImage = layer["ha_multi_layer_parallax_image"]["url"],
                alt = layer['alt'];
              html = '<img ' + imgID + ' class="ha-multi-layer-parallax-img" src="' + backgroundImage + '" alt="' + alt + '">';
            }
          } else {

            // var attributes = imgID + ' class="' + ("yes" === layer.draw_svg ? "premium-svg-drawer" : "premium-svg-nodraw") + '"';

            // if ("yes" === layer.draw_svg) {
            //     attributes += 'data-svg-reverse="' + layer.svg_reverse + '"';
            //     attributes += 'data-svg-loop="' + layer.svg_loop + '"';
            //     attributes += 'data-svg-sync="' + layer.svg_sync + '"';
            //     attributes += 'data-svg-hover="' + layer.svg_hover + '"';
            //     attributes += 'data-svg-restart="' + layer.restart_draw + '"';
            //     attributes += 'data-svg-fill="' + layer.svg_color + '"';
            //     attributes += 'data-svg-stroke="' + layer.svg_stroke + '"';
            //     attributes += 'data-svg-frames="' + layer.frames + '"';
            //     attributes += 'data-svg-yoyo="' + layer.svg_yoyo + '"';
            //     attributes += 'data-svg-point="' + (layer.svg_reverse ? layer.end_point.size : layer.start_point.size) + '"';
            // }

            // html = '<div ' + attributes + '>' + layer.ha_multi_layer_parallax_svg + '</div>';
          }
          return html;
        }
        if (-1 !== layerSettings.devices.indexOf(currentDevice)) {
          target.find('.ha-multi-layer-parallax').each(function (index, layer) {
            var data = $(layer).data();
            if ('yes' === data.parallaxScroll) {
              var effects = [],
                vScrollSettings = {},
                hScrollSettings = {},
                settings = {};
              if ('yes' === data.parallaxVscroll) {
                effects.push('translateY');
                vScrollSettings = {
                  speed: data.parallaxSpeed,
                  direction: data.parallaxDirection,
                  range: {
                    start: data.parallaxStart,
                    end: data.parallaxEnd
                  }
                };
              }
              if ('yes' === data.parallaxHscroll) {
                effects.push('translateX');
                hScrollSettings = {
                  speed: data.parallaxHscroll_speed,
                  direction: data.parallaxHscroll_direction,
                  range: {
                    start: data.parallaxHscroll_start,
                    end: data.parallaxHscroll_end
                  }
                };
              }
              settings = {
                elType: 'SECTION',
                vscroll: vScrollSettings,
                hscroll: hScrollSettings,
                effects: effects
              }, instance = null;

              // instance = new premiumParallaxEffects(layer, settings);
              instance = new happyParallaxEffects(layer, settings);
              instance.init();
            }
          });
        }
        target.mousemove(function (e) {
          $(this).find('.ha-multi-layer-parallax[data-parallax="true"]').each(function () {
            var $this = $(this),
              resistance = $(this).data("rate");
            TweenLite.to($this, 0.2, {
              x: -((e.clientX - window.innerWidth / 2) / resistance),
              y: -((e.clientY - window.innerHeight / 2) / resistance)
            });
          });
        });
      }
    };
    elementorFrontend.hooks.addAction("frontend/element_ready/section", MultiLayerParallaxHandler);
    elementorFrontend.hooks.addAction("frontend/element_ready/container", MultiLayerParallaxHandler);
  });
})(jQuery, window);