jQuery(document).ready(function($) {
	var imgsPerPage = 8;
	
	var numImages = $('li.viewerBtn').size();
	if (numImages > imgsPerPage) { 
		$('span#nextModal').show(); 
	} else { 
		$('span#nextModal').hide(); 
		$('div#galleryTopModal').hide();
/*		$('ul#listModal').css('margin', '0 auto 0 auto');*/
	}
	$('span#backModal').hide();
	
	var currentPage = 0;
	var lastPage = Math.ceil(numImages / imgsPerPage) - 1;
	
	$('div.product-img-box li').click(function(){
		currentPage = getPage($(this).index());
		scrollToPage(currentPage, true);
		setButtons();
		setImage($(this).index());
		showModal();
		$('div.informational').append($(this).index());
	});
	
	$('img#image').click(function(){
		setImage(0);
		showModal();
	});
	
	$('div#closeMe').click(function(){
		$('div#sdg_modal').hide();
		scrollToPage(0);
		currentPage = 0;
	});
	
	$('span#backModal').click(function(){
		if(currentPage > 0) { currentPage--; }
		setButtons();
		scrollToPage(currentPage);
	});
	
	$('span#nextModal').click(function(){
		if(currentPage < lastPage) { currentPage++; } else { currentPage = lastPage; }
		setButtons();
		scrollToPage(currentPage);
	});
		
	function setImage(id){
		$('li.viewerBtn').removeClass('active').eq(id).addClass('active');
		var thisImg = $('ul#imgs li').eq(id).html();
		$('div#mainImage').html(thisImg);
	}
	
	function showModal(){
		var width = $(document).width();
		var height = $(document).height();
		$('div#sdg_modal').css('width', width).css('height', height).show();
	}
	
	function scrollToPage(page, direct){
		setBullets();
		var scrollAmt = page * 760 * -1;
		if (direct){
			$('ul#listModal').css('margin-left', scrollAmt);
		} else {
			$('ul#listModal').animate({
				opacity: 1,
				marginLeft: scrollAmt
			}, 500);
		}
	}
	
	function getPage(index){
		var thisPage = Math.ceil((index + 1) / imgsPerPage) - 1;
		if (thisPage < 0) thisPage = 0;
		return  thisPage;
	}
	
	function setButtons(){
		if(currentPage > 0) { $('span#backModal').show(); } else { $('span#backModal').hide(); }
		if(currentPage < lastPage){ $('span#nextModal').show(); } else { $('span#nextModal').hide(); }
	}
	
	function setBullets(){
		var elements = "";
		var imgSrc = "";
		for (i = 0; i <= lastPage; i++) {
			if(i == currentPage){
				imgSrc = "/skin/frontend/dreamgear/default/images/gallery/bullet_black.png";
			} else {
				imgSrc = "/skin/frontend/dreamgear/default/images/gallery/bullet_white.png";
			}
			elements += "<img src=\""+imgSrc+"\" alt=\"Gallery Pager\" />";
		}
		$('div#galleryTopModal').html(elements);
	}
});