$(function() {
  $("body#home").animate({ dummy: 1 }, 300, function() {
    $(this).startAutoSlide();
  });

  $.fn.startAutoSlide = function() {
    $('div#fullsize-image').each(function() {
      if ($(this).children().length > 1)
      {
        $elem = $(this).children('img').eq(1).show().fadeOut(0);
        $elem.css({'z-index': 2 }).fadeIn('slow');
        $(this).children('img').eq(0).fadeOut('fast', function() {
          $(this).css({'z-index': 0}).appendTo($(this).parent('div'));
        });
      } else {
        $elem = $(this).children('img').eq(0).show().fadeIn('fast');
      }
    });
    
    $("body").animate({ dummy: 1 }, 10000, function() {
      $(this).startAutoSlide();
    });
    return this;
  };

  $('div.scroll-container').each(function() {
    $(this).css('width', String($(this).children().length*$(this).parent('div').width())+'px');
  });

  if ($('div#fullsize-image img').length > 1)
  {
    $('a.theme-control').show();
  }
  $('a.theme-control').bind('mousedown', function(e) {
    e.preventDefault();
    var $parent = $(this).parents('div.image-container,div.content-scroll');
    var $scroll = $parent.children('div.scroll-pane');
    var direction = ($(this).hasClass('prev'))? -1 : 1;
    var width = $parent.width();
    var cur = Math.round($scroll.scrollLeft()/width)*width;
    var new_pos = cur+(width*direction);
    var len = $scroll.children('div').children('img').length;
    if (new_pos+width > width*len) new_pos = 0;
    if (new_pos < 0) new_pos = width*(len-1);
    $scroll.scrollTo(new_pos, 800, {easing:'easeInOutCubic', axis: 'x'});
  });
  $('a.start-video-player').bind('click', function(e) {
    e.preventDefault();
    $('a.video-player').toggle();
  });
  $('a.video-player')
  .flowplayer('/media/static/swf/flowplayer.commercial-3.1.5.swf', 
    { key: "#@7a81f22197585145eaf",
      allowfullscreen: true,
      clip: { scaling: 'fit', accelerated: true },
      play: { replayLabel: null, opacity: 0.8 }
     });
});
