$(function() {
	
	if($('div.module_gallery').length > 0) {
		
		gallery = $('div.module_gallery');
		main = gallery.children('div.main');
		thumbs = gallery.children('div.thumbs');
		
		thumbs.data('thumbsPerSlide', 10);
		
		thumbs.prepend('<p class="prev disabled">Previous Images</p>').append('<p class="next' + (thumbs.find('ul li').size() <= thumbs.data('thumbsPerSlide') ? ' disabled' : '') + '">Next Images</p>');
		
		thumbs.children('p.prev, p.next').click(function() {
			
			var self = $(this);
			viewport = self.siblings('div.window');
			
			list = viewport.children('ul');
			
			if(list.is(':animated')) {
				return false;
			}
			
			origOffset = parseInt(list.css('margin-left').replace('px', ''));
			
			if(!viewport.data('offset')) {
				viewport.data('offset', 0);
			}
			
			// if cannot be scrolled
			if(self.hasClass('prev') && origOffset == 0 || (self.hasClass('next') && (viewport.data('offset') + 1) >= (list.children('li').size() / thumbs.data('thumbsPerSlide')))) {
				return false;
			}
			
			offset = (self.hasClass('prev')) ? origOffset + 600 : origOffset - 600;
			
			if(self.hasClass('prev')) {
				viewport.data('offset', viewport.data('offset') - 1);
			}
			else {
				viewport.data('offset', viewport.data('offset') + 1);
			}
			
			// if at beginning, disable prev button
			if(offset == 0) {
				viewport.siblings('p.prev').addClass('disabled');
			}
			else {
				viewport.siblings('p.prev').removeClass('disabled');
			}
			
			// if at end, disable next button
			if((viewport.data('offset') + 1) >= (list.children('li').size() / thumbs.data('thumbsPerSlide'))) {
				viewport.siblings('p.next').addClass('disabled');
			}
			else {
				viewport.siblings('p.next').removeClass('disabled');
			}
			
			// scroll thumbs
			list.animate({marginLeft: offset + 'px'}, 500);
			
		});
		
		thumbs.find('ul li a').click(function() {
			
			element = $(this);
			
			$.ajax({'url': '/ajax.php?action=getGalleryImage', // the replace here fixes IE adding the current url to a relative link automatically, removes everything before ?
					'type': 'POST',
					'data': {'entry_id': element.attr('href').replace(/^(.*)\?gallery=/, '')},
					'dataType': 'json',
					'beforeSend': function() { main.addClass('loading'); },
					'success': function(data) {
						
						$('<img />').bind('load', function() {
										
										main.removeClass('loading').children('img').replaceWith($(this));
										main.children('p.caption').removeClass('empty').text(data.caption);
										
										if(!data.caption) {
											main.children('p.caption').addClass('empty');
										}
										
									})
									.attr('src', data.src);
						
					}});
			
			return false;
			
		});
		
	}
	
});
