jQuery(function($){
	var slides = $('#slides');
	var items = slides.children();
	var slider = $('#slider');
	var current, auto, autoN, autoButtons, z = 1;
	
	function stopAuto() {
		if(auto) {
			clearInterval(auto);
			auto = false;
		}
	}
	function switchTo(that) {
		var currentNow = current;
		if(currentNow && currentNow.is('video')) {
			currentNow[0].pause();
		}
		that.css('z-index', z++).hide().fadeIn(500, function() {
			if(currentNow && currentNow != current) {
				currentNow.hide();
			}
			if(that.is('video')) {
				//that[0].play();
			}
		});
		autoButtons.removeClass('open').eq(that.prevAll('a').length).addClass('open');
		if(!currentNow) {
			that.siblings().hide();
		}
		current = that;
	}
	
	items.each(function() {
		var that = $(this);
		slider.append($('<a href="#"></a>').click(function() {
			if(!$(this).is('.open')) {
				switchTo(that);
				$(this).addClass('open').siblings().removeClass('open');
			}
			return false;
		}));
	}).click(function() {
		stopAuto();
	}).not(':first').hide();
	autoButtons = slider.find('a').mouseup(function() {
		clearInterval(auto);
	});
	autoN = slides.is('.random') ? (Math.random() * autoButtons.length) << 0 : 0;
	autoButtons.eq(autoN).click();
	
	if(slides.is('.prevnext')) {
		slider.prepend($('<a class="prev" href="#"></a>').click(function() {
			stopAuto();
			if(current.prev().length > 0) {
				switchTo(current.prev())
			}
			return false;
		})).append($('<a class="next" href="#"></a>').click(function() {
			stopAuto();
			if(current.next().length > 0) {
				switchTo(current.next());
			}
			return false;
		}));
	}
	
	auto = setInterval(function() {
		autoN = (autoN + 1) % items.length;
		autoButtons.eq(autoN).click();
	}, 5000);
	
	
	$('#portfolio a:not(.open)').mouseenter(function() {
		$(this).stop().animate({
			opacity : 1
		}, {
			queue : false,
			duration : 200
		});
	}).mouseleave(function() {
		$(this).stop().animate({
			opacity : 0.35
		}, {
			queue : false,
			duration : 500
		});
	});
});
