// Homepage Banner Rotator
function slideSwitch(target, opacity_toggle) {
  var $active = $('div.active', target);

  if ( $active.length == 0 ) $active = $('div:last', target);

  // use this to pull the images in the order they appear in the markup
  var $next =  $active.next('div').length ? $active.next('div')
    : $('div:first', target);

  // uncomment the 3 lines below to pull the images in random order
  
  // var $sibs  = $active.siblings();
  // var rndNum = Math.floor(Math.random() * $sibs.length );
  // var $next  = $( $sibs[ rndNum ] );

  if ((opacity_toggle == 'no_ie_opacity') && ($('html').hasClass('old-ie'))) {
    $active.hide().removeClass('active');
    $next.show().addClass('active');
  }
  else {
    $active.css({opacity: 1.0}).animate({opacity: 0.0}, 1000);
    $next.css({opacity: 0.0})
      .animate({opacity: 1.0}, 1000, function() {
        $active.removeClass('active');
      }).addClass('active');
  }
};

// Header Logos
function rotateLogos(target, opacity_toggle) {
  var $active = $('ul.active', target);
  
    if ( $active.length == 0 ) $active = $('ul:last', target);
  
    var $next =  $active.next('ul').length ? $active.next('ul')
      : $('ul:first', target);

  
    if ((opacity_toggle == 'no_ie_opacity') && ($('html').hasClass('old-ie'))) {
      $active.hide().removeClass('active');
      $next.show().addClass('active');
    }
    else {
      $active.css({opacity: 1.0}).animate({opacity: 0.0}, 1000);
      $next.css({opacity: 0.0})
        .animate({opacity: 1.0}, 1000, function() {
          $active.removeClass('active');
        }).addClass('active');
    }
} 

var Countdown = {
  tick: function() {
    var dt = Date.parse($('#countdown time').attr('datetime'));
    var now = new Date();
    var diff = this.diff(now, dt);
    $('#countdown .countdown-days').html(diff[0]);
    $('#countdown .countdown-hours').html(diff[1]);
    $('#countdown .countdown-mins').html(diff[2]);
    $('#countdown .countdown-secs').html(diff[3]);
  },
  
  diff: function(from, to) {
    var diff = parseInt(to - from) / 1000;
    if (diff <= 0) {
      return [0,0,0,0];
    } else {
      return $.map([
        diff / (60 * 60 * 24),
        (diff % (60 * 60 * 24)) / (60 * 60),
        (diff % (60 * 60)) / 60,
        diff % 60
      ], function(i) { return Math.floor(i); });
    }
  }
};

$(function() {
	
	// New Date Parse function to allow for ISO-8601 dates, used from:
	// http://zetafleet.com/blog/javascript-dateparse-for-iso-8601
	var origParse = Date.parse;
	Date.parse = function (date) {
		var timestamp = origParse(date), minutesOffset = 0, struct;
		if (isNaN(timestamp) && (struct = /^(\d{4}|[+\-]\d{6})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?))?/.exec(date))) {
			if (struct[8] !== 'Z') {
				minutesOffset = +struct[10] * 60 + (+struct[11]);
				if (struct[9] === '+') {
					minutesOffset = 0 - minutesOffset;
				}
			}
			timestamp = Date.UTC(+struct[1], +struct[2] - 1, +struct[3], +struct[4], +struct[5] + minutesOffset, +struct[6]);
		}
		return timestamp;
	};
	
  Countdown.tick();
  
  // Placeholder
  $("input[placeholder]").placeHeld();
  
  // Initialize homepage banner rotator
  setInterval( "slideSwitch('#banner','no_ie_opacity')", 7000 );
  
  // Races Carousel
  $('#races-carousel ul').jcarousel({
    scroll: 1,
    //auto: 1,
    buttonNextHTML: "<div><span></span><a></a></div>",
    buttonPrevHTML: "<div><span></span><a></a></div>"
  });
    
  // Gallery Carousel
  $('#gallery-carousel ul').jcarousel({
    scroll: 1,
    visible: 1,
    buttonNextHTML: "<div><span></span><a></a></div>",
    buttonPrevHTML: "<div><span></span><a></a></div>",
    itemLoadCallback: function(carousel, state) {
      $('#gallery-counter mark').html(carousel.first);
    }
  });
   
  // Track infobox carousel
  $('.jcarousel-skin-track-logos, .jcarousel-skin-manufacturer-logos').jcarousel({
    scroll: 1,
    //auto: 1,
    buttonNextHTML: "<div><a></a></div>",
    buttonPrevHTML: "<div><a></a></div>"
  });
    
  // Races Checkbox
  
  $("#races-labels ul label input").change(function(e) {
    var label = $(this).parent('label');
    
    if ($(this).is(':checked')) {
      label.addClass('selected');
    }
    else label.removeClass('selected');

    e.stopPropagation();
  });
  
  $("#race-register fieldset label").click(function() {
    var input = $(this).children('input');
    
    if (input.is(':checked')) {
      $(this).addClass('selected');
    }
    else $(this).removeClass('selected');
  });
  
  $("race-register fieldset label input, #races-labels ul label input").click(function(e) {
    e.stopPropagation();
  });
  
  // Tooltips
  $("#race-register fieldset label a[title], #suppliers li a[title], #races-labels label a[title]").tooltip();
  
  // Tabs
  $('#tabs').tabs({ selected: 0 });
  $('#sidetabs').tabs({ selected: 0 });
  $('#tabs1').tabs({ selected: 0 });
  
  // Header Logos
  setInterval( "rotateLogos('#logos','no_ie_opacity')", 5000 );
  setInterval( 'Countdown.tick();', 1000 );
  
  $('img[data-deferred-src]').each( function() {
    $(this).attr('src', $(this).attr('data-deferred-src'));
  });
});
