var pics;

var PICS_PER_PAGE = 20;
var PICS_PER_ROW = 4;
var PIC_FILE_URL = "/girls/photos/picfile.php";
var PAGES_IN_NAV = 5; // The number of pages listed in nav bars (other than first and last, including current page)
var PLUS_ONE_PAGE = PICS_PER_PAGE - 1; // Used to get to the next page in the index math

var num_pages;
var current_page = 1;

var preloaded_thumbs = {};
var page_load_status = {};

var makePageTimer;
var loadingImageShown = false; // Is the loading image current on the page?

// Stuff for page number passed via the anchor tag (#)
var initial_page;
var initial_page_selected = false;

// Document load
$(document).ready(function() {
	// Load the JSON first
	jQuery.getJSON ("/girls/photos/global/ajax/albums.php?aid=" + $("#aid").text(), function (json) {
		pics = json;
		JSONloaded();
	});
});

// Json loaded, ready to continue
function JSONloaded() {
	// How many pages will we need?
	num_pages = Math.ceil( pics.length / PICS_PER_PAGE );
	
	// Check for album page
	var myFile = document.location.toString();
	if (myFile.match('#')) { // the URL contains an anchor
		var myAnchor = (myFile.split('#')[1] == "" || myFile.split('#')[1] == null) ? 1 : myFile.split('#')[1];
		initial_page = parseInt(myAnchor);
		initial_page_selected = true;			
	}
	
	if ( num_pages == 1 ) { // 1 page
		// Find out what to load
		startIndex = 0;
		finishIndex = pics.length - 1;
		doLoad(startIndex, finishIndex);
		
		doPageNav();
		makePage(current_page);
	} else if ( initial_page_selected ) { // Check if we have an anchor to deal with
		goToPage(initial_page);
	} else if ( num_pages > 1 ) { // > 1 page
		// Load first page
		startIndex = 0
		finishIndex = PICS_PER_PAGE;
		
		doLoad(startIndex, finishIndex);
		
		// Set everything up
		doPageNav();
		makePage(current_page);
		
		// Load next page
		loadForPage();
	} else {
		$("#pic-page").html("<b>Sorry, no pictures at this time.</b>").css({textAlign: "center"});
		$(".left, .center, .right").html("");
	}	
}

// Duh..
function getNextPage() {
	return current_page + 1;	
}

// Again..
function getPrevPage() {
	return current_page - 1;	
}

// Test to see if an image has been loaded
function imgLoaded(img) {
	if ( preloaded_thumbs[img] == null || !preloaded_thumbs[img].complete )
		return false;
	else
		return true;
}

// Test to see if all img thumbs have been loaded
function checkPageLoaded(page) {
	var start_index; var finish_index;
	if ( current_page == num_pages || num_pages == 1 ) { // Special case for one page only or last page
		start_index = (page * PICS_PER_PAGE) - PICS_PER_PAGE;
		finish_index = pics.length - 1;	
	} else {	
		start_index = (page * PICS_PER_PAGE) - PICS_PER_PAGE;
		finish_index = start_index + PLUS_ONE_PAGE;
	}
	
	for (i = start_index; i <= finish_index; i++) {
		if ( !imgLoaded(i) )
			return false;
	}
	return true;
}

// Do the actual loading
function doLoad(start_index, finish_index) {
	// Load only if it hasn't been loaded
	for ( z = start_index; z <= finish_index; z++ ) {
		if ( !imgLoaded(z) ) {
			preloaded_thumbs[z] = new Image();
			$(preloaded_thumbs[z]).attr('src', PIC_FILE_URL + "?pid=" + pics[z].pid + "&thumb" );
		}
	}
}

function loadNextPage() {
	if ( !checkPageLoaded(getNextPage()) ) {
		if ( pics.length >= ( getNextPage() * PICS_PER_PAGE ) ) { // We'll have more pages after this
			start_index = (getNextPage() * PICS_PER_PAGE) - PICS_PER_PAGE;
			finish_index = start_index + PLUS_ONE_PAGE;
		} else {  // Last page, tailor indicies to fit
			start_index = (getNextPage() * PICS_PER_PAGE) - PICS_PER_PAGE;
			finish_index = (pics.length - 1)
		}
		
		doLoad(start_index, finish_index);
	}
}

function loadPrevPage() {
	if ( !checkPageLoaded(getPrevPage()) ) {		
		start_index = (current_page - 2) * PICS_PER_PAGE; // We multiply by PICS_PER_PAGE which assumes that each page has PICS_PER_PAGE in it, so we need to go two pages back to get the start index
		finish_index = start_index + PLUS_ONE_PAGE; // Because its zero indexed we dont need to add PICS_PER_PAGE
		
		doLoad(start_index, finish_index);
	}
}

// Load for current page
function loadForPage() {
	var start_index; var finish_index;
	if ( current_page != 1 && current_page != num_pages ) { // Not the first or last page
		loadNextPage();
		loadPrevPage();
	} else if ( current_page == 1 ) {
		loadNextPage();
	} else { // Last page
		loadPrevPage();
	}
}

function loadSpecificPage(page) {
	if ( page == num_pages ) { // Special case for last page
		start_index = (page * PICS_PER_PAGE) - PICS_PER_PAGE;
		finish_index = pics.length - 1;	
	} else {	
		start_index = (page * PICS_PER_PAGE) - PICS_PER_PAGE;
		finish_index = start_index + PLUS_ONE_PAGE;
	}
	doLoad(start_index, finish_index);
}

function doPageNav() {
	var nav_string = "";
	
	if ( num_pages <= PAGES_IN_NAV ) {  // For the number of pages being less than the max number of PAGES_IN_NAV (ie only two pages)
		for ( i=1; i <= num_pages; i++ ) {
			class_html = (i == current_page) ? "class='current'" : "";
			nav_string += "<a " + class_html + " href='javascript: goToPage(" + i + ")'>" + i + "</a>";
			
			
			if ( i != num_pages ) {
				nav_string += " ";
			}
		}
	} else if ( current_page - 2 <= 1 ) { // The sequence will go (1, 2, 3, 4) because the page is two away
		// Print the first pages up to PAGES_IN_NAV:
		for ( i=1; i <= PAGES_IN_NAV; i++ ) {
			if ( i <= num_pages ) { // Make sure we dont overrun the page count
			
				class_html = (i == current_page) ? "class='current'" : "";
				nav_string += "<a " + class_html + " href='javascript: goToPage(" + i + ")'>" + i + "</a>";
				
				
				if ( i != PAGES_IN_NAV ) {
					nav_string += " ";
				}
			}
		}
		
		nav_string += (num_pages > PAGES_IN_NAV) ? " ... <a href='javascript: goToPage(" + num_pages + ")'>" + num_pages + "</a>" : "";
	} else if ( current_page + 2 >= num_pages ) { // Sequence will have last PAGES_IN_NUM pages ( 5, 6, 7, 8, 9 ) where num_pages = 9
		nav_string = "<a href='javascript: goToPage(1)'>1</a> ... ";
		
		for ( i = num_pages - (PAGES_IN_NAV - 1); i <= num_pages; i++ ) {
			class_html = (i == current_page) ? "class='current'" : "";
			nav_string += "<a " + class_html + " href='javascript: goToPage(" + i + ")'>" + i + "</a>";
		}
	} else { // Its in the middle somewhere
		nav_string = "<a href='javascript: goToPage(1)'>1</a> ... ";
		for ( i = current_page - 2; i <= current_page + 2; i++ ) { // Start two pages back, go to pages forward
			class_html = (i == current_page) ? "class='current'" : "";
			nav_string += "<a " + class_html + " href='javascript: goToPage(" + i + ")'>" + i + "</a>";
			
			if ( i != (current_page + 2) ) {
				nav_string += " ";
			}
		}
		
		nav_string += " ... <a href='javascript: goToPage(" + num_pages + ")'>" + num_pages + "</a>";
	}
	
	$(".center").html(nav_string);
}

function makePageHtml(page) {
	// Make the stuff -- We make the holder first, then reloop and inject the image elments into the dom with
	// the class name of img-index# (index# from the pics object)
	if ( current_page == num_pages || num_pages == 1 ) { // Special case for one page only or last page
		start_index = (page * PICS_PER_PAGE) - PICS_PER_PAGE;
		finish_index = pics.length - 1;	
	} else {	
		start_index = (page * PICS_PER_PAGE) - PICS_PER_PAGE;
		finish_index = start_index + PLUS_ONE_PAGE;
	}
	
	html = "<table class='pic-list'>";
	
	rowCount = 0;  // We count up to PICS_PER_ROW pictures per row
	for ( i = start_index; i <= finish_index; i++ ) {
		if ( rowCount == 0 )
			html += "<tr>";
			
		titleText = ( pics[i].title == null ) ? "" : pics[i].title;
		html += "<td class='img-" + i + "'><a class='imglink' href='/girls/photos/picture.php?pid=" + pics[i].pid + "'></a><br /><a href='/girls/photos/picture.php?pid=" + pics[i].pid + "'>" + titleText + "</a><br />" + pics[i].disp_count + " Views</td>";
		
		if ( rowCount == PICS_PER_ROW ) {
			html += "</tr>";
			rowCount = 0;
		} else {
			rowCount++;
		}
		
	}
	// Put the table on the page
	$("#pic-page").html(html);
	
	// Inject the images (before everything)
	for ( i = start_index; i <= finish_index; i++ ) {
		$(".img-" + i).find(".imglink").append(preloaded_thumbs[i]);
	}
}

// Make the html for the next page
function makePage(page) {
	makePageTimer = setInterval (function() {
		if ( checkPageLoaded(page) ) {
			loadingImageShown = false;
		
			makePageHtml(page);
			
			$("#pic-page").show(1);
			
			// Stop the timer
			clearInterval(makePageTimer);
		} else {
			if ( !loadingImageShown ) {
				$("#pic-page").show(1); // Really fast
				$("#pic-page").html("<center><img src='/girls/images/ajaxactivity.gif' /></center>");
				loadingImageShown = true;
			}
		}
	}, 500);
}


// Function to load the next page
function goToPage(page) {
	prev_current_page = current_page; // Save the page we're moving from just in case
	current_page = page;
	
	// Load the page if it isn't loaded already
	if ( !checkPageLoaded( page ) ) {
		$("#pic-page").hide("slide", {direction: "left"}, 750);
		loadSpecificPage(page);
		doPageNav();
		makePage(page);
		loadForPage();
	} else {
		$("#pic-page").hide("slide", {direction: "left"}, 750);
		setTimeout( function() { makePageHtml(page) }, 700 ); // Wait to load the others
		doPageNav();
		$("#pic-page").show("slide", {direction: "right"}, 750);
		loadForPage();
	}
	
	// Set the anchor so we can keep track of the page
	var myFile = document.location.toString();
	if (myFile.match('#')) { // the URL contains an anchor
		var fileWithoutAnchor = myFile.split('#')[0];
		document.location = fileWithoutAnchor + "#" + current_page;
	} else {
		document.location = document.location + "#" + current_page;
	}
	
}


function goNextPage() {
	if ( getNextPage() <= num_pages )
		goToPage(getNextPage());
}

function goPrevPage() {
	if ( getPrevPage() >= 1 )
		goToPage(getPrevPage());
}
