/*
File:           slidegrid.js
Description:    for more information see http://www.zackgrossbart.com/hackito/slidegrid/

*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/

/**
* Adds a specific cell to the set of used cells.  Used cells are skipped 
* when laying cells out in the future.
* 
* @param usedCells the array of used cells
* @param col       the column of the used cell
* @param row       the row of the used cell
*/
function setUsed(/*array*/ usedCells, /*int*/col, /*int*/row) {
  var index = usedCells.length;
  usedCells[index] = { left: col, top: row};
  //row++;
  //col++;
}

/**
* Lets you know if a specific column and row index has already been used.
* 
* @param usedCells the array of used cells
* @param col       the column of the cell to check
* @param row       the row of the cell to check
*/
function isUsed(/*array*/ usedCells, /*int*/ col, /*int*/ row) {
  for (var i = 0; i < usedCells.length; i++) {
    if (usedCells[i].left === col &&
      usedCells[i].top === row) {
        return true;
      }
    }
    return false;
  }

/**
* Applies the styling to a specific cell.
* 
* @param cell       The JQuery object representing the cell to style
* @param x          the left position of the cell in EMs
* @param y          the top position of the cell in EMs
* @param cellWidth  the width of the cell in EMs
* @param cellHeight the height of the cell in EMs
* @param animate    true if this style should be animated and false otherwise
*/
function styleCell(cell, x, y, cellWidth, cellHeight) {
  cell.css({
    width: cellWidth + "px",
    height: cellHeight + "px",
    position: "absolute",
    left: x + "px",
    top: y + "px"
  });
  
  var col = x / 190
  var row = y / 130
  
  // console.log("--- Positioniere Element "+cell+" auf row/col "+row+"/" + col + " -- Koordinaten:" + x + "|" + y);
  
  cell.addClass("used");
}

/**
* Aligns a set of elements in a resizable grid.
* 
* @param cellWidth  the width of each cell in EMs
* @param cellHeight the height of each cell in EMs
* @param padding    the paddin between each cell in EMs
*/
function alignGrid(/*int*/ cellWidth, /*int*/ cellHeight, /*int*/ padding) {
  var x = 0;
  var y = 0;
  var count = 1;
  /* 
  * When we add a "bigcell" to the grid it takes up four cells instead of one. 
  * That makes we need to not add any other cells to those areas or the cells 
  * will overlap.  These three variables are used to remember the cells used 
  * by big cells. 
  */
  var curCol = 0;
  var curRow = 0;
  var usedCells = [];

  $(".slidegrid").each(function() {

    // the specific kkk layout has four columns
    var cols = 4;

    // define new block formatting context
    $(this).css("position", "relative");

    // our entries are link tags
    var children = $(this).children("a");

    // positioning foo starts ...
    for (var i = 0; i < children.length; i++) {

      // console.log("- Aktuelles Element: "+i);

      // if our element is already positioned, skip it!
      if (!(children.eq(i).hasClass("used"))) {

        // console.log("-- Prüfe Position: " + curRow + "|" + curCol);

        // if the current cell is already in use, decrease the children-counter to keep the current element
        if (isUsed(usedCells, curCol, curRow)) {
          /* 
          * If the current cell is used we
          * just want to try the next column. 
          * However, we also want to bump to 
          * the next row if needed so we are 
          * calling the column logic and then 
          * backing up the counter. 
          */
          i--;
          // console.log("--- Position belegt.");

          // else, again: find a position!
        } else {
          // console.log("--- Position frei.");

          // if it's a larger cell ...
          if (children.eq(i).hasClass("large_entry")) {
            // console.log("-- Element ist große Box.");

            // ... it can only get a positon, that is free, and that isn't in the 3rd column
            if (!((curCol == 3) || (isUsed(usedCells, curCol + 1, curRow) || isUsed(usedCells, curCol, curRow + 1) || isUsed(usedCells, curCol + 1, curRow + 1))))
            {
              // console.log("--- Große Box kann platziert werden.");
              styleCell(children.eq(i), x, y, (cellWidth * 2) + padding, (cellHeight * 2) + padding);
              //console.log("curRow: " + curRow + " | curCol: " + curCol + " -- large item with id " + children.eq(i).domid);
              /* 
              * Big cells are twice as large as normal cells.  That means they 
              * use up the cell to the right, the cell below, and the cell to 
              * the right and below. 
              */
              setUsed(usedCells, curCol, curRow); 
              setUsed(usedCells, curCol + 1, curRow);
              setUsed(usedCells, curCol, curRow + 1);  
              setUsed(usedCells, curCol + 1, curRow + 1); 
            } else {
              // console.log("--- Große Box kann nicht platziert werden.");

              // find a small item instead and assign the current cell as the position
              styleCell($(".slidegrid .entry_partial:not(.used):not(.large_entry):first"), x, y, cellWidth, cellHeight);

              // ... and keep the large element for the next cell
              i--;
            }

          } else {
            // console.log("-- Element ist kleine Box.");
            
            styleCell(children.eq(i), x, y, cellWidth, cellHeight);
            //setUsed(usedCells, curCol, curRow); 
            //console.log("curRow: " + curRow + " | curCol: " + curCol + " -- small item with id " + i);

          } // end if (children.eq(i).hasClass("bigcell"))
        } // end if (isUsed(usedCells, curCol, curRow))


        // the positoning foo is over, do some orga stuff
        if (curCol+1 == cols)
        {
          /* 
          * This means it is time to bump down to the next row
          */
          curCol = 0;
          curRow++;
          // console.log("Wechsle zu Reihe " + curRow);
          x = 0;
          y += cellHeight + padding;

        } else
        {
          x += cellWidth + padding;
          curCol++;
          // console.log("Wechsle zu Spalte " + curCol);
        }


      } // end if (children.eq(i).hasClass("used") )
    } // for ... over!

    /*
    * Now we reset the variables for the next grid.
    */
    x = 0;
    y = 0;
    count = 1;
  });
}

function animateCells() {
  var intTime = 0;
  $('.entry_partial').each(function(i){
    var _this = this;
    window.setTimeout(function(){$(_this).animate({ opacity: 1.0, marginLeft: "0px", marginTop: "0px"}, 250 );}, intTime);
    intTime += 80;
  });
}

var windowWidth = 0;

$(document).ready(function() {
  alignGrid(180, 120, 10);
  animateCells();
  $(".slidegrid").height($(document).height()-150);
});