$(function(){
	$('body').removeClass('js-disabled').addClass('js-enabled');
	
	Shadowbox.init();

	$('#head_splash_menu').navInit();

	$('#contact_form').highlightAssociatedLabels();
	
	$('dl').toggleable();
	
});

$.fn.navInit = function() {
  return this.each(function(){
    var jump_nav = $('.jump a',this);
    jump_nav.click(function() {
			if (scrolling) window.clearInterval(scrolling);
			scrollSplashTo.call(this)
    });

		function scrollSplashTo() {
      var splash = $("#"+$(this).parents('li').get(0).id.replace(/^nav_/, 'splash_'));
			var splashLeft = splash.parent().children().index(splash) * 920 + 'px';
    
      $("#splash_scroller").animate({scrollLeft: splashLeft}, 500);
    
      jump_nav.parent("li").removeClass("selected");
      $(this).parent("li").addClass("selected");
      this.blur();
    
      return false;
		}
  
    $('#nav_prev', this).click(function() {
			if (scrolling) window.clearInterval(scrolling);
      $('#head_splash_menu .jump li.selected').prev('li').children('a').click();
      return false;
    });
  
    $('#nav_next', this).click(function() {
			if (scrolling) window.clearInterval(scrolling);
      $('#head_splash_menu .jump li.selected').next('li').children('a').click();
      return false;
    });

		// initialise the scroller back to the first on page reload incase of DOM caching
    scrollSplashTo.call($('#head_splash_menu ul.jump a:first'));
  
		// automate the scroller
		var scrolling = window.setInterval(function(){
			currentLi = $('#head_splash_menu .jump li.selected');
			if (currentLi.next('li').length>0) {
				scrollSplashTo.call(currentLi.next('li').children('a'));
			}
			else {
				scrollSplashTo.call($('#head_splash_menu .jump li:first>a'));
			}
		},5000);
  });
}

$.fn.highlightAssociatedLabels = function() {
  var inputs = $('input[type=text],input[type=password],select,textarea', this)
  inputs.focus(function() {
    $('label.selected:not(.no_bg)').removeClass('selected');
    $('label[for='+$(this).attr('id')+']:not(.no_bg)').addClass('selected');
  });

  inputs.blur(function() {
    $('label[for='+$(this).attr('id')+']:not(.no_bg)').removeClass('selected');
  });
}

$.fn.toggleable = function() {
	return this.each(function(){
		$('dd',this).hide();
		$('dt',this).each(function(){
			$(this).addClass('closed').click(function(){
				var thisWasClosed = $(this).is('.closed');
				$('dd:visible').slideUp().prev().removeClass('open').addClass('closed');
				if (thisWasClosed) {
					$(this).removeClass('closed').addClass('open').next('dd').slideDown();
				}

			});
		});
	});
}