var paused = true;
var max    = 12;

function buildPage(file) {

	var targetPage = $.query.get('page');
	if (targetPage == undefined | targetPage == '') { targetPage = 1; }

	// TODO: make sure if targetPage > # of possible pages, we're still ok

	$.getJSON(file, function(data) {
		var multiplePages = Math.ceil(data.image.length/max) > 1;
		for(var lastImage = max; lastImage - max < data.image.length; lastImage = lastImage + max) {
			if (multiplePages == true) {
				if (lastImage % max == 0) {
					var page  = lastImage / max;
					if (page == targetPage) { 
						$('<li class="selected">' + page + '</li>').appendTo('#pages'); 
					} else {
						$('<li><a href="' + buildPageLink(page) + '" class="pager" >' + page + '</a></li>').appendTo('#pages');
					}
				}
			}
			if (lastImage / max == targetPage) {
				buildSlides(data, lastImage - max, lastImage -1);
			}
                } 
		

	});

}

function buildPageLink(index) {
	return $.url.attr("path") + "?page=" + index;
}


function buildSlides(images, first, last) {

	var image 	= [];
	var highest	= 0;
	var remaining	= 0;

	if (images.image.length > 0) {

		$('#slides').empty();

// Slides not currently loading all the way, or not sizing
// I can restore it by setting cycle to fit slides and setting the .pic img class to width:480 instead of auto

		for(var idx = first; idx <= last && idx < images.image.length; idx++) {

			remaining = remaining + 1;

			$('#nav1').append('<li><a href="#" style="width:80px;height:80px;background-image:url(\'' + getThumb(images.image[idx].url, 'thumbs') + '\')" /></li>');

			image[idx] = new Image();
			image[idx].src = images.image[idx].url;

			var tag = $('<img src="' + images.image[idx].url + '" style="visibility:hidden" />');
			$('#slides').append(tag);

			$(image[idx]).bind("load", {imageTag: tag}, function(e) {
				remaining = remaining -1;
				if (remaining == 0) {
					startCycle();
					$('#slides img').css('visibility', 'visible');
				}
			});
		}

	}

}

	function startCycle() {
		$('#slides').cycle({
			fx:	'fade',
			speed:	'fast',
			timeout: 2500,
			pager:	'#nav1',
			fit:			0,
			containerResize: 	1,

			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(i, slide) {
				return '#nav1 li:eq(' + i + ') a';
			}

		});


		$('#start').click(function() {
			if (paused) {
				$('#start').html('stop slideshow');
				$('#slides').cycle('resume');
			} else {
				$('#start').html('start slideshow');
				$('#slides').cycle('pause');
			}
			paused = !paused;
		});

		$('#slides').cycle('pause');
	}


function getThumb(source, thumbsFolder) {
  return source.replace('images/', thumbsFolder + '/');
}