jQuery(document).ready(function(){
	// image slider
	viewer_images = $('.gallery-viewer img');
	if(viewer_images.length > 1) {
		// create gallery nav bar
		navbar = '<ul class="gallery-nav">';
		for(i=0; i < viewer_images.length; i++) {
			navbar += '<li'+(i == 0 ? ' class="active"' : '')+'><a href="#">'+ (i + 1) +'</a></li>';
		}
		navbar += '</ul>';
		$('.gallery-viewer').parent().after(navbar);
		$('.gallery-nav').hide();

		// assign slider functions
		active = 0;
		width = $('.gallery-viewer').width();
		sliding = false;
		$('.gallery-nav li a').each(function(i){
			// assign position reference
			$(this).attr('number',i);
			$(this).click(function(){
				if(sliding) { return false; } // don't do anything if we're already on the move
				number = $(this).attr('number'); // grab position reference

				if(active == number) { return false; } // if the active button is clicked, do nothing
				sliding = true; // enter sliding mode

				if(active < number) { // move to the right
					distance = ((active * width) - (number * width));
				}
				else { // move to the left
					distance = ((active * width) - (number * width));
				}
				$('.slider').animate({"left":'+='+distance},'slow','swing'); // slide...

				// switch active link styles
				$('.gallery-nav a[number="' + active +'"]').parent('li').removeClass('active');
				$(this).parent('li').addClass('active');

				active = number; // set new active
				sliding = false; // exit sliding mode
				return false; // return false so link doesn't activate
			});
		});
	}	

    $(".gallery").hover(function()
	{ }, function()
	{
        $(".gallery-previous").hide();
        $(".gallery-next").hide();
	});
	$(".gallery-previous").click(function()
	{
		$('.gallery-nav a[number="' + (parseInt(active)-1) + '"]').click();
		$(".gallery").mousemove();
	});
	$(".gallery-next").click(function()
	{
		$('.gallery-nav a[number="' + (parseInt(active)+1) + '"]').click();
		$(".gallery").mousemove();
	});
	$(".gallery").mousemove(function(e)
	{
		var xPos = (e.pageX - $(this).position().left);
		$(this).css('cursor', 'default');
		if (xPos < (parseInt($(this).width())/2) && active > 0)
		{
			$(".gallery-previous").show();
			$(this).css('cursor', 'pointer');
		}
		else
		{
            $(".gallery-previous").hide();
        }
		if (xPos > (parseInt($(this).width())/2) && active < (parseInt($(".slider").find('li').length)-1))
		{
			$(".gallery-next").show();
			$(this).css('cursor', 'pointer');
		}
		else
		{
            $(".gallery-next").hide();
        }
	});
});
