// JavaScript Document
var arrPhotos = document.getElementsByName('photo[]');
var selectedPhoto = 0;
var transLock = false;
var timerSpeed = 6000;

(jQuery.noConflict())(function($)
{
	for(i = 0; i < arrPhotos.length; i++)
	{
		$('#btn-container').append('<img class="btn-nav" src="images/btn-nav.png" id="btn-' + i + '" />');	
	}
	
	$('.btn-nav').click(function()
	{	
		if(transLock) return; 

		transLock = true; 
		selectedPhoto = $(this).attr('id').replace('btn-','');
		moveToImg(selectedPhoto);
	});
	
	$('#btn-previous').hide();
	$('#btn-next').hide();
	
	$('#btn-previous').click(function()
	{
		if(transLock) return; 
		
		selectedPhoto--;
		if (selectedPhoto < 0) selectedPhoto = arrPhotos.length - 1;

		transLock = true; 
		moveToImg(selectedPhoto);
	});
	
	$('#btn-next').click(function()
	{
		if(transLock) return; 
		
		selectedPhoto++;
		if (selectedPhoto >= arrPhotos.length) selectedPhoto = 0;

		transLock = true; 
		moveToImg(selectedPhoto);
	});
	
	$('#frame').hover(frameIn, frameOut);
	$('#frame').mousemove(frameMove);
	
	moveToImg(selectedPhoto);
	
	/** FUNCTIONS **/
	function frameMove(e)
	{
		var x = e.pageX - this.offsetLeft;
		var y = e.pageY - this.offsetTop;
		
		//$('#debug').html('X=' + x + ' Y=' + y);

		if (x / 690 < (375 - y) / 375)
		{
			$('#btn-previous').show();
			$('#btn-next').hide();
		}
		else
		{
			$('#btn-previous').hide();
			$('#btn-next').show();
		}
	}

	function frameIn(e)
	{
	}

	function frameOut(e)
	{
		$('#btn-previous').hide();
		$('#btn-next').hide();
	}

	function moveToImg(id)
	{	
		$('#caroussel-right').fadeOut(500);
		$('#caroussel-left').fadeOut(500);
		
		$('#transition-container').animate({'left': -(id * 690) + 'px'}, 750, 'swing', function()
		{
			for(i = 0; i < arrPhotos.length; i++) $("#btn-"+i).attr('src','images/btn-nav.png');	
			$('#caroussel-right').html($('#caption-'+id).html());
			$("#btn-"+id).attr('src','images/btn-nav-selected.png');																					
			transLock = false;
			myTimer.reset(timerSpeed);
		});
		
		$('#caroussel-right').fadeIn(1500);
		$('#caroussel-left').fadeIn(1500);
	}

	var myTimer = $.timer(timerSpeed, function (timer)
	{
		if (transLock) return; 

		transLock = true; 
		selectedPhoto++;
			
		if(selectedPhoto > arrPhotos.length - 1) selectedPhoto = 0;
		moveToImg(selectedPhoto);
	});
	
});


