/* 
 * results.js
 */

function init_results(){
  var placed = {};
  $$('.result-thumb').each(function(img){
    var width = img.getStyle('width').toInt();
    var height = img.getStyle('height').toInt();
    var coords = place_image(width,height);
    img.setStyle('left',coords['x']+'px');
    img.setStyle('top',coords['y']+'px');
  });
}

var placed_imgs = new Array();

function can_place(img){
  for(var i=0; i<placed_imgs.length; i++){
    var pimg = placed_imgs[i];
    if( (img['x'] <= pimg['x']+pimg['w'] && img['x']+img['w'] >= pimg['x']) &&
        (img['y'] <= pimg['y']+pimg['h'] && img['y']+img['h'] >= pimg['y']))
    {
        return false;
    }
  }
  return true;
}

function place_image(width,height){
  var img = {'x': 50+$random(0,40), 'y': 105+$random(0,40), 'w': width+50, 'h': height+50};
  var cnt = 0;
  while(true){
    if(cnt++ > 100000){
      break;
    }
    if(can_place(img)){
      break;
    }
    img['x'] += 50;
    if(img['x'] >= (890-width)){
      img['x'] -= (890-width);
      img['y'] += 10;
    }
  }
  placed_imgs[placed_imgs.length] = img;
  return img;
}

window.addEvent('domready', function(){
  init_results();
  var div_height = 0;
  for(i=0; i<placed_imgs.length; i++){
    var new_height = placed_imgs[i]['y']+placed_imgs[i]['h'];
    if(new_height > div_height) div_height = new_height;
  }
  $('the-results').setStyle('height',div_height+50);
  $('the-loading-message').setStyle('display','none');
  $('the-results').setStyle('display','block');
});

