/*
07/09/2009
Baglioni - gallery application JS file
author: Alessandro Chinazzo
*/

function showPrev() {
	$galleryLeft = $("#gallery ul").position().left;
	$shift = $galleryLeft + ($left*4);
	if ( $galleryLeft < 0 ) {
		$("#gallery ul").animate({ left: $shift }, 300, function(){
			$btn_next.css('visibility', 'visible');
			if ( $shift == 0 )
				$btn_prev.css('visibility', 'hidden');
		} );
	}
}

function showNext() {
	$shift = $("#gallery ul").position().left - ($left*4);
	if ( Math.abs($shift) < $totalWidth ) {
		$("#gallery ul").animate({ left: $shift }, 300, function(){
			$btn_prev.css('visibility', 'visible');
			if ( ($totalWidth - Math.abs($shift)) <= ($left*4) )
				$btn_next.css('visibility', 'hidden');
		} );
	}
}

$(document).ready(function(){
	
	$('img.bg').maxImage({
	  	//isBackground: true,
		topSpace: 85,
		bottomSpace: 10,
		leftSpace: 30,
		rightSpace: 30,
	  	//verticalAlign: 'top',
		//zIndex: -10,
		horizontalAlign: 'center',
		maxFollows: 'both'
	});
	
	$('p.active a').click(function(){
		$('#nav').toggle();
		return false;
	});
	
	$('#gallery a').click(function(evt){
		_to_display = $(this);
		$('.bg').fadeOut(function(){
			var preloaded = new Image();
			$(preloaded).load(function(){
				$('.bg').remove();
				old_id = _to_display.find('img').attr('id');
				index = old_id.substring(old_id.indexOf('-')+1);
				$('<img class="bg" id="image-' + index + '" />')
				.attr('src', preloaded.src)
				.hide()
				.appendTo('body');
				
				$('.bg').maxImage({
					horizontalAlign: 'center',
					topSpace: 85,
					bottomSpace: 10,
					leftSpace: 30,
					rightSpace: 30,
					restart: true,
					maxFollows: 'both'
				});
			})
			.attr('src', _to_display.attr('href'))
			.fadeIn();
		});
		evt.stopPropagation();
		//$(this).parent().siblings().removeClass('current');
		//$(this).parent().addClass('current');
		return false;
	});
	
	if ( $('#gallery ul li').size() > 4 ) {
		
		$left = $('#gallery ul li').width()+10;
		
		$('#gallery ul').css('width', $('#gallery ul li').size()*($('#gallery ul li').width()+15));
		$totalWidth = $('#gallery ul').width();
		
		$('#gallery-container').wrap( $('<div id="wrapper" class="clearfix" style="position: relative" />') );
		
		$btn_prev = $('<a id="btn_prev"><img src="/images/ico-arrow-left.png" alt="" /></a>')
		.appendTo('#wrapper')
		.css({
			visibility: 'hidden',
			top: $('#wrapper').height()/2 - 9,
			left: '-5px'
		})
		.click( showPrev );
		
		$btn_next = $('<a id="btn_next"><img src="/images/ico-arrow-right.png" alt="" /></a>')
		.appendTo('#wrapper')
		.css({
			visibility: 'visible',
			top: $('#wrapper').height()/2 - 9,
			right: '-5px'
		})
		.click( showNext );
		
	}
	
});