google.setOnLoadCallback(init); 

function init()
{       
  $.getScripts(
    [
      base_dir + '/js/jquery.easing.1.3.js',
      base_dir + '/js/jquery.coda-slider-2.0.js',
      base_dir + '/js/jquery.columnize.min.js'
    ],
    initLoaded
  );
}

function initLoaded()
{
  initColumnize();
  initPortfolioSlider();
  initHeads();
  
  $('code').replaceWith('<marquee>' + $('code').html() + '</marquee>');
}

function initHeads()
{
  setTimeout('randomHead()', headTime);
  $('#heads img').css({opacity: 0}).attr('shown', 0).show();
}

var headTime = 3000;
var lastHead = -1;
var headCount = 0;
function randomHead()
{   
  var r = Math.round(Math.random() * 5);
  var i = $($('#heads img')[r]);
  var s = i.attr('shown') == 1;
  if ((r == lastHead) || (headCount < 3 && s) || (headCount >= 3 && !s)) 
  {
    randomHead(); 
    return;
  } 
  i.attr('shown', s ? 0 : 1).animate({opacity: s ? 0 : 1}, 1000);
  lastHead = r;
  headCount += s ? -1 : +1 ;
  setTimeout('randomHead()', headTime);
}

function initColumnize()
{
  // create multiple columns where needed
  $('.columnize').each(function()
  {
    $(this).columnize({ 
      columns: parseInt($(this).attr('columns')) 
    });
  });
  
  // clear columns styles; already defined in screen.css
  $('.column').attr('style', '').removeAttr('style');
}

function initPortfolioSlider()
{
  $('#slideshow_images .image')
    .addClass('panel-wrapper')
    .wrap('<div class="panel" />')
  ;
  
  $('#slideshow_images').each(function()
  {
    if ($('.image', $(this)).length > 1)
    {
      $(this)
        .css('height', 'auto')
        .addClass('coda-slider preload')
        .wrap('<div class="coda-slider-wrapper" />')
        .codaSlider({
          autoHeight: false,
          firstPanelToLoad: 1,
          dynamicArrows: false,
          dynamicTabs: false,
          autoSlide: true,
          autoSlideInterval: 4000,
          autoSlideStopWhenClicked: true,
          slideHorizontal: true
        })
      ;
      
      var h = $('#slideshow_images').height();
      console.log('slideshow_images height = ' + h);
      $(this).find('.image').each(function()
      {
        var p = Math.max(0, (h - $(this).height())/2); 
        console.log('image height = ' + $(this).height());
        console.log('image margin = ' + p); 
        $(this).css('margin-top', p + 'px');
      });
    }  
  });    
}

$.getScripts = function(scripts, onComplete)
{
  var i = 1;
  var ii = scripts.length;  
  var onScriptLoaded = function(data, response) { if (i++ == ii) onComplete(); } ; 
  for(var s in scripts) { $.getScript(scripts[s], onScriptLoaded); } ;
};
