var loader = '/application/admin/images/ajax-loader.gif';


$(document).ready(function()
{
	// for each image
	$('.nimg').each(function()
	{
			// on click
			$(this).click(function(ev)
			{
				// set main this image to main image (leader_picture .imgfl)
				ev.preventDefault();
				nlink = $(this).find('a');
				$('.newspic .imgfl').fadeOut('slow', function() {
    				// Animation complete.
					$('.heightr').css('position', 'relative');
					html = buildLoader();
					$('.heightr').append(html);
					centerLoader();
					$('.imageloader').show();
					$(this).attr('src', nlink.attr('href'));
					$(this).load(function()
					{
						$('.imageloader').hide();
						$('.newspic .imgfl').fadeIn('slow', function() {
        				// Animation complete
      					});
					});
  				});
				
			});
	});
	
	// sets the total width of canvas
	twidth = 0;
	thumbw = $('.nimg').outerWidth(true);
	mar = $('.nimg').outerWidth(true) - $('.nimg').width();
	maskw = $('.gal_o_flow').width() + mar;
	$('.nimg').each(function(i)
	{
		// add image plus any padding .width
		twidth += thumbw;	   
	});
	
	// sets the canvas to be wide enough to hold all images
	$('.newspic .canvas').width(twidth);
	
	// if the canvas is bigger than is visible
	if($('.newspic .canvas').width() > maskw)
	{
		// click on right arrow
		$('.rarrow').click(function()
		{
			// if (canvas is not at end)
			pos = parseInt($('.newspic .canvas').css('left'));
			if(0 < pos + (twidth - maskw) )
			{
				moveImages(pos, thumbw, 'r');
			}
		});
		
		// click on left arrow
		$('.larrow').click(function()
		{
			// if (canvas is not at end)
			pos = parseInt($('.newspic .canvas').css('left'));
			if(pos < 0)
			{
				moveImages(pos, thumbw, 'l');
			}
	
		});
	}
	
	

});

function moveImages(pos, thumbw, dir) {
	if(dir == 'l')
	{
		c = pos + thumbw;
	}
	if(dir == 'r')
	{
		c = pos - thumbw; 
	}
 	$('.newspic .canvas').animate({left: c}, 1000, 'easeOutCirc' );
};

function buildLoader() {
var html = '<img src="' +loader + '" class="imageloader" style="position:absolute; display: none; top: 0; left: 0;" />';
return html;	
};

function centerLoader()
{
	loaderWidth = $('.imageloader').width();
	parentWidth = $('.imageloader').parent().width();
	
	loaderHeight = $('.imageloader').height();
	parentHeight = $('.imageloader').parent().height();
	
	centered = (parentWidth - loaderWidth) / 2;
	vcentered = (parentHeight - loaderHeight) / 2;
	
	$('.imageloader').css({'left': centered, 'top': vcentered});
}
