$(document).ready(function()
{
	// Get all list items
	var items = $('#lifestream .nav ul li h3');
	
	// ...and iterate over them to retrieve their class
	for (i = 0; i < items.length; ++i)
	{
		// get the single item and its class
		var itm = $(items[i]);
		var id = itm.attr('id');

		// send a request for every item to load the latest feeditems
		$.getJSON('json.php', {key: id}, function(data, status)
		{
			var fCls = data.info.cls;
			var fUrl = data.info.url;
			var fTitle = data.info.title;
			var fItems = data.items;
			
			// generate the base block
			$('body').append('<div id="b_' + fCls + '" class="section feedlist ' + fCls + '"></div>');
			
			// get the base block
			var feedList = $('div.feedlist.' + fCls);
			
			// append the heading
			feedList.append('<h4 class="' + fCls + '">' + fTitle + '</h4>');
			
			// append the content list
			feedList.append('<ul></ul>');
			$.each(fItems, function(i, item)
			{
				feedList.find('ul').append('<li><a href="' + item.url + '">' + item.title + '</a></li>');
			});
			
			// add the "more" link
			feedList.append('<p class="more"><a href="' + fUrl + '">mehr davon</a></p>');
			
			// display the close button
			feedList.append('<a href="#" class="close">schließen</a>');
			
			// make it draggable
			feedList.draggable({handle: 'h4', stack: { group: '.feedlist', min: 10 }, opacity: 0.7});
			
			// change class in list for ui-feeling
			$('#lifestream .nav ul li #' + fCls).parent().removeClass('loading').addClass('loaded');
		});
	}
	
	/**
	 * This is used for openig the appropriate window by click on a list item
	 */
	 $('#lifestream .nav ul li h3 a').click(function()
	{
		// find out the class
		var h3 = $(this).parent();
		var li = h3.parent();
		var id = h3.attr('id');
		
		// check if the window is already active or not
		if (li.hasClass('active'))
		{
			// close the window
			$('.feedlist.' + id).fadeOut();
			li.removeClass('active').addClass('loaded');
		}
		else if (li.hasClass('loaded'))
		{
			// open the window
			$('.feedlist.' + id).fadeIn();
			li.removeClass('loaded').addClass('active');
		}
		
		return false;
	});
	
	/**
	 * This closes the window by click on the close button
	 */
	$('.feedlist .close').live('click', function()
	{
		var parent = $(this).parent();
		
		parent.fadeOut();
		$('#lifestream .nav ul li #' + parent.attr('id').substr(2)).parent().removeClass('active').addClass('loaded');
		
		return false;
	});
	
	/**
	 * Switch pages with click on a footer link
	 */
	$('.footer .nav a').click(function()
	{
		var id = $(this).attr('href').substr(1);
	
		$('.activecontent').fadeOut().removeClass('activecontent');
		$('#' + id).fadeIn().addClass('activecontent');
		return false;
	});
});
