$(document).ready(function(){
	
	$panels = $('#thumbnails');
	$leftbtn = $('#thumbs_left');
	$rightbtn = $('#thumbs_right');
	$mainImages = $('#main_images');
	
	galleryWidth = 952;
	imagesPerPage = 14;
	currentPosition = 0;
	currentImage = 0;
	numberOfImages = $panels.children().length;
	numberOfPages = numberOfImages/imagesPerPage;
	
	
	$(this).keypress(function (e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		
		 if(code == 37) { //LEFT
			if(currentImage>0){
				currentImage--;
			}
			selectItem(currentImage);
		 }
		 
		 if(code == 39) { //RIGHT
		  	if(currentImage<Math.floor(numberOfImages)){
				currentImage++;
				selectItem(currentImage);
			}
		 }
	});

	
	
	//selecting function
	function selectItem(index){
		currentImage=index;
		
		$panels.children().each(function() {
				$(this).removeClass('active');	
		});
		
		
		$panels.children().eq(index).addClass('active');		
		
		$mainImages.animate({'marginLeft' : 980*(-index)}, 450, "linear");
	}
	

	//assign the links to each thumbnail
	$panels.children().each(function() {
        var child = $(this);
		
		child.click(function (e){
			var pos = $(this).prevAll('li').length;
			selectItem(pos);			  
		});
	});
	

	
	//sliding functions...
	function slidePage(page){
		$panels.animate({'marginLeft' : galleryWidth*(-page)}, 350, "linear");
	}	
	$leftbtn.click(function (e) {
		if(currentPosition>0){
			currentPosition--;
		}
		slidePage(currentPosition);
		
	});
	
	$rightbtn.click(function (e) {
		if(currentPosition<Math.floor(numberOfPages)){
			currentPosition++;
			slidePage(currentPosition);
		}
	});

	//turn first image on at start...
	 $("#thumbnails li:first-child").addClass('active');
});