/**
 * Author: Dennis Robinson
 * Date: December 21, 2009
 * Copyright: Mergenta (c) 2009
 *
 * Passport javascript file.
 */

// Variables
var base_url = '';
var pages = new Array('index');
var cache = new Array();
var pageData = new Array();
var start_page = pages[0];
var currentPage = pages[0];

/**
 * Loads all of the pages into memory.
 */
function loadAllPages()
{
	// Load each page
	for (var i = 0; i < pages.length; i++)
	{
		loadPage(pages[i]);
	}
}

/**
 * Loads a single page into memory.
 */
function loadPage(page)
{
	// Set the page to loading
	pageData[page] = new Array();
	pageData[page]['data_status']  = 'loading';
	pageData[page]['image_status'] = 'loading';
	pageData[page]['data']         = undefined;
	pageData[page]['image']        = undefined;

	// Load the content of this page
	jQuery.ajax({
		type: 'GET',
		cache: false,
		url: (base_url + '/pages/' + page + '.xml'),
		success: function(response)
		{
			// Convert the xml document
			response = $(response);

			// Store the data in the grades array
			pageData[page]['data_status'] = 'loaded';
			pageData[page]['data'] = new Array();
			pageData[page]['data']['title']       = response.find('page').find('title').text();
			pageData[page]['data']['leftColumn']  = response.find('page').find('leftColumn').text();
			pageData[page]['data']['rightColumn'] = response.find('page').find('rightColumn').text();
		},
		error: function()
		{
			pageData[page]['status'] = 'error';
		},
		dataType: 'xml'
	});

	// Load the navigation image for this page
	pageData[page]['image'] = $('<img />')
		.attr('src', (base_url + '/images/navigation_' + page + '.jpg'))
		.load(function()
		{
			pageData[page]['image_status'] = 'loaded';
		});
}

/**
 * Called by a link to change the page.
 */
function changePage(page, attempt)
{
	var data_status;
	var image_status;
	var data;

	// Check if this page exists
	if (pageData[page] == undefined)
	{
		// It doesn't, so display an error message
		data_status = 'error';
		image_status = 'error';
	}
	else if (page == currentPage)
	{
		// We are already on this page so don't change to it again
		return;
	}
	else
	{
		data_status  = pageData[page]['data_status'];
		image_status = pageData[page]['image_status'];
		data         = pageData[page]['data'];
	}

	// Set the attempt to 1 if not set
	// 'attempt' keeps track of how many times we have attempted to change the page
	if (attempt == undefined)
	{
		attempt = 1;
	}

	if (data_status == 'loaded' && image_status == 'loaded')
	{
		// Page is loaded and ready to be displayed
		if (isIndexGreaterThan(currentPage, page))
		{
			// Flip right to left
			// Display the right column and transition image
			changeRight(page);
			$('#passport #overlayImageLeft').show();

			// Wait for 250ms then hide the transition image and display the left column
			setTimeout("$('#passport #overlayImageLeft').hide();", 300);
			setTimeout("changeLeft('" + page + "');", 300);

			// Change from cover image to left image
			setTimeout("$('#passport #overlayImageLeft').attr('src', 'images/page_flip_left.png');", 300);
		}
		else
		{
			// Flip left to right
			// Display the left column and transition image
			changeLeft(page);
			$('#passport #overlayImageRight').show();

			// Wait for 250ms then hide the transition image and display the right column
			setTimeout("$('#passport #overlayImageRight').hide();", 300);
			setTimeout("changeRight('" + page + "');", 300);
		}

		// Change the window title
		document.title = ('Destinations Travel Clinic - ' + data['title']);

		// Set the current page
		currentPage = page;
	}
	else if ((data_status == 'loading' || image_status == 'loading') && attempt <= 10)
	{
		// Try again in a half second
		setTimeout(("changePage('" + page + "', " + (attempt + 1) + ")"), 500);
	}
	else
	{
		// Must be an error
		$('#passport #page #leftColumn').html('');
		$('#passport #page #rightColumn').html('Error: The page could not be found.');
	}

	// Change the url
	window.location.hash = page;
}

/**
 * Changes the left page.
 */
function changeLeft(page)
{
	// Display the left column
	$('#background #backgroundLeftColumn').css('background-image', 'url(\'images/background_left.jpg\')');
	$('#passport #header h1').css('display', 'block');
	$('#passport #page #leftColumn').html(pageData[page]['data']['leftColumn']);
}

/**
 * Changes the right page.
 */
function changeRight(page)
{
	// Display the right column
	$('#background #backgroundRightColumn').css('background-image', 'url(\'images/background_right.jpg\')');
	$('#passport #header div').css('display', 'block');
	$('#passport #page').css('overflow-y', 'scroll');
	$('#passport #page #rightColumn').html(pageData[page]['data']['rightColumn']);

	// Change the navigation image
	$('#passport #navigation_background').css('background-image', 'url(\'images/navigation_' + page + '.jpg\')');
}

/**
 * Determines if a page's index is greater than another page's index.
 */
function isIndexGreaterThan(oldPage, newPage)
{
	var oldIndex = 0;
	var newIndex = 0;

	// Find the indexes for the pages
	for (var i = 0; i < pages.length; i++)
	{
		if (pages[i] == oldPage)
		{
			oldIndex = i;
		}
		else if (pages[i] == newPage)
		{
			newIndex = i;
		}
	}

	// Return if the new index is greater than the old one
	return (newIndex > oldIndex);
}

/**
 * Redirects www.site.com/page to www.site.com/#page
 */
function redirectToHashtag()
{
	var current_url = (window.location.protocol + '//' + window.location.host + window.location.pathname);

	// Check if a page was specified using the directory structure
	if (current_url !== (base_url + '/'))
	{
		var page = current_url.substr(base_url.length + 1);

		// Redirect to the proper URL
		window.location = (base_url + '/#' + page);

		return true;
	}

	return false;
}

/**
 * Code to execute on load.
 */
$(document).ready(function() {

	current_page = pages[0];

	// Redirect to the hashtag version of the URL if necessary
	if (redirectToHashtag())
	{
		// Go no further
		return;
	}

	// Preload images
	cache['background_left']  = $('<img />').attr('src', (base_url + '/images/background_left.jpg'));
	cache['background_right'] = $('<img />').attr('src', (base_url + '/images/background_right.jpg'));
	cache['logo']             = $('<img />').attr('src', (base_url + '/images/logo.gif'));
	cache['enter']            = $('<img />').attr('src', (base_url + '/images/enter.jpg'));
	cache['page_flip_left']   = $('<img />').attr('src', (base_url + '/images/page_flip_left.png'));
	cache['page_flip_right']  = $('<img />').attr('src', (base_url + '/images/page_flip_right.png'));
	cache['page_flip_cover']  = $('<img />').attr('src', (base_url + '/images/page_flip_cover.png'));
	cache['checkmark']        = $('<img />').attr('src', (base_url + '/images/checkmark.png'));

	// Start loading all of the pages
	loadAllPages();

	// Check for a hash tag
	if (window.location.hash.length > 1)
	{
		// Go to the page in the hash tag
		changePage(window.location.hash.substr(1));
	}
	else
	{
		// Go to the default page
		changePage(start_page);
	}

});
