jQuery(document).ready(function($)
{
  if($("#boxes").length)
  {
    var gridCols=2;
    var contentCols=2;
    var cellWidth=119;
    var cellHeight=116;
    var cellGutter=6;
    var previewVerticalPadding=51+6;
    var previewHorizontalPadding=11+6;
    var postID,initialBoxID;
    var foundID=false;
    var targetAnchor=null;
    
    /*this prevents url from opening by default
    $(".bpr h2.main-heading a").click(
    function(e)
    {
      e.preventDefault()
    });*/
    
    arrangeBoxes()
  }
  function openBox(num,heading,targetAnchor)
  {
    var boxType,postID;
    if(typeof targetAnchor=='undefined')
      targetAnchor=null;
      num=num.replace("box-","");
      $(".box .content").hide();
  }
  function openBoxCallback(num,targetAnchor)
  {
    var heading;
    $(".box").each(function()
    {
      $(this).removeClass("box-content bpr hover").addClass("bpr");
      heading=$(this).find(".box-title h1");
      if(heading.length)
      {
        heading.replaceWith('<h2 title="'+heading.attr('title')+'" class="main-heading">'+heading.attr('title')+'</h2>')
      }
    });
    arrangeBoxes(targetAnchor)
  }
  
  function arrangeBoxes(targetAnchor)
  {
    var numBoxes=$(".box").size();
    var contentBox=$(".box-content");
    var row,col,cell,box,contentBoxNum,ID,contentStartRow,contentStartCol,startRow,i,cellInContent,contentRow,gridHeight,boxSlug,contentHeight,contentRows,contentCells,fragmentURL,scrollTarget;
    var gridUsedCells=numBoxes;
    var gridRows=Math.ceil(gridUsedCells/gridCols);
    var availableCells=[];
    row=col=cell=box=contentBoxNum=ID=contentStartRow=contentStartCol=startRow=i=0;
    contentRows=contentCells=1;
  
    if(typeof targetAnchor=='undefined')targetAnchor=null;
    $(".box").removeAttr("style");
    gridHeight=gridRows*(cellHeight+cellGutter);
    for(row=0;row<gridRows;row++)
    {
      for(col=0;col<gridCols;col++)
      {
        cell=(row*gridCols)+col;
        if(cell<=gridUsedCells)
        {
          cellInContent=false;
          if(!cellInContent)
          availableCells.push(cell)
        }
      }
    }
    i=0;
    for(box=0;box<numBoxes;box++)
    {
      if(!contentBox.length||box!=contentBoxNum)
      {
        cell=availableCells[i];
        $("#box-"+box).css({"top":getCellTop(cell)+"px","left":getCellLeft(cell)+"px","height":cellHeight-previewVerticalPadding+"px"});
        i++
      }
        
    }
    /*very important for hovering effect*/
    $(".bpr").unbind().mouseenter(
    function()
    {
      $(this).toggleClass("hover")
    })
  }

  function getCellTop(cell)
  {
    var cellTop=0;if(cell>(gridCols-1)){cellTop=Math.floor(cell/gridCols)*(cellHeight+cellGutter)}return cellTop
  }
  function getCellLeft(cell)
  {
    var cellLeft=0;
    if((cell%gridCols)>0)
    {
      cellLeft=(cell%gridCols)*(cellWidth+cellGutter)
    }
    return cellLeft
  }
});

