$(document).ready(function(){

// Hide all main images, except first.
	$('#image_active li:not(:first)').hide();
	
// Does the gallery need to display arrows?
	var galCount = $('.gallery_nav li').length;
	if(galCount > 4){
		$('<a href="#" id="prev" class="arrow">PREV</a><a href="#" id="next" class="arrow">NEXT</a>').insertBefore('#image_active');
		$('.range_main #range_gallery .gallery_nav_container').css('margin-left','37px');
	}
	
// Set appropriate gallery navigation width
	var thumbWidth = 124;
	var galWidth = galCount * thumbWidth;
	$('.gallery_nav').css('width', galWidth + "px");

// Gallery navigation control.	
	$('#range_gallery .arrow').bind('click',function(){	
		var $nav = $('.gallery_nav');										
		var direction = $(this).attr('id');
		var navigationWidth = $($nav).css('width').replace("px", "");
			navigationWidth = -navigationWidth + 550;
		
		var currentPos = $nav.data('currentPos');
	    if (currentPos == undefined) {currentPos = 0;}
		
		if(direction == 'prev' && currentPos != 0){
			currentPos += 118;
		}
		else if(direction == 'next' && currentPos > navigationWidth){
			currentPos -= 118;
		}
		$nav.stop().animate({left: currentPos}, 400);
		$nav.data('currentPos', currentPos);
	});
	
// Active image control.
	$('#range_gallery li').live('click',function(){
		
		var $visible_img = $('#image_active li:visible').attr('rel');
		var $clicked_img = $(this).attr('rel');

		if($clicked_img != $visible_img){
			$('#image_active li:visible').fadeOut(800);
			$('#image_active li[rel="' + $clicked_img + '"]').fadeIn(800);
		}
		
	});

});
