function paginate() {
	var numpages = 0;
	var html = '<div id="navigator"><span class="link" rel="0">Previous</span>';
	$("fieldset").each(function(i) {
		$(this).addClass("num-"+ i);
		numpages++;
		if(i == 0) {
			html += '<span class="link current" rel="'+ i +'">'+ (i + 1) +'</span>';
			$(this).addClass('current');
		} else {
			html += '<span class="link" rel="'+ i +'">'+ (i + 1) +'</span>';
		}
	});
	html += '<span class="link" rel="1">Next</span></div>';
	$("form").before('<div id="progressbar"></div>')
		.after(html);

	$(".link").click(function() {
		var goTo = parseInt($(this).attr('rel'));

		if(goTo < numpages) {
			// Remove Currents
			$(".current").removeClass('current');

			// Set Previous and Next
			$(".link:first").attr('rel', (goTo - 1));
			$(".link:last").attr('rel', (goTo + 1));

			// Set Current
			$(".num-" + goTo).addClass('current');
			$('.link').each(function() {
				if($(this).attr('rel') == goTo) {
					$(this).addClass('current');
				}
			});

			// ScrollTo progress bar
			$.scrollTo('#progressbar');

			// Change Progress Bar
			$("#progressbar").progressbar("option", "value", (goTo * (100/numpages)));
		}
	});

	$("#progressbar").progressbar({
		value: 0
	});

	$(".date").datepicker({
		changeYear: true,
		yearRange: 'c-75:c'
	});
}

function AssignClicks() {
	$('a[href$=".html"]').click(function() {
		href = $(this).attr('href').replace(/^.*#/, '');
		$.history.load(href);
		return false;
	});
}

function LoadPage(href) {
	if(href == "index.html") {
		href = "home.html";
	}
	if(href != "") {
		href = href + " #content";
		$("#content").fadeOut(function() {
			$(this).load(href, function() {
				if(href == "form.html #content") {
					paginate();
				}
				AssignClicks();
				Shadowbox.setup();
				$(this).fadeIn();
			});
		});
	}
}

$(document).ready(function() {
	$.history.init(LoadPage);
	Shadowbox.init({
		skipSetup: true
	});

	var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1,location.pathname.length);
	
	if(location.hash != "") {
		LoadPage(location.hash);
	} else if(filename != "index.html" && filename != "") {
		LoadPage(filename);
	} else {
		$.history.load('home.html');
	}

	AssignClicks();
});
