/**
 * Simple Spotlight para Malcom
 * nommac.net
 */

$(document).ready(function()
{
	// Si existe el spotlight
	if ($('#spotlight').length != 0)
	{
		var autoTime= 11000;
		
		var $spotlight = $('#spotlight');
		var $container = $('#spotlight div.inside');
		var $slides = $('#spotlight article');
		
		var $video = $('video');
		
		$slides.filter(':not(.active)').css({ opacity : 0});
		
		var anchoSpotlight = $spotlight.width();
		
		$controls = $('#spotlight .control li a');
		
		var auto = new AutoInterval(autoTime, $controls);
		auto.start();
		
		$video.bind('play', function(e) { auto.clear(); });
		$video.bind('pause stop', function(e) { auto.clear(); auto.start(); });
		
		$controls.bind('click', function(e)
		{
			e.preventDefault();
			
			if ($container.is(':animated')) { return; }
			
			auto.clear();
			$video.trigger('pause');
			
			$controls.removeClass('active');
			$(this).addClass('active');
			
			$previous = $slides.filter('.active');
			$previous.animate({ opacity : 0 }, 900, 'easeInOutSine', function()
			{
				$(this).css({'visibility' : 'hidden'});	
			});
			
			$destination = $($(this).attr('href'));
			$destination.css({'visibility' : 'visible'});
			$destination.animate({opacity : 1}, 400, 'easeInOutSine', function()
			{
				$(this).css('filter','');
				$slides.removeClass('active');
				$destination.addClass('active');
			});
			
			var posDestination = parseInt($destination.position().left);
			
			$container.animate({ left : -posDestination }, 1000, 'easeInOutSine', function()
			{
				auto.start();
			});
			
		});

		

	}
	
});

// Clase para objeto que controla el slide automático
function AutoInterval(time, $controls)
{
	var that = this;
	this.timeoutID = 0;
	
	this.controls = $controls;
	this.autoTime = time;
	this.start = function()
	{
		window.clearTimeout(that.timeoutID);
		
		that.timeoutID = window.setTimeout(function()
		{
			$thisControls = that.controls;
			var totalIndex = $thisControls.length-1;
			
			$activeControl = $thisControls.filter('.active');
			var activeIndex = $thisControls.index($activeControl);
			
			if (activeIndex >= totalIndex) 
			{
				$($thisControls.get(0)).trigger('click');
			}
			else
			{
				$($thisControls.get(activeIndex+1)).trigger('click');
			}
			that.start();
			
		}, time);
	}
	this.clear = function()
	{
		window.clearTimeout(that.timeoutID);
	};
}



