<%
  edit ||= easy_page_context[:page_params][:edit]
  (tabs = easy_page_context[:page_params][:tabs]) && tabs.count > 1 && current_tab = easy_page_context[:page_params][:current_tab]
  tab_pos = (current_tab && current_tab.position) || 1
  page_params = easy_page_context[:page_params]
%>
<div class="easy-page-add-module">
  <div class="easy-page-add-module__wrapper">
    <div class="easy-page-add-module__container">
      <% easy_page_available_modules(page_params[:page]).each do |_group_key, group| %>
        <h3><%= group[:name] %></h3>
        <div class="easy-page-add-module__content">
          <% group[:modules].sort! { |a, b| a.module_definition.translated_name.downcase <=> b.module_definition.translated_name.downcase }
             group[:modules].each do |available_module| %>
            <div id="<%= available_module.id %>" class="easy-page-add-module__item" data-gs-width="3">
              <i class="easy-page-add-module__item-image"></i><span class="easy-page-add-module__item-name"><%= available_module.module_definition.translated_name %>
              <span class="easy-page-add-module__item-description"></span></span></div>
          <% end %>
        </div>
      <% end %>
    </div>
  </div>
  <% if !edit %>
    <div class="easy-page-add-module__controls">
      <%= link_to(l(:button_unlock), 'javascript:void(0)', :onclick => %q{(function(e,obj){ $(obj).closest('.easy-page-add-module').toggleClass('easy-page-add-module_active').closest('.easy-page-content').toggleClass('easy-page-add-module__easy-page-content_activated') })(event, this)}, class: 'button-1 lock-grid', data: {lock: l(:button_lock), unlock: l(:button_unlock)}) %>
    </div>
  <% end %>
</div>

<div id="tab<%= tab_pos %>-list-top-middle-container" class="grid-stack-zone" style="display: none;" data-gs-current-height="10">
  <%= yield :easy_page_zone_top_middle %>
</div>

<%= javascript_include_tag('grid/grid.js') %>

<script type="text/javascript">
  $(function () {
    $('#easy-page-layout-service-box-bottom').remove();
    PageLayout.initSortable = function () {
    };

    var $page_zone = $('#tab<%= tab_pos %>-list-top-middle-container .easy-page-zone');

    var $parent = $page_zone.parent();
    $page_zone.detach();
    var $chldrn = $page_zone.children().not('.add-module-edit-content, script');
    $chldrn.children('.module-content').perfectScrollbar({
      includePadding: true,
      useSelectionScroll: true,
      wheelPropagation: true
    });
    $grds = $('<div id="tab-<%= tab_pos %>-gridstack_container" class="grid-stack" data-gs-current-height="10"></div>').appendTo($page_zone);
    $grds.append($chldrn);
    $chldrn.wrap("<div class='grid-stack-item-wrapper'></div>").parent().append("<span class='grid-stack-item-handle'>");
    var $parents = $chldrn.parent();

    $page_zone.appendTo($parent);

    var add_module_url = "<%= url_for(page_params[:url_add_module].merge(zone_id: page_params[:page].zones.first, t: tab_pos, edit: false, back_url: page_params[:back_url], original_url: page_params[:back_url], only_path: true)).html_safe %>";

    $grds = $grds.gridstack({
      itemClass: 'grid-stack-item-wrapper',
      handleClass: 'grid-stack-item-handle',
      cellHeight: ERUI.boxPadding,
      minWidth: 720,
      width: 12,
      verticalMargin: ERUI.boxPadding,
      resizable: {handles: 'se, sw'},
      acceptWidgets: '.easy-page-add-module__item'
    });

    $grds.on('resizestart', function (event, ui) {
      $chldrn.detach();
    });
    $grds.on('dragstart', function (event, ui) {
      $chldrn.detach();
    });
    $grds.on('resize', function (event, ui) {
      var evt = event || window.event
      var diff = evt.clientY - window.innerHeight;

      if (diff > 0) {
        window.scrollBy(0, diff);
      }
    });
    $grds.on('resizestop', function (event, ui) {
      $parents.each(function (index) {
        var $this = $(this);
        $this.append($($chldrn[index]));
      });
      pokeChart();
      responsivizer.fakeResponsive();
    });
    $grds.on('dragstop', function (event, ui) {
      $parents.each(function (index) {
        var $this = $(this);
        $this.append($($chldrn[index]));
      });
      pokeChart();
    });

    var grid = $grds.data('gridstack');

    var decoy = $(".grid-stack-decoy");
    if (decoy.length > 0) {
      grid.removeWidget(decoy.parent(), true);
    }

    function pokeChart() {
      setTimeout(function () {
        $('.easy_query_chart').resize();
      }, 300);
    }

    $grds.droppable({
      drop: function (event, ui) {
        var $container = $("<div class='grid-stack-item-wrapper' ></div>");

        var $placeholder = $grds.find('.grid-stack-placeholder');
        var placeholderPosition = $placeholder.offset();
        var placeholderCoordinates = grid.getCellFromPixel({
          top: placeholderPosition.top + 10,
          left: placeholderPosition.left + 10
        }, false);
        var placeholderWidth = $placeholder.data('gs-width');

        if (isNaN(placeholderWidth)) {
          placeholderWidth = 3
        }
        ;

        var callback = function () {
          grid.removeWidget($placeholder);

          var $child = $container.children().not('script');
          $chldrn = $chldrn.add($child);
          $parents = $parents.add($container);

          var widget = grid.addWidget($container.append("<span class='grid-stack-item-handle'>"), placeholderCoordinates.x, placeholderCoordinates.y, placeholderWidth, 10, false, 1, 12, 3);

          responsivizer.fakeResponsive();

          $container.find('.module-content').perfectScrollbar({
            includePadding: true,
            //suppressScrollX: true,
            useSelectionScroll: true,
            wheelPropagation: true
          });

          grid.update();
          saveGrid();

        }

        PageLayout.returnModule(add_module_url, ui.draggable.attr('id'), $container, callback);
      }
    });

    $(".easy-page-add-module__container").accordion({
      heightStyle: "fill"
    }).find(".easy-page-add-module__item").draggable({
      revert: true
    });

    var positions_json = JSON.parse('<%= easy_page_context[:page_params][:gridstack].to_json.html_safe %>');

    grid.batchUpdate();

    for (var uuid in positions_json) {
      var pos = positions_json[uuid];
      if (pos === undefined || !pos) {
        continue;
      }
      grid.update($('#module_' + uuid).parent(), Number(pos.x), Number(pos.y), Number(pos.width), Number(pos.height));
    }
    grid.commit();

    $chldrn.children('.module-content').perfectScrollbar('update');

    $('.grid-stack').on('change', function (event, items) {
      if (event.target == this)
        saveGrid();
    });
    toggleGridLock();
    $('.lock-grid').click(function (evt) {
      evt.preventDefault();
      toggleGridLock();
    });

    $('#tab<%= tab_pos %>-list-top-middle-container .easy-page-zone').on('easy_page:module_removed', function (evt, data) {
      $el = data.page_module.parent();
      grid.removeWidget($el);
    });

    function saveGrid() {
      var posData = {};
      $('.grid-stack .easy-page-module.box').each(function () {
        var $el = $(this);
        var node = $el.parent().data('_gridstack_node');
        var moduleName = $el.attr('id').replace(/^module_/, '');
        posData[moduleName] = {x: node.x, y: node.y, width: node.width, height: node.height};
      });
      $.ajax(
        '<%= easy_page_context[:page_params][:page].is_a?(EasyPage) ? easy_page_layout_save_grid_path : easy_page_template_layout_save_grid_path %>',
        {method: 'POST', data: {page_modules: posData}}
      );
    };

    function toggleGridLock() {
      var $btn = $('.lock-grid');
      var $grdstack = $('.grid-stack');
      if ($grdstack.hasClass('locked')) {
        grid.enable();
        $grdstack.removeClass('locked');
        $btn.text($btn.data('lock'));
      } else {
        grid.disable();
        $grdstack.addClass('locked');
        $btn.text($btn.data('unlock'));
      }
      $grdstack.find('.easy_query_chart').resize();
    };
    var height = $('.easy-page-add-module').height();

    $('.grid-stack-zone').css({
      display: "block"
    })
  });
</script>
<style>
  .grid-stack .easy-page-zone {
    position: relative;
    padding: 0;
  }

  .grid-stack-item-wrapper {
    position: absolute;
  }
</style>
