// http://isotope.metafizzy.co/tests/centered-masonry.html
$.Isotope.prototype._getCenteredMasonryColumns = function() {
  this.width = this.element.width();
  
  var parentWidth = this.element.parent().width();
  
                // i.e. options.masonry && options.masonry.columnWidth
  var colW = this.options.masonry && this.options.masonry.columnWidth ||
                // or use the size of the first item
                this.$filteredAtoms.outerWidth(true) ||
                // if there's no items, use size of container
                parentWidth;
  
  var cols = Math.floor( parentWidth / colW );
  cols = Math.max( cols, 1 );

  // i.e. this.masonry.cols = ....
  this.masonry.cols = cols;
  // i.e. this.masonry.columnWidth = ...
  this.masonry.columnWidth = colW;
  
  return this;
};

$.Isotope.prototype._masonryReset = function() {
  // layout-specific props
  this.masonry = {};
  // FIXME shouldn't have to call this again
  this._getCenteredMasonryColumns();
  var i = this.masonry.cols;
  this.masonry.colYs = [];
  while (i--) {
    this.masonry.colYs.push( 0 );
  }
  return this;
};

// always trigger reLayout, just to quell media query issues
$.Isotope.prototype._masonryResizeChanged = function() {
  return true;
};

$.Isotope.prototype._masonryGetContainerSize = function() {
  var itemsTotalWidth = 0;
  this.$filteredAtoms.each(function(){
    itemsTotalWidth += $(this).outerWidth(true);
  });
  
  var layoutWidth = this.masonry.cols * this.masonry.columnWidth,
      size = {
        height : Math.max.apply( Math, this.masonry.colYs ),
        width : Math.min(layoutWidth, itemsTotalWidth )
      };
  return size;
  
};

$(document).ready(function(){

  var $main = $('#gallery, #gallery2');


  $main.isotope({
    layoutMode: 'masonry',
  });

  $('#filter a').click(function() {
    var $this = $(this);
    
    // don't continue if filter is already active
    if (!$this.hasClass('selected')) {
      $this.parents('#filter').find('.active').removeClass('active');
      $this.addClass('active');
    }

    // filtering active class
    var selector = $this.attr('data-filter');
    
    $main.isotope({
      filter: selector
    });
    return false;
  });

});
