$(function() {
  var counter = 0 ;
  $("body").append('<div id="fullsizePreloader"></div>') ;
  //$("#fullsizePreloader").hide() ;
  $("#thumbnails a").each(function() {
    $(this).fadeTo(0, 0.4) ;
    $("#fullsizePreloader").append('<img class="preloaded' + counter + '" src="' + $(this).attr("href") + '" />') ;
    $("#fullsizePreloader img.preloaded" + counter).load(function() {
      $("#thumbnails a").eq($(this).attr("class").substr(9,1)).fadeTo(0, 1) ;
    }) ;
    counter++ ;
  }).click(function() {
    $("#mainpic").attr("src", $(this).attr("href")) ;
		if ($("#fullsize").hasClass('landscape')) {
		  var img = "#fullsizePreloader img[src$=" + $(this).attr("href") + "]" ;
			var padtop = Math.round((365 - $(img).height())/2) ;
			var height = 365 - padtop; 
			$("#fullsize").css('height',height).css('padding-top',padtop) ;
		}

      // Clear out any old play buttons
    clear_play_video();
    
      // If its a video
    if ($(this).attr('data-video') === 'video') {
      $("#fullsize").addClass("video").removeClass("image");
      
        // Work out the height and the width of the video
      var video_width = parseInt($("#videoBox iframe").attr('width'), 10);
      var video_height = parseInt($("#videoBox iframe").attr('height'), 10);
      
        // Add 5 on the height to stop any scroll bars
      video_height += 5; 
      
        // Write in the play button
      var $play_video = $('<a class="play" href="#TB_inline?height='+ video_height +'&width='+ video_width +'&inlineId=videoBox">Play</a>');
      $play_video.bind("click", function(e) {
        e.preventDefault();
      });
      $("#fullsize").append($play_video);
      
        // Thickbox the play button
      tb_init("#fullsize .play");
    }
      // Otherwise its an image
    else {
      $("#fullsize").addClass("image").removeClass("video");
    }
    
    return false;
  }) ;
  
  $(window).ready(function() {
    $("#thumbpics a").fadeTo(1,1) ;
  }) ;
  
  /**
   * Helper functions
   */
   
  function clear_play_video() {
    $("#fullsize .play").remove();
  }
  
}) ;

