// At which page are we?
var cpage = location.hash.substr(1);
var firsttime_nav = true;

var form_focus = false;

var status = 0;
/*	0 = Doing nothing
	1 = Fading out
	2 = No content
	3 = Fading in
*/
var status_data = "";

var slideshow_timer = null;

$(document).ready( function() {
	
	$.History.bind( function(page){
		load_page(page);
	});
	
	if (window.location.hash == '')
	{
		// Everything is already done for us
		firsttime_nav = false;
		
		bind_page_events($("#content .contentwrapper"));
	}
	$("a[href^=?p=]").click( function() {
		// Which page is this?
		var pagenav = $(this).attr('href').substr(3);
		
		$.History.setHash(pagenav);
		
		$(this).blur();
		
		return false;
	});
});



function load_page(page)
{
	if (page == ""){page = "home";}
	if (cpage == page & firsttime_nav == false)
	{
		return;
	}
	if (status != 0) {return;}
	status = 1;
	status_data = "";
	clearTimeout(slideshow_timer);
	
	cpage = page;
	form_focus = false;
	
	show_navigation(page);
	
	var old_wrapper = $(".contentwrapper");
	$("#content").css({height: $("#content").height()});
	old_wrapper.fadeOut(100, function() {
		$(this).remove();
		
		if (status_data != "")
		{
			load_page_data(status_data);
		}
		else
		{
			// Create loader
			var loader = $("<img/>");
			loader.attr('src', 'img/loader2.gif');
			loader.attr('class', 'page-loader');
			loader.hide().fadeIn(1500);
			$("#content").append(loader);

			status = 2
		}
	});
	
	// Load the page
	$.ajax({
		type: "GET",
		url: "data/" + page + ".html",
		dataType: "html",
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			// File not found. Try the 404
			$.ajax({
				type: "GET",
				url: "data/404.html",
				dataType: "html",
				success: function(data, textStatus){
					if (status == 2)
					{
						// Page has faded out
						load_page_data(data);
					}
					else
					{
						// Page has not yet faded out
						status_data = data;
					}
				}
			});
		},
		success: function(data, textStatus) {
			if (status == 2)
			{
				// Page has faded out
				load_page_data(data);
			}
			else
			{
				// Page has not yet faded out
				status_data = data;
			}
		}
	});
}

function load_page_data(data)
{
	status = 3;
	$("#content img").remove(); //Remove loader;
	
	var lines = data.split("\r\n");
	
	title = lines.shift();
	body = lines.join("\n");
	
	if (title == "")
	{
		document.title = "BlueWolf.nl";
	}
	else
	{
		document.title = title + ' - BlueWolf.nl';
	}
	
	
	var old_wrapper = $(".contentwrapper");
	var new_wrapper = $("<div class='contentwrapper'></div>");
	new_wrapper.html(body);
	
	bind_page_events(new_wrapper)
	
	$("#content").append(new_wrapper);
	
	
	new_wrapper.css({opacity:0});
	
	// Get new height
	old_height = $("#content").height();
	$("#content").css({height:""});
	new_height = $("#content").height();
	$("#content").css({height:old_height});
	
	$("#content").animate({height:new_height}, 400, function() {
		$(this).css({height: ""});
	});
	
	new_wrapper.fadeTo(200, 1, function() {
		new_wrapper.css({opacity:''}); //IE(7) will display weird things when opacity is set
	});
	
	status = 0;
}

function bind_page_events(page)
{
	page.find("a[href^=?p=]").click( function() {
		// Which page is this?
		var pagenav = $(this).attr('href').substr(3);
		
		$.History.setHash(pagenav);
		scroll_to_top();
		
		return false;
	});
	
	page.find('form *').focus( function() {
		form_focus = true;
	});
	page.find('form *').blur( function() {
		form_focus = false;
	});
	
	// Safari does not accept multiple selectors
	// In IE(7) ALL containers need to be pointers, instead of just the li
	page.find(".subitems li").css({cursor:'pointer'});
	page.find(".subitems li *").css({cursor:'pointer'});
	
	page.find(".subitems li").click( function() {
		var url = $(this).find('a').attr('href');
		url = url.substring(url.indexOf('?p=')+3);
		$.History.setHash(url);
		scroll_to_top();
		
		return false;
	});
	
	// Do we need a slideshow?
	var slideshow = page.find(".slideshow");
	if (slideshow.length != 0)
	{
		// Only show the first
		slideshow.find("img:not(img:first)").css({display:'none'});
		
		slideshow.find("img").css({position:"absolute"});
		slideshow_timer = setInterval(do_slideshow, 7000);
	}
}

function scroll_to_top()
{
	$('html, body').animate({scrollTop:0}, 250);
}

function show_navigation(page)
{
	// Find the item
	var item = $("#menu a[href=?p=" + page + "]");
	if (item.length == 1)
	{
		var open = [];
		
		// Remove all selected-classes
		$("#menu a").removeClass('selected');
		
		// Current selection
		item.addClass('selected');
		
		// Find the child
		var sub = item.parent().find("ul:first");
		if (sub.length == 1)
		{
			open[open.length] = sub;
		}
		
		// Find all parents
		item = item.parent().parent();
		while(!item.hasClass('menu_1'))
		{
			// Add the selected class
			item.parent().find('a:first').addClass('selected');
			
			open[open.length] = item;
			
			item = item.parent().parent();
		}
		
		
		// Close everything else
		$("#menu ul ul").each(function(i, item) {
			item = $(item);
			
			if (is_equal(item, open))
			{
				if (firsttime_nav)
					{item.show();}
				else
					{item.show(250);}
			}
			else
			{
				if (firsttime_nav)
					{item.hide();}
				else
					{item.hide(300);}
			}
		});
		
		
		
		
	}
	else
	{
		// Item not found. Just close all items
		if (firsttime_nav)
		{
			$("#menu ul ul").hide();
		}
		else
		{
			$("#menu ul ul").hide(300);
		}
		
		// Remove all selected-classes
		$("#menu a").removeClass('selected');
	}
	
	firsttime_nav = false;
}

function is_equal(item, list)
{
	for(var i in list)
	{
		if (item.find('a').attr('href') == list[i].find('a').attr('href'))
		{
			return true;
		}
	}
	return false;
}



function contact(form)
{
	form = $(form)
	
	// Disable all input
	form.find('*:input').attr('disabled','true');
	
	// Show loader
	form.find('.ajax-loader').fadeIn(500);
	
	// Remove all previous errors
	form.find('*:input').blur();
	
	// Put all data in a POST-variable
	var data = {};
	$.each(form.find('*:input[name]'), function(i,e) {
		data[$(e).attr('name')] = $(e).val();
	});
	data['form_focus'] = form_focus;
	
	// Post!
	$.post('contact.php', data, function(data) {
		if (data['error'] == null)
		{
			var succeed = $("<div></div>");
			succeed.attr('class', 'contact-succeed');
			succeed.append("Thank you for your message. I'll contact you soon");
			
			form.fadeOut(200, function() {
				form.after(succeed);
				succeed.hide().fadeIn(500);
			});
		}
		else
		{
			var error = $("<div></div>");
			error.attr('class', 'contact-error');
			error.append(data['error'][1]);
			error.insertBefore($('#errorinsert'));
			error.hide().slideDown(250);
			
			// Highlight input
			var input = form.find('*[name=' + data['error'][0] + "]");
			input.addClass('fail');
			input.one('blur', function() {
				$(this).removeClass('fail');
				error.slideUp(1000, function() {
					error.remove();
				});
			});
			
			// Enable input again
			form.find('*:input').attr('disabled','');
			
			// Remove loader
			form.find('.ajax-loader').stop().fadeOut(1000);
			
			// Select failed input
			input.focus();
			input.select();
			
		}
	}, 'json');
}



function do_slideshow()
{
	$.each($("#content .slideshow"), function(i, e) {
		e = $(e);
		
		var current = e.find('img:visible');
		current.css({zIndex:0});
		
		var next = current.next();
		
		if (next.length == 0)
		{
			// End of our list. Start with the beginning
			next = e.find('img:first');
		}
		
		next.css({zIndex:1});
		
		next.fadeIn(1500, function() {
			current.hide();
		});
		
	});
}

