/*
 * tetrisgallery
 * http://source.mihelac.org
 *
 * Copyright (c) 2009 Bojan Mihelac
 *
 */
 
jQuery.fn.reverse = function() {
	return this.pushStack(this.get().reverse(), arguments);
}
 
function add_space(row, w, h) {
  if (row.length > 0 && row[row.length-1][1] == h) {
    row[row.length-1][0] += w;
  } else {
    row.push([w,h]);
  }
}

function available_space(row, x, w) {
  var current_x = 0;
  var res = [];
  x2 = x+w;
  for (var i=0; i < row.length; i++) {
    if ((current_x <= x && x < current_x+row[i][0]) || (current_x < x2 && x2 <= current_x+row[i][0])) {
      res.push(row[i][1]);
    }
    current_x += row[i][0];
  }
  if (res.length == 0) return(0);
  return(Math.min.apply(Math, res));
}

function calc_row_height(row) {
  row_height = 0;
  $.each(row, function() {
    if (this[1] > row_height) row_height = this[1];
  });
  return (row_height);
}

function transform_row_height_to_space(row, height) {
  $.each(row, function() {
    this[1] = height-this[1];
  });
}

function fill_remaining_space(row, total_width) {
  if (row.length == 0) return;
  w = 0;
  $.each(row, function() {
    w += this[0];
  });
  row[row.length-1][0] += total_width-w;
}

function tetrisgallery(gallery_el) {
  var current_top = null;
  var row = [];
  var previous_row = null;
  var x_pos = 0;
  var gallery_width = $(this).width();
  $(gallery_el).children('.cell').each(function(){
    el = $(this);
    if (el.position()['top'] != current_top) {
      el.before('<div class="row"></div>');
      $(this).addClass('first');
      current_top = el.position()['top'];
      previous_row = row;
      row = [];
      transform_row_height_to_space(previous_row, calc_row_height(previous_row));
      fill_remaining_space(previous_row, gallery_width);
      x_pos = 0;
    }
    off = el.offset();
    if (space = available_space(previous_row, x_pos, el.outerWidth())) {
      // move element up by space
      el.css('margin-top', -space + 'px');
    }
    add_space(row, el.outerWidth(), el.outerHeight()-space);
    x_pos += el.outerWidth();
  });
}

$(document).ready(function() {
  $('.gallery').each(function() {
    tetrisgallery(this);
  });
});