// Available pages
var aPages = [ 'aanvullendediensten', 'actiepagina', 'algemenevoorwaarden', 'bedankt', 'contact', 'faq', 'index', 'overalltrahome', 'recensies', 'login' ];
var bFirstLoad = true;
var sPage = 'index';

function HashChange()
{
	// Inspect the hash
	sPage = 'index';
	if(window.location.hash)
	{
		// Take off the #
		var sHash = window.location.hash.substring(1);
		if($.inArray(sHash, aPages) != -1)
			sPage = sHash;
	}

	// Fade out page, fade in loader, or just call the loader if this is a first load
	if(bFirstLoad)
	{
		bFirstLoad = false;
		LoadPage(sPage);
	}
	else
	{
		$("#page_content").fadeOut('fast', function()
		{
			$("#page_loading").fadeIn('fast', function()
			{
				LoadPage(sPage);
			});
		});
	}
}

function LoadPage(sPage)
{
	// Load it with fading callbacks
	$("#page_content").load('content/' + sPage + '.html', function()
	{
		$("#page_loading").fadeOut('fast', function()
		{
			$("#page_content").fadeIn('fast');
		});
	});
}

function Login(oForm)
{
	// Wrap it
	oForm = $(oForm);

	// Send it
	$.post('login.php', oForm.serialize(), LoginCallback, 'json');

	// No actual submit
	return false;
}

function LoginCallback(oData)
{
	if(oData.login)
		window.location.href = 'reload.php';
	else
		alert('Gebruikersnaam of wachtwoord incorrect');
}

function SendContact(oForm)
{
	// Wrap it
	oForm = $(oForm);

	// Send it
	$.post('contact.php', oForm.serialize(), SendContactCallback);

	// No actual submit
	return false;
}

function SendContactCallback()
{
	$("#contact_form").fadeOut('fast', function()
	{
		$("#contact_form").load('content/bedankt.html', function()
		{
			$("#contact_form").fadeIn('fast');
		});
	});
}

function EditPage()
{
	// Make it a bit wider so all content fits
	$("#page_container").width(664);

	// Swap buttons
	$("#edit_button").hide();
	$("#save_button").show();
	$("#cancel_button").show();

	// Edit
	$("#page_content").ckeditor({customConfig: 'config.js'});
}

function CancelPage(bUpdate)
{
	// Destroy the editor
	$("#page_content").ckeditorGet().destroy(bUpdate);

	// Return width
	$("#page_container").width(654);

	// Swap buttons
	$("#edit_button").show();
	$("#save_button").hide();
	$("#cancel_button").hide();
}

function SavePage()
{
	// Fetch the editor
	var oEditor = $("#page_content").ckeditorGet();

	// Only save if dirty
	if(oEditor.checkDirty())
	{
		// Fetch the new content and save it
		var sData = oEditor.getData();
		$.post('save.php', { page: sPage, content: sData });
	}

	// Handle the rest as a cancel
	CancelPage(false);
}

function Logout()
{
	// Just call it
	window.location.href = 'logout.php';
}

// Page setup
$(function()
{
	// Hash change callback
	$(window).hashchange(HashChange);

	// Trigger a fake hash change for load
	$(window).hashchange();
});

