// Cufon.replace('#section_header,#why_join>h2,#nav_sub>h2');
Cufon.replace('#section_header,#why_join>h2,#nav_sub>h2');

$(function(){
	
	$('#nav').showSubNav();
	
	$('#gallery_images').gallerify();
	
	$('#body_galleries #gallery a').colorboxHelper();
	
	$('#login_form>h2').showHideLogin();
	
});

$.fn.colorboxHelper = function(){
	return this.each(function(){
		var title = $(this).attr('rel');
		$(this).colorbox({title: title});
	});
} 

$.fn.gallerify = function(){
	return this.each(function(){
		var container = $(this);
		var scrollAmount = 864;
		var ul = $('>ul',container);
		var items = $('>li',ul);
		
		var slideGallery = function(e){
			var currentScroll = container.scrollLeft();
			if ( !(e.data.direction=='prev' && currentScroll==0) && !(e.data.direction=='next' && currentScroll+scrollAmount>ul.width()/2) ) {
				container.animate({
					scrollLeft: e.data.direction == 'prev' ? currentScroll-scrollAmount : currentScroll+scrollAmount
				},500);
			}
		}

		container.css({
			height: items.css('height'),
			overflow: 'hidden'
		});
		ul.css({width: items.outerWidth(true) * items.length * 2 + 'px'});

		$('<button id="button_next"><img src="/images/button_next.png" alt="Next set" /></button>')
			.bind('click',{direction:'next'},slideGallery).insertAfter(container);
		$('<button id="button_prev"><img src="/images/button_prev.png" alt="Previous set" /></button>')
			.bind('click',{direction:'prev'},slideGallery).insertAfter(container);
	});
}

$.fn.showSubNav = function(){
	return this.each(function(){
		var sublists = $('>ul>li>ul',this);

		sublists.css('left','auto').hide(); // jump through this hoop cos IE6 complains if set to hidden directly in CSS
		
		sublists.parent().each(function(){
			var timer;
			var ul = $(this).children('ul');
			$(this).mouseenter(function(){
				window.clearTimeout(timer);
				if (!ul.is(':animated')) ul.slideDown();
			}).mouseleave(function(){
				timer = window.setTimeout(function(){
					ul.slideUp();
				},200);
			});
		});

	});
}

$.fn.showHideLogin = function(){
	return this.each(function(){
		var form = $(this).next();
		var cancel = $('<a href="#">Cancel »</a>');
		$('.submit',form).after(cancel);
		
		$(this).add(cancel).click(function(){
			form.toggleClass('visible');
			return false;
		})
	});
}