$(function() {
 
  // Banner rotation...
  $('div#banner ul').innerfade({ 
		speed: 'slow',
		timeout: 10000,
		type: 'random',
		containerheight: '161px'
	});
	
	
	// Image preloading
	// http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
  var cache = [];
    $.preLoadImages = function() {
      var args_len = arguments.length;
      for (var i = args_len; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
      }      
    }
  
	
	// Case Study Thumbnails
  $('a.case-study-thumbnail').click(function() {
    var me = $(this);
    var new_image = me.attr('href');
    var main_image = me.parent().parent().find('div.main-image img');
    main_image.animate({opacity:'0'},250).queue(function () {
      var img = new Image();
      $(img).load(function() {
        main_image.replaceWith(this);
        main_image.animate({opacity:'1'},250);
      }).attr('src',new_image);    
      $(this).dequeue();
    });
    return false;
  });
  
  
  // Showcase
  
  var timerId;
  function cycleShowcase() {
    $('a#next-arrow').click();
    timerId = setTimeout(cycleShowcase,15000);
  }
  timerId = setTimeout(cycleShowcase,15000);
  
  $('div#arrows img').each(function() {
    $(this).css('display','block');
    $(this).show();
  })
  $('a#previous-arrow').click(function() {
    var current = $('div.sidebar-content:visible');
    current.animate({opacity:'0'},250).queue(function() {
      var next = $(this).next('div.sidebar-content');
      if(next.length > 0) {
        next = next[0];
      } else {
        next = $('div.sidebar-content')[0];
      }
      $(this).css('display','none');
      $(next).css('display','block').css('opacity','0').animate({opacity:'1'},250);
      $(this).dequeue();
    });
    clearTimeout(timerId);
    return false;
  });
  $('a#next-arrow').click(function() {
    var current = $('div.sidebar-content:visible');
    current.animate({opacity:'0'},250).queue(function() {
      var next = $(this).prev('div.sidebar-content');
      if(next.length > 0) {
        next = next[0];
      } else {
        items = $('div.sidebar-content');
        next = items[items.length-1];
      }
      $(this).css('display','none');
      $(next).css('display','block').css('opacity','0').animate({opacity:'1'},250);
      $(this).dequeue();
    });
    clearTimeout(timerId);
    return false;
  });

  
  // Handle click on sidebar thumbnails  
  $('.sidebar-thumbnail a').click(function() {
    var me = $(this);
    var new_image = me.attr('href');
    var main_image = me.parent().parent().parent().find('div.main-image img.main');
    main_image.animate({opacity:'0'},250).queue(function () {
      main_image.attr('src',new_image);
      main_image.animate({opacity:'1'},250);
      $(this).dequeue();
    });
    return false;
  });
  
});