'use strict';

$(document).ready(function() {

  if ($("#flt_head").length > 0) {

    console.log($("#flt_head"))

    if (detectIE() == false) {
      flt_head();
    } else {
      flt_head__IE();
    }

  }

});



function flt_head() {
  var $context = $('#main_content'),
    $tHead = $('#flt_head'),
    sTop = parseInt($tHead.position().top),
    scrollTimer = null,
    offset = 1,
    pos = 0;

  // precalc offset
  sTop += offset;

  $context.on("scroll", function(evt) {
    // clearTimeout(scrollTimer);   // clear any previous pending timer
    // scrollTimer = setTimeout(function() {
    handleScroll(evt.target.scrollTop);
    // }, 150);   // set new timer
  });

  function handleScroll(scrolled) {
    pos = scrolled - sTop;
    if (pos > 0) {
      $tHead.css("transform", "translateY(" + pos + "px)");
      return;
    } else {
      $tHead.css("transform", "translateY(" + 0 + "px)");
      return;
    }
  }
};



function flt_head__IE() {

  var $clonedHeaderRow = $("#flt_head"),
      $context = $('#main_content'),
      widths = [];

  // get widths of original th's
  $('#flt_head').find('th').each(function(index) {
    widths[index] = $(this)[0].getBoundingClientRect().width;
  })

  // clone the original header
  $clonedHeaderRow.before(
    $clonedHeaderRow.clone()
    .css("width", $clonedHeaderRow.width())
    .addClass("floatingHeader")
  )

  // set widths for cloned header
  $('.floatingHeader').find('th').each(function(index) {
    $(this).css({
      "min-width": widths[index],
      "width": "100%"
    });
  })

  $context.on("scroll", function(evt) {
    UpdateTableHeader__IE();
  });

  $( document ).on( "EVT__sidebar", function(event, state) {
    var $el = $("#data-table"),
        offset = $el.offset(),
        scrollTop = $(window).scrollTop(),
        $floatingHeader = $(".floatingHeader", this),
        offset_left = 0;

        if(offset.left == 350 || offset.left == 50) {
            offset_left = (state == 'visible')? 350 : 50
        } else {
          if (state == 'hidden'){
              offset_left =  offset.left - 300
          }
          else {
              offset_left =  offset.left + 300
          }
        }

      if ((scrollTop > offset.top) && (scrollTop < offset.top + $el.height())) {
        $floatingHeader.css({
          "left": offset_left
        });
      };
  });

  function UpdateTableHeader__IE() {
      var $el = $("#data-table"),
          offset = $el.offset(),
          scrollTop = $(window).scrollTop(),
          $floatingHeader = $(".floatingHeader", this)

      if ((scrollTop > offset.top) && (scrollTop < offset.top + $el.height())) {
        $floatingHeader.css({
          "visibility": "visible",
          "left": (offset.left)
        });
      } else {
        $floatingHeader.css({
          "visibility": "hidden"
        });
      };
  }
}
