jQuery(document).ready(function($) {
  $( ".pix_tables.pricing" ).each(function(){
    var t = $(this),
      minwidth = parseFloat(t.data('opts').minwidth);
    $(window).bind('resize', function(){
      var w = t.parent().width();
      if (w <= minwidth) {
        t.addClass('minwidth-reached');
      } else {
        t.removeClass('minwidth-reached');
      }
    });
  });
});

jQuery(document).ready(function($) {
  var switched = false;
  var updateTables = function() {
    $(".pix_tables.data").each(function(i, element) {

      var $div = $(this),
        minwidth = parseFloat($div.data('opts').minwidth),
        $table = $('table', $div);

      if (($(window).width() < minwidth) && !switched ){
        switched = true;
        splitTable($table);
      } else if (switched && ($(window).width() > minwidth)) {
        switched = false;
        unsplitTable($table);
      }

    });
    return true;
  };
   
  $(window).load(updateTables);
  $(window).on("redraw",function(){switched=false;updateTables();}); // An event to listen for
  $(window).on("resize", updateTables);
  
  function splitTable(original)
  {
    original.wrap("<div class='table-wrapper' />");
    
    var copy = original.clone();
    copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
    copy.removeClass("responsive");
    
    original.closest(".table-wrapper").append(copy);
    copy.wrap("<div class='pinned' />");
    original.wrap("<div class='scrollable' />");

    setCellHeights(original, copy);
  }
  
  function unsplitTable(original) {
    original.closest(".table-wrapper").find(".pinned").remove();
    original.unwrap();
    original.unwrap();
  }

  function setCellHeights(original, copy) {
    var tr = original.find('tr'),
        tr_copy = copy.find('tr'),
        heights = [];

    tr.each(function (index) {
      var self = $(this),
          tx = self.find('th, td');

      tx.each(function () {
        var height = $(this).outerHeight(true);
        heights[index] = heights[index] || 0;
        if (height > heights[index]) heights[index] = height;
      });

    });

    tr_copy.each(function (index) {
      $(this).height(heights[index]);
    });
  }

});
