google.load("jquery", "1.4.2");
google.load('search', '1');

var GRID_SIZE = 24;
var grid = [];
var images = [];
PAGE_SIZE = 3;

function searchComplete(imageSearch) {
  // Check that we got results
  if (imageSearch.results && imageSearch.results.length > 0) {
    // Grab our content div, clear it.

    // Loop through our results, printing them to the page.
    var results = imageSearch.results;
    for (var i = 0; i < results.length; i++) {
      // For each result write it's title and image to the screen
      var result = results[i];

      var newImg = document.createElement('img');
      // There is also a result.url property which has the escaped version
      newImg.src = result.tbUrl;
      newImg.width = 106;
      newImg.height = (106.0/parseInt(result.tbWidth))*parseInt(result.tbHeight);
      $(newImg).hide();

      images.push($(newImg));

      var cursor = imageSearch.cursor;
      if (cursor && cursor.currentPageIndex < PAGE_SIZE) {
        imageSearch.gotoPage(cursor.currentPageIndex+1);
      }

    }
  }
}

function OnLoad() {
  // setup grid

  for(var i = 0; i < 24; i++) {
    var n = $('<div></div>');
    n.addClass('result')

    if (i < 12)
      $('.a').append(n);
    else
      $('.b').append(n);

    grid.push(n);
  }


  $('#spread img').each(function() {
    // set up pointer cursor
    var imageSearch = new google.search.ImageSearch();
    imageSearch.setResultSetSize(5);

    // Restrict to extra large images only
    imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                               google.search.ImageSearch.IMAGESIZE_MEDIUM);
    imageSearch.setNoHtmlGeneration();

    // Here we set a callback so that anytime a search is executed, it will call
    // the searchComplete function and pass it our ImageSearch searcher.
    // When a search completes, our ImageSearch object is automatically
    // populated with the results.
    imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);

    $.each($(this).attr('title').split(","), function() {
      imageSearch.execute(this);
    });

   });

  $('div.result').mouseenter(function() {
      var newImg = images[Math.floor(Math.random()*images.length)].clone();
      if ($(this).find('img').length > 0) {
      $(this).find('img').fadeOut('fast', function(){
          $(this).find('img').remove();
          $(this).parent().append(newImg);
          $(newImg).fadeIn();
        });
      } else {
        $(this).append(newImg);
        $(newImg).fadeIn();
      }
  });
  $('.result').mouseleave(function() {
    var img = $(this).find('img');
    setTimeout(function() {
      img.fadeOut('fast'); 
    }, 3000);
  });

  $('#about, #download').click(function(){ 
      $('#about, #download').removeClass('selected').next('.info').hide();
      $(this).addClass('selected'); 
      $(this).next('.info').toggle();
  });
}

google.setOnLoadCallback(OnLoad);

