/* the Flash version has 2,3,4,5 on a row
*/
var blockwidth=150;
var blockheight=100;
var blockgrid;
var blockcols;
var blockpadding = 7;
var blockspacing = 4;
var blockinitialrows = 3;

function runit()
{
  var testelem = document.createElement('div');
  testelem.style.cssText = "background-size: cover; -moz-background-size: cover; -webkit-background-size: cover; -o-background-size: cover;";
  //var bgsizesupport = (testelem.style.cssText != "");
  // IE always returns the original csstext string
  var bgsizesupport = (typeof testelem.style.backgroundSize!="undefined"
                     ||typeof testelem.style.MozBackgroundSize!="undefined"
                     ||typeof testelem.style.WebkitBackgroundSize!="undefined"
                     ||typeof testelem.style.OBackgroundSize!="undefined"
                     );

  //creer blocks
  //bgsizesupport = false;
  for(var i=0;i<blocks.length;++i)
  {
    var curblock = blocks[i];

    //var blockurl = forcehtml ? curblock.url+"&forcehtml" : curblock.url;
    var blockurl = curblock.url;

    var newblock;
    if (curblock.bgimage != "")
    {
      newblock = new Element('a',
          { styles: { width: (blockwidth * curblock.size - blockspacing - blockpadding*2) + "px"
                    , height: (blockheight * curblock.size - blockspacing - blockpadding*2) + "px"
                    , color: curblock.textcolor=="" ? "#FFFFFF" : curblock.textcolor
                    , position: 'absolute'
                    //, backgroundImage: 'url("'+curblock.bgimage+'")'
                    }
          , "class":  "articleblock size"+curblock.size
          , html:   curblock.showtitle ? "<span style='display:block;position:relative;z-index:2;'>"+blocks[i].text+"</span>" : ""
          , href:   blockurl
          });

      if (bgsizesupport)
      {
        // browser can strech the background image to be the correct size
        newblock.style.backgroundImage = 'url("'+curblock.bgimage+'")';
      }
      else
      {
        var newimage = new Element( 'img'
                            , { src:    curblock.bgimage
                              , styles: { width: (blockwidth * curblock.size - blockspacing) + "px"
                                        , height: (blockheight * curblock.size - blockspacing) + "px"
                                        }
                              }
                            );
        newblock.appendChild(newimage);
      }
    }
    else
    {
      // (fixme: the following lines do not work correctly in IE)
      //if(curblock.bgcolor[0]!="#")
      //  curblock.bgcolor = "#"+curblock.bgcolor;
      //if(curblock.textcolor[0]!="#")
      //  curblock.textcolor = "#"+curblock.textcolor;

      newblock = new Element('a',
          { styles: { width: (blockwidth * curblock.size - blockspacing - blockpadding*2) + "px"
                    , height: (blockheight * curblock.size - blockspacing - blockpadding*2) + "px"
                    , position: 'absolute'
                    , backgroundColor: curblock.bgcolor=="" ? "#0083B1" : curblock.bgcolor
                    , color: curblock.textcolor=="" ? "#FFFFFF" : curblock.textcolor
                    }
          , "class":  "articleblock size"+curblock.size
          , html:   curblock.showtitle ? blocks[i].text : ""
          , href:   blockurl
          });
    }

//    newblock.style.mozBoxShadow = "-1px -1px 10px #CCCCCC";

    $('blockcontainer').appendChild(newblock);

    blocks[i].node = newblock;
  }

  prepare_rearrange_blocks();
  arrangeblocks_random();
  move_blocks();
}

function reshuffle()
{
  prepare_rearrange_blocks();
  arrangeblocks_random();
  move_blocks_tween();
}

function prepare_rearrange_blocks()
{
  blockgrid = [];
  blockcols = 6;

  //fixup blocks
  for(var tofix = blocks.length-1;tofix>=0;--tofix)
  {
    blocks[tofix].curx = blocks[tofix].newx;
    blocks[tofix].cury = blocks[tofix].newy;
  }

  //shuffle blocks
  var toshuffle = blocks.length;
  while(--toshuffle>0)
  {
    var swappos = Math.floor(Math.random()*toshuffle+1);
    var temp = blocks[toshuffle];
    blocks[toshuffle]=blocks[swappos];
    blocks[swappos]=temp;
  }
}
function fitblock(x,y,size)
{
  //extend the grid as needed
  while(blockgrid.length < (y+size)*blockcols)
    blockgrid.push(false);

  for(var test_y=y; test_y<y+size;++test_y)
    for(var test_x=x; test_x<x+size;++test_x)
      if(blockgrid[test_y * blockcols + test_x])
        return false; //spot taken

  for(var set_y=y; set_y<y+size;++set_y)
    for(var set_x=x; set_x<x+size;++set_x)
      blockgrid[set_y * blockcols + set_x]=true;
  return true;
}

function arrangeblocks_random()
{
  var initialrow = 0;
  var giveupafter = 1500; //how many tries before giving up on a row

  //randomized plaatser

  var blocksvertical = 0;

  for(var i=0;i<blocks.length;++i)
  {
    for (var attempts=0;;++attempts)
    {
      if( (attempts % giveupafter) == (giveupafter-1))
        ++initialrow; //time to try a new row

      var try_y = initialrow + Math.floor(Math.random() * (blockinitialrows - blocks[i].size + 1));
      var try_x = Math.floor(Math.random() * (blockcols - blocks[i].size + 1));

      if(!fitblock(try_x, try_y, blocks[i].size))
        continue;

      if (try_y+blocks[i].size > blocksvertical)
        blocksvertical = try_y+blocks[i].size;

      blocks[i].newx = try_x * blockwidth;
      blocks[i].newy = try_y * blockheight;
      break;
    }
  }

  // fixme: is there a better place to do the resizing?
  // resize container to fit all blocks
  $('blockcontainer').style.height = (blocksvertical * blockheight) + "px";
}

function move_blocks()
{
  for(var i=0;i<blocks.length;++i)
  {
    blocks[i].node.set('styles', { left: blocks[i].newx + 'px'
                                  , top: blocks[i].newy + 'px'
                                });
  }
}
function move_blocks_tween()
{
  for(var i=0;i<blocks.length;++i)
  {
    var effect = new Fx.Morph(blocks[i].node, { duration: 'normal'
                                              , transition: Fx.Transitions.Sine.easeOut
                                              });
    effect.start({ 'left': [ blocks[i].curx, blocks[i].newx ]
                 , 'top': [ blocks[i].cury, blocks[i].newy ]
                 });
  }
}
