jQuery(document).ready(function($) {
	
	var fSort = function( a, b ) {
		// Sort Ascending
		var x = $(a).find('title').text().toLowerCase();
		var y = $(b).find('title').text().toLowerCase();
		
		return ( ( x < y ) ? -1 : ( ( x > y ) ? 1 : 0 ) );
	}
					
	$('#topicsxmlitem').hide();
	
	var bHasTopicsXmlItem = $('#topicsxmlitem').length ? true : false;
	
	$.get(
		'xml/topics.xml',
		function( xml ) {
			
			var items = $(xml).find('item');
			var half = Math.ceil( items.length / 2 );
			
			items.sort( fSort ).each(function( i ) {
				
				var id = 'topic_' + i;
				var title = $(this).find('title').text();
				
				// add link
				var col = ( i < half ) ? 1 : 2;
				
				$('#topicstable ul.col_' + col).append( '<li><a href="topics.html#' + id + '">' + title + '</a><\/li>' );
				
				
				// add content
				if ( bHasTopicsXmlItem ) {
				
					var tmpl = $('#topicsxmlitem').clone();
					
					tmpl.removeAttr('id');
					tmpl.find('h2 a').html( title );
					tmpl.find('h2 a').attr( 'id', id );
					tmpl.find('h2 a').attr( 'name', id );
					tmpl.find('div.topicscontent').html( $(this).find('content').text() );
					
					tmpl.show();
				}
				
				$('#topicsxmlblock').append( tmpl );
				
			});
			
			if ( window.location.toString().match(/#/) ) {
				window.location = window.location;
			}
			
		}
	);
	
});

