jQuery(document).ready(function($){
	
	//References
	var links = $("ul#nav a");
	var loading = $("#stloader");
	var content = $("#content");
	
	var XMLarray = new Array();
	
	var months= {
 		'11' : "December 2010",
 		'0' : "Januari 2011",
 		'1' : "Februari 2011" };

		
/*  Initial loading of content  */	

	$(function(){
		content.load( "home.html", function() { contentLoaded("home"); } ); 
		links.removeAttr("href");
	});	
		
	$("ul#nav span").hover(function () {
		$(this).stop().animate({ opacity: 1 }, 300);	
		}, function () {
			$(this).stop().animate({ opacity: 0 }, 300);
	});
	$("ul#nav span").css("opacity", "0");
			
	//Manage click events
	links.click(function(){
		showLoading();
		var page=this.id;
		content.animate( { opacity:0 } , 'slow', function() {
			content.load( page + ".html", function(){
				contentLoaded(page);
			});
		});
	});
	
	
/*  Functions  */	
	
	//show loading icon
	function showLoading(){
		loading
			.css({visibility:"visible"})
			.css({opacity:"0.5"})
			.css({display:"block"});
	}
	
	function contentLoaded(page){
		content.animate( { opacity:1 } , 'slow');
		loading
			.css({visibility:"hidden"})
			.css({opacity:"0"})
			.css({display:"none"});
		switch(page) {
			case "home":
				loadNews();		
				break;		
			case "team":
				loadTeamMenu();		
				break;
			case "fotos":
				loadFotoMenu();		
				break;
			case "kalender":
				var m = new Date().getMonth();
				loadCalendar(m);					
				$('#prev').click(function() {
					prevdate();
				});
				$('#next').click(function() {
					nextdate();
				});
				break;
		}
	}

	
	function ajaxError(request, type, errorThrown)	{
		var message = "There was an error with the AJAX request.\n";
		switch (type) {
			case 'timeout':
				message += "The request timed out.";
				break;
			case 'notmodified':
				message += "The request was not modified but was not retrieved from the cache.";
				break;
			case 'parsererror':
				message += "XML/Json format is bad.";
				break;
			default:
				message += "HTTP Error (" + request.status + " " + request.statusText + ").";
		}
		message += "\n";
		console.log(message);
	}
	
	
	/* load XML if file hasnt been loaded yet, then call the callback */
	function loadXMLFile(file,callback,args) {
		if (XMLarray[file]==undefined) {
			$.ajax({ 	 
				type: "GET",
				url: "public/xml/" + file,
				dataType: ($.browser.msie) ? "text" : "xml",
				error: ajaxError,
				success: function(data) { 				
					var xml;
	     				if (typeof data == "string") {
						xml = new ActiveXObject("Microsoft.XMLDOM");
						xml.async = false;
						xml.loadXML(data);
	     				} else {
						xml = data;
	     				}
					XMLarray[file]=xml;
					callback(args);
				}	
			});
		} else {
			callback(args);
		}
	}
	
	
	function loadNews()	{
		loadXMLFile("news.xml",createNews);	
	}
	
	
	function createNews() {
		var output = '<span class="header"><h2>Nieuws</h2></span>';		
		$(XMLarray["news.xml"]).find("item").each(function() { 
			output += '<div><p><b>' + $(this).find('titel').text() + '</b><br />';
			output += $(this).find('text').text() + '</p></div>'; 	
		});
		$("#news").html(output);
	}
	
	function loadFotoMenu() {
		loadXMLFile("fotos.xml",createFotoMenu);
	}
	
	function loadFotoAlbum(id) {
		loadXMLFile("fotos.xml",createAlbum,[id]);
	}
	
	
	function createFotoMenu() {
		var output = '<ul id="fotonav">';
		$(XMLarray["fotos.xml"]).find("album").each(function() {	
			if ($(this).attr('dir') == 'empty') {				
				output += '<li>' + $(this).attr('name') + '</li>';	
			} else {
				output += '<li><a id="' +  $(this).attr('id') + '">' + $(this).attr('name') + '</a></li>';						
			}
		});
		output += '</ul>';
		$("#fotocontainer").html(output);
		$('#fotonav a').click(function() { loadFotoAlbum(this.id); } );
	}
	
	function createAlbum(id) {
		var output = '';
		$(XMLarray["fotos.xml"]).find("album[id=" + id + "]").each(function() {
			output += '<table><thead><tr><td><a id="back">Terug naar overzicht</a></td><td>' + $(this).attr('name') + '</td></tr></thead><tbody><tr>';
			var dir = $(this).attr('dir');
			var i = 1;
			var last = $(this).children().length;
			$(this).children().each(function() {				
				var subdir = 'public/images/fotos/' +  dir + "/"
				var image = subdir + $(this).text();
				var thumb = subdir + "thumb_" + $(this).text();				
				output += '<td><a href="' + image + '" rel="lightbox[' + id + ']" title="' + $(this).attr('title') + '"><img class="thumb" src="' + thumb + '" alt="' + $(this).attr('title') + '" ></a></td>';
				if ( i%3 == 0 || i == last) {
					output += '</tr>';
				}
				i++;
			});
			output += '</tbody></table>';		
		});
		$("#fotocontainer").html(output);
		$("#back").click(function() { 	loadFotoMenu();	});
		$("#fotocontainer td").css({ opacity: 0.6 }).hover(function () {
			$(this).stop().animate({ opacity: 1 }, 300);	
				}, function () {
			$(this).stop().animate({ opacity: 0.6 }, 300);
		});
	}
	
	
	function loadTeamMenu() {
		loadXMLFile("team.xml",createTeamHTML)
	}
	
	function loadMember(id) {
		loadXMLFile("team.xml",createMember,id)
	}
	
	
	var loadingmember = false;
	function createTeamHTML() {
		
		var isIE = (navigator.appName == 'Microsoft Internet Explorer');
		var count=1;
		var output = '';
		$(XMLarray["team.xml"]).find("rijder").each(function() {		  
			var id = $(this).attr('id');								  	
			var naam = $(this).find("naam").text();
			output += '<a id="' + id + '">' + naam + '</a>';
			naam = naam.split(' ').join('').toLowerCase();
			
			if (isIE == false)
			{
				if ($(this).attr("functie") == "rijder") { 			
					output += '<div class="tooltip"><img src="public/images/team/profile_' + naam + '.jpg" width="170" height="185"/></div>';
				} else {
					output += '<div class="tooltiporange"><img src="public/images/team/profile_' + naam + '.jpg" width="170" height="185"/></div>';
				}
			
				if (count==6) {
					output += '<br />';
					count = 0;
				}
				count++;
			}
		});
		
		$("#teamnav").html(output);		
		
		if (isIE) {
			$('#teamnav a').click(function(){ loadMember([this.id]); } );
		}		
		else {		
			$('#teamnav a').tooltip( { effect: 'slide', relative: true }  ).click(function(){ loadMember([this.id]); }).hover( function(){
				if ($('#teamfoto').css('opacity') != 0.2 && !loadingmember ) {
					$('#teamfoto').stop().animate({ opacity: 0.4 }, 300);
				}
			}, function() {
				if ($('#teamfoto').css('opacity') != 0.2 && !loadingmember ) {
					$('#teamfoto').stop().animate({ opacity: 1 }, 300);					
				}
			});
		}
	}
	
	
	function createMember(id) {
		loadingmember = true;		
		$('#teamfoto').stop().animate({ opacity: 0.2 }, 300,function() {
			$(XMLarray["team.xml"]).find("rijder[id=" +  id + "]").each(function() {
				var isRijder = ($(this).attr("functie") == "rijder");
				 
				var output = '<ul>';						
				output += '<li><label>Naam:</label><p><b>' +  $(this).find("naam").text() + '</b></p></li>';
				if (isRijder) {
					output += '<li><label>Beennummer:</label><p>' + $(this).find("beennummer").text() + '</p></li>';
				}				
				output += '<li><label>Geboortedatum:</label><p>' + $(this).find("geboortedatum").text() + '</p></li>';
				output += '<li><label>Woonplaats:</label><p>' + $(this).find("woonplaats").text() + '</p></li>';
				output += '<li><label>Burgerlijke staat:</label><p>' + $(this).find("burgerlijkestaat").text() + '</p></li>';
				output += '<li><label>Werk/Opleiding:</label><p>' +  $(this).find("werk").text() + '</p></li>';
				output += '<li><label>Nationaliteit:</label><p>' + $(this).find("nationaliteit").text() + '</p></li>';

				var i=0;					
				if (isRijder) {
					$(this).find("websites").children().each(function() {
						output += '<li><label>';
						if (i == 0) {
							output += 'Website:';
						}						
						output += '</label><p><a href="' + $(this).attr("url") + '" title="' + $(this).attr("url") + '">' + $(this).text() + '</a></p></li>';
						i++;
					});
				}
				i=0;
				$(this).find("materialen").children().each(function() {
					var hasUrl = ($(this).attr("url") && $(this).attr("url").length > 0);
					output += '<li><label>';
					if (i == 0) {
						output += 'Materialen:';
					}						
					output += '</label><p>';
					if (hasUrl) {
						output += '<a href="' + $(this).attr("url") + '" title="' + $(this).attr("url") + '">'
					}					
					output += $(this).text();
					if (hasUrl) {
						output += '</a>'; 
					}
					output += '</p></li>';
					i++;
				});						
				if (isRijder) {
					output += '<li><label>Doelstelling:</label><p>' + $(this).find("doelstelling").text() + '</p></li>';					
				}				
				output += '<li><label>Hoogtepunt carrière:</label><p>' + $(this).find("hoogtepunt").text() + '</p></li>';
				output += '<li><label>Favoriete ijsbaan:</label><p>' + $(this).find("ijsbaan").text() + '</p></li>';
				output += '</ul>';
				var fotoClass = (isRijder) ? "memberfoto" : "trainerfoto";
				output += '<div class="' + fotoClass + '"><img src="public/images/team/profile_' + $(this).find("naam").text().split(' ').join('').toLowerCase() + '.jpg" width="170" height="185"/></div>';									
				$("#member").html(output);
			});
		});
	}
		
	
	function loadCalendar(month) {
		loadXMLFile("calendar.xml",createRows,month);
	}
	
	
	function createRows(month) {
		$('#curMonth').fadeOut('fast',function(){			
			$(this).html(months[month]);
			$(this).fadeIn('fast');
		});
		$("#calendar tbody").hide('normal',function(){
			var count = 0;
			$("#calendar tbody").html('');
			$(XMLarray["calendar.xml"]).find("event[month='" + month + "']").each(function() {		  				  	
				var date = $(this).find("date").text();
				var eventname = $(this).find("eventname").text();
				var place = $(this).find("place").text();			
				var output = (count % 2) ? '<tr class="odd">' : '<tr>';
				output += '<td>' + date + '</td>';
				output += '<td>' + eventname + '</td>';
				output += '<td>' + place + '</td>';
				output += "</tr>";
				$("#calendar tbody").append(output);
				count++;
			});				
			$("#calendar tbody").show('normal');
		});			
	}
	
	
	function nextdate() {
		var cmonth = $('#curMonth').html();
		var newMonth = 0;
		$.each(months, function(key, value){
			if(cmonth == value) {
				newMonth=parseInt(key) + 1;
				if(newMonth==1) {
					$('#next').toggleClass('next_disabled').toggleClass('next');
					$('#next').unbind('click');
				} else if(newMonth==12) {
					$('#prev').toggleClass('prev').toggleClass('prev_disabled');
					$('#prev').click(function(){ prevdate(); });
					newMonth=0;		
				}
			}	
		});
		loadCalendar(newMonth);
	}
	
	
	function prevdate() {
		var cmonth = $('#curMonth').html();
		var newMonth = 0;
		$.each(months, function(key, value){
			if(cmonth == value) {
				newMonth=parseInt(key) - 1;
				if(newMonth==-1) {
					newMonth = 11;
					$('#prev').toggleClass('prev_disabled').toggleClass('prev');
					$('#prev').unbind('click');
				} else if(newMonth==0) {
					$('#next').toggleClass('next').toggleClass('next_disabled');
					$('#next').click(function(){ nextdate(); });
				}
			}	
		});
		loadCalendar(newMonth);
	}
});

