var ControllerPortfolio = {
	
	timer: null,
	imagesArray: [],
		
	init: function()
	{
		this.addStyles();
		this.preloadImages();
		$('#portfolio .item a').mouseover(function() {
			ControllerPortfolio.handleMouseSelection(this);
		});
		$('#portfolio .item img').mouseover(function() {
			ControllerPortfolio.startSlideshow(this);
		});
		$('#portfolio .item img').mouseout(function() {
			ControllerPortfolio.stopSlideshow();
		});
	},
	
	addStyles: function()
	{
		$('#portfolio .item').each(function(index, item) {
			if (index % 2 == 1)
				$(item).addClass('lastInRow');
		});
	},
	
	preloadImages: function()
	{
		$('.linksWrapper a').each(function (index, item) {
			var rel = $(this).attr('rel');
			var preloadedImage = document.createElement('img');
			preloadedImage.src = rel;
			ControllerPortfolio.imagesArray.push(preloadedImage);
		});
	},
	
	setNextPicture: function(current) 
	{
		var next = $(current).next();
		if (next.length == 0)
			next = $(current).siblings('a:first');
		
		this.handleMouseSelection(next);
		
		if (this.timer)
			this.timer = setTimeout(function() {ControllerPortfolio.setNextPicture(next)}, 1000);
	},
	
	startSlideshow: function(img)
	{
		this.timer = setTimeout(function() {ControllerPortfolio.setNextPicture($(img).parent().find('a.active'))}, 0);
	},
	
	stopSlideshow: function()
	{
		clearTimeout(this.timer);
	},
	
	handleMouseSelection: function(a)
	{
		if ($(a).hasClass('active')) 
			return false;
		
		$(a).siblings("a").removeClass('active');
		$(a).addClass('active');
		
		var newSrc = $(a).attr('rel');
		var img = $(a).parent().siblings("img:first");
		
		$(img).attr('src', newSrc);
	}
}

$(document).ready(function() {
	ControllerPortfolio.init();
});
