$(function() {
	if($('body').is('#homepage')) {
		var overlay = $('#overlay').delay(100),
			main = $('#main'),
			site = $('nav,footer').css('opacity',0);
		$.when(overlay.hasLoaded()).done(function() {
			overlay.animate({backgroundColor:'#fff'},function() {
				$.when(main.hasLoaded()).done(function() {
					overlay.fadeOut(1000,function() {
						site.delay(500).fadeTo(2000,1);
						setInterval(function() {
							var cur = main.children(':visible').fadeOut(2000),
								next = cur.next();
							next.length || (next = main.children().eq(0));
							next.fadeIn(2000);
							
						},5000);
						
					});
				});
			}).delay(600);			
		});
		main.children().eq(0).siblings().hide();
	} else if($('body').is('.section-collections')) {
		var collections = $('.collection').hide();
		$(window).resize(function() {
			collections.css('margin-left',$(window).width()/2-254);
		}).resize();
		var controls = $('<div id="controls"><a href="#" id="controls-next">«</a><a href="#" id="controls-prev">»</a></div>'),
			active = $(),
			image = $();
		$('#collection-list a').click(function() {
			active.removeClass(active);
			active = $(this).addClass('active');
			var collection = $(active.attr('href'));
			controls.insertAfter(active);
			collections.fadeOut();
			collection.css('left',0).fadeIn();
			image = collection.find('img').eq(0).fadeTo(500,1);
			return false;
		}).eq(0).click();
		$('.collection li img').click(function() {
			image.fadeTo(500,0.3);
			image = $(this).fadeTo(500,1);
			image.closest('.collection').animate({left:-$(this).position().left});
		});
		controls.children().click(function() {
			var direction = $(this).is('#controls-next') ? 'prev' : 'next';
			image.parent()[direction]().children().eq(0).click();
			return false;
		});
		
	}
});

$.fn.extend({
	hasLoaded : function() { // when all images have loaded
		var images = this.find('img').toArray(), // find all images
			load = function(src) { // function to load one image
				return $.Deferred(function(task) { // we create a deferred
					var image = new Image(); // that creates a new image element
					image.onload = function () { task.resolve(image); } // and either resolves when the image loads
					image.onerror = function () { task.reject(); } // or aborts the task
					image.src = src; // then sets the src after the event is attached
				});
			},
			queue = new Array(); // a queue to hold all the promises
		$.each(images,function() { // with each image
			queue.push(load(this.src)); // create a deferred that it will load
		});
		return $.when.apply(queue); // and send back one promise that aggregates the queue of deferreds
	}
});
