var af_frame_right = af_cur_frame == af_want_frame;
var af_cur_page = af_cur_frame;
var af_page_right = true; // Is the current page the one that was requested in the URL/hash? 
var af_loading_url = af_cur_page;
var af_cur_page_error = false; // Might be '404' or '403'
var af_hash = window.location.hash;
if (af_hash == '#')
	af_hash = '';
var af_xhr_obj = null; // XMLHttpRequest object for the current request, if one is underway
var af_scroll_element = 'html,body'; // For smooth scrolling; will be detected as either 'body' or 'html'
var af_initial_hash = af_hash; // The original hash value when this frame was loaded 
// Set up smooth scrolling:
$(function() {
    $('html, body').each(function () {
        var initScrollTop = $(this).attr('scrollTop');
        $(this).attr('scrollTop', initScrollTop + 1);
        if ($(this).attr('scrollTop') == initScrollTop + 1) {
        	af_scroll_element = this.nodeName.toLowerCase();
            $(this).attr('scrollTop', initScrollTop);
            return false;
        }    
    });
});
// Initialization - check what page we should load or element we should scroll to:
if (af_hash && af_hash.charAt(1) == '/') {
	// We need to load a different page, which was specified in the hash:
	af_page_right = false;
	$(document).ready(function() {
		$("#cframe").html('<p>Loading...</p>');
		af_goto(af_hash.substring(1,af_hash.length));
	});
} else {
	$(document).ready(af_updated);
	if (af_initial_hash) { // Scroll to a particular spot in the document:
		$(function() {
			if ($(af_initial_hash).length) { // Check that the target element exists
				$(af_scroll_element).animate({scrollTop: $(af_initial_hash).offset().top}, 500, function() {  });
			}
		});
	}
}
function af_updated() { // Called on doc load and whenever page changes
	//alert('af_updated, cur_page is '+af_cur_page+' and loading_url is '+af_loading_url+' and hash is '+af_hash+' (real '+window.location.hash+')');
	af_page_right = true;
	// Set up links:
	$("a").each(function() {
		var url = $(this).attr('href');
		if (!url || $(this).hasClass('af-ignore') || $(this).hasClass('aframeignore') /* aframeignore is deprecated */)
			return; // not a hyperlink
		if ($(this).hasClass('af-download')) { // links with af-download are assumed to point to PDF files, etc., so we don't modify them
			if (url.charAt(0) != '/') // Fix relative links:
				$(this).attr('href', af_folder_name(af_cur_page)+ url);
			if (typeof page_download_handler == 'function')
				$(this).click(page_download_handler);
			return;
		}
		if (url.charAt(0) != '/') {
			if (url.charAt(0) == '#') {
				// Regular hash link; convert to use smooth scrolling:
				if ($(this.hash).length) { // Check that the target element exists
					$(this).attr('href', af_cur_page+url);
					$(this).click(function(event) {
	                    var targetOffset = $(this.hash).offset().top;
	                    var target = this.hash;
	                    event.preventDefault();
	                    $(af_scroll_element).animate({scrollTop: targetOffset}, 500, function() { location.hash = target; });
	                });
				}
				return;
			}
			if (url.indexOf(':') != -1 && url.indexOf(':') < 20)
				return; // External or mailto link; pass through
			// At this point, url must be a relative link, like 'path.php' or '../'
			// So prepend the current folder
			url = af_folder_name(af_cur_page)+ url; 
		}
		url = af_clean_url(url);
		$(this).attr('href', url);
		if (af_frame_right) {
			$(this).click(af_link_click);
		} else {
			// We need to change the frame URI
			if (url != af_want_frame)
				$(this).attr('href', af_want_frame+'#'+url);
			else
				$(this).attr('href', af_want_frame);
		}
	});
	$("img").each(function() {
		var src = $(this).attr('src');
		if (!src || $(this).hasClass('aframeignore'))
			return;
		if (src.charAt(0) != '/') {
			if (src.indexOf(':') != -1 && src.indexOf(':') < 20)
				return; // External link; pass through
			// At this point, src must be a relative reference, like 'cool.jpg'
			// So prepend the current folder
			src = af_folder_name(af_cur_page)+ src;
			$(this).attr('src', src); 
		}
	});
	//alert('Weird. Got here. '+af_hash+' is hash, af_cur_page is '+af_cur_page);
	// Update the window title:
	document.title = $("#cframe .cfTitleStr").text()+' ';
	if (af_cur_page != af_cur_frame)
		af_hash = '#'+af_cur_page;
	else
		af_hash = '';
	if (window.location.hash != af_hash && !(af_cur_page == af_cur_frame && window.location.hash.charAt(1) != '/'))
		window.location.hash = af_hash;
	if (typeof page_update_handler == 'function') {
		page_update_handler(af_cur_page);
	}
}
function af_goto(url) {
	if (af_xhr_obj)
		af_xhr_obj.abort();
	af_loading_url = url;
	//af_xhr_obj = $.get(af_loading_url, {af_in_frame: 1}, af_ajax_done, 'html');
	//$("#cframe").load(af_loading_url, 'af_in_frame', af_ajax_done);
	af_xhr_obj = $.ajax({type: "GET", url: af_loading_url, data:{af_in_frame: 1}, dataType: "html", success: af_ajax_done, error: af_ajax_error});
}
function af_link_click(e) {
	if (e.which == 1 || e.which == null) { // This if statement is a hackish workaround so that middle-clicks function properly
		af_goto($(this).attr('href'));
		return false; // Cancel the click event
	}
}
function af_ajax_done(responseHTML, textStatus) {
	// The AJAX Request has succeeded:
	af_cur_page = af_loading_url;
	af_loading_url = null;
	af_xhr_obj = null;
	af_cur_page_error = false;
	$('#cframe').html(responseHTML);
	af_updated();
}

function af_ajax_error(XMLHttpRequest, textStatus, errorThrown) {
	var status_code = af_xhr_obj.status;
	var failed_page = af_loading_url;
	af_loading_url = null;
	af_xhr_obj = null;
	
	var display_generic_message = true;
	if (typeof page_error_handler == 'function') {
		display_generic_message = page_error_handler(failed_page, status_code, textStatus, errorThrown);
	}
	if (display_generic_message) {
		if (status_code == '404' || status_code == '403' || status_code == '500') {
			if (status_code == '404')
				$("#cframe").html('<h1>Error 404: Page Not Found</h1><p>Sorry, the requested page, <strong>'+failed_page+'</strong>, could not be found on this server.</p><br /><p><a href="'+af_cur_page+'">&laquo; Back</a></p><div class="cfTitleStr" style="display:none;">Page Not Found (Error 404)</div>');
			else if (status_code == '403')
				$("#cframe").html('<h1>Error 403: Forbidden</h1><p>Sorry, you do not have permission to view this page.</p><br /><p><a href="'+af_cur_page+'">&laquo; Back</a></p><div class="cfTitleStr" style="display:none;">Forbidden (Error 403)</div>');
			else
				$("#cframe").html('<h1>Error 500: Internal Server Error</h1><p>Sorry, a problem with the web server is preventing this page from being displayed. Please try again in a few minutes.</p><br /><p><a href="'+af_cur_page+'">&laquo; Back</a></p><div class="cfTitleStr" style="display:none;">Server Error (500)</div>');
			af_cur_page = failed_page;
			af_cur_page_error = status_code;
			af_updated();
		} else {
			alert('An error occurred while trying to load the page you requested; please try again.');
		}
	}
}
function af_folder_name(url) {
	// Isolate and simplify a folder name.
	// Given "/test/index.php?a=b", this function returns "/test/"
	// Path given must start with a /
	if (url.charAt(0) != '/')
		throw new Error("Invalid argument to af_folder_name");
	var q_index = url.indexOf('?');
	if (q_index != -1)
		url = url.substring(0,q_index); // delete the query string part, which may contain a / that will screw up the following:
	url = url.substring(0,url.lastIndexOf('/')+1); // trim everything after the last /
	return url; 
}
function af_clean_url(url) { // Clean up an url, fixing duplicate slashes, ../ references, etc.
	var append = '';
	var q_index = url.indexOf('?');
	if (q_index != -1) {
		append = url.substring(q_index); // we will append the query string later
		url = url.substring(0,q_index); // delete the query string part for now, which may contain a / that will screw up the following:
	}
	var to_fix = /\/\//; // Get rid of duplicate forward slashes (//)
	while (to_fix.test(url)) { url = url.replace(to_fix, '/'); }
	to_fix = /\/\.\//; // Interpret ./ sequences
	while (to_fix.test(url)) { url = url.replace(to_fix, '/'); }
	to_fix = /\/[^\/]+\/\.\.\//; // Interpret ../ sequences
	while (to_fix.test(url)) { url = url.replace(to_fix, '/'); }
	return url+append;
}
function af_hash_changed() {
	af_hash = window.location.hash;
	if (af_hash && af_hash.charAt(1) == '/' && af_hash != '#'+af_cur_page) {
		af_goto(af_hash.substring(1,af_hash.length));
	} else if (!af_hash || af_hash == '#' || af_hash == '#'+af_cur_page) {
		$(af_scroll_element).animate({scrollTop: 0}, 500);
	}
}
function af_poll_hash() {
	if (af_hash != window.location.hash)
		af_hash_changed();
}
$(function() {
	// Watch for hash changes:
	if ("onhashchange" in window) {
	    // Browser supports native hashchange events:
		window.onhashchange = af_hash_changed;
	} else {
		setInterval("af_poll_hash()", 350);
	}
});