$(document).ready(function()
{	
	var display;
	var order;
	var descasc;
	var view;
	
	var overviewMatrixSize;
	var overviewMatrixWidth;
	var overviewMatrixHeight;
	
	var opacityValue = 0.4;
	var easingDuration = 600;
	var easingType = 'easeOutQuart';
	
	var animated = 0;
	
	var holdDetails = false;
	
	var entries;
//	var newMarginTop = ($(window).height() - $('#center').height() + 2) / 2;
	
	$('a.desc, a.asc').click(toggleDescasc);
	$('a.all, a.lastfm, a.twitter, a.flickr').click(filterEntries);
	startUp();

	function startUp()
	{
		display = 'all';
		order = 'date';
		descasc = 'desc';
		view = 'over';
		
		sizeContent();
		sizeMatrix();
		showEntries();
		
		entries = $('.content').children();
		checkMenuClasses();
	}
	
	function sizeContent()
	{
		var newHeightValue = $(window).height() - $('.head').height() - 180;		
		var newHeightFloor = Math.floor(newHeightValue / 60);
		var newHeight = newHeightFloor * 60;
		
		var newWidth = $(window).width() - 100;
		$('.content').css({height: newHeight, width: newWidth}); 
	}
	
	function sizeMatrix()
	{
		overviewMatrixWidth = Math.floor($('.content').width() / 60);
		overviewMatrixHeight = Math.floor($('.content').height() / 60);
		overviewMatrixSize = overviewMatrixWidth * overviewMatrixHeight;
	}
	
	function showEntries()
	{
		if(display == 'all')
		{					
			for(var i = 0; i < overviewMatrixSize; i++)
			{
				fillEntry(i);							
			}
		} 
	}
	
	function addEntry()
	{
		$('.content').append('<div class="entry"><div class="thumbnail"></div></div>');
	}
	
	function filterEntries(event)
	{
		if(display != $(event.target).attr('class'))
		{	
			display = $(event.target).attr('class');
			var filteredEntryCount = $('.content .' + display).length;
			
			$('.entry').each(function()
			{
				if(display != 'all')
				{
					if(!$(this).hasClass(display))
					{
						$(this).fadeOut(duration(), easingType);
						$(this).addClass('hidden');
					}
					
					else
					{
						$(this).fadeIn(duration(), easingType);
						$(this).removeClass('hidden');
					}
					
					if(filteredEntryCount < overviewMatrixSize)
					{
						var entriesToAdd = overviewMatrixSize - filteredEntryCount;	
						entries = $('.content').children();
								
						//for(var i = entries.length - 1; i >= filteredEntryCount; i--)
						//{
							//fillEntry(i);
							//$('.hidden').remove();
						//}
				
						sortEntries();
						entries = $('.content').children('*[class!=hidden]');
			
						for(var i = 0; i < entries.length; i++)
						{
							var posTop = Math.floor(entryNumber / overviewMatrixWidth);
							var posLeft = entryNumber % overviewMatrixWidth;
							$(entries[i]).animate({top: posTop * 60, left: posLeft * 60}, duration(), easingType, fillEntry(i));
						}
					}
				}
				
				else
				{
					$(this).fadeIn(duration(), easingType);
					$(this).removeClass('hidden');
				}	
			});			
			
			checkMenuClasses();
		}
	}
	
	function fillEntry(entryNumber)
	{
		$.getJSON(
        	"query.php", 
        	{
        		number: entryNumber + 1,
        		descasc: descasc,
        		order: order,
        		display: display
        	},			
       		function(data)
       		{
				$.each(
					data.items, 
					function(i,item)
          			{

            			$('.content').append('<div class="entry ' + item.type + '" id="entry-' + item.id + '"><div class="thumbnail"><img src="' + item.image + '" alt="' + item.title + '" /></div></div>');
            			$('#entry-' + item.id).find('.thumbnail img').hide();
            			positionOverviewEntryStart($('#entry-' + item.id), entryNumber);
            			
            			$('#entry-' + item.id + ' .thumbnail img').load(function()
            			{
            				$(this).fadeIn(duration());
            			});
            			
            			if(item.type == 'lastfm')
            			{            				
            				$('#entry-' + item.id).append('<div class="service"><a href="http://www.last.fm/user/snorpey/">last.fm</a></div>');
            				$('#entry-' + item.id).append('<div class="date">' + item.date + '</div>');
            				$('#entry-' + item.id).append('<div class="details"><span class="title">' + item.title.toLowerCase() + '</span> / ' + item.artist.toLowerCase() + ' / ' + item.album.toLowerCase() + '</div>');
            			}
            					
            			if(item.type == 'twitter')
            			{            						
            				$('#entry-' + item.id).append('<div class="service"><a href="http://twitter.com/snorpey">twitter</a></div>');
            				$('#entry-' + item.id).append('<div class="date">' + item.date + '</div>');
            				$('#entry-' + item.id).append('<div class="details"><div class="text">' + item.content.toLowerCase().replace('snorpey: ', '') + '</div></div>');
               			}
            					
            			if(item.type == 'flickr')
            			{            						
							$('#entry-' + item.id).append('<div class="service"><a href="flickr.com/photos/snorpey/">flickr</a></div>');
            				$('#entry-' + item.id).append('<div class="date">' + item.date + '</div>');
            				$('#entry-' + item.id).append('<div class="details"><span class="title">' + item.title.toLowerCase() + '</span></div>');
              			}
              			
              			if(item.type == 'steam')
            			{            						
            				$('#entry-' + item.id).append('<div class="service"><a href="http://steamcommunity.com/id/snorpey">steam</a>/' + item.game.toLowerCase() + '</div>');
            				$('#entry-' + item.id).append('<div class="date">' + item.date + '</div>');
            				$('#entry-' + item.id).append('<div class="details"><div class="text">' + item.title.toLowerCase() + ': ' + item.text.toLowerCase() + '</div></div>');
               			}
              			
              			$('#entry-' + item.id + ' .date').hide();
						$('#entry-' + item.id + ' .service').hide();
						$('#entry-' + item.id + ' .details').hide();
						//$('#entry-' + item.id).css({position: 'absolute', top: -50, left: -50});
						$('#entry-' + item.id + ' .thumbnail').css({width: 50, height: 50});
						$('#entry-' + item.id + ' .thumbnail img').css({width: 50, height: 50});
						$('#entry-' + item.id + ' .thumbnail img').hover(overviewOver, overviewOut);
						
						$('#entry-' + item.id + ' .thumbnail img').click(function()
						{
							if(holdDetails)
							{
								holdDetails = false;
							}
							
							else
							{
								holdDetails = true;
							}
						});
          			}
          		);
        	}
        );	
	}
	
	function positionOverviewEntry(entry, entryNumber)
	{
		var entryID = Number($(entry).attr('id').replace('entry-', '')) - 1;	
		var posTop = Math.floor(entryNumber / overviewMatrixWidth);
		var posLeft = entryNumber % overviewMatrixWidth;
		$(entry).animate({top: posTop * 60, left: posLeft * 60}, duration(), easingType, overviewDone);
	}
	
	function overviewDone()
	{
		var entries = $('.content').children('*[class!=hidden]');
		
		
		if(animated < entries.length)
		{
			positionOverviewEntry(entries[animated], animated);
			animated++;
		}
		
		else
		{
			animated = 0;
		}
		
	}
	
	function positionOverviewEntryStart(entry, entryNumber)
	{
		var entryID = Number($(entry).attr('id').replace('entry-', '')) - 1;	
		var posTop = Math.floor(entryNumber / overviewMatrixWidth);
		var posLeft = entryNumber % overviewMatrixWidth;
		$(entry).css({position: 'absolute', top: posTop * 60, left: posLeft * 60});
	}
	
	function toggleDescasc(event)
	{
		if(!$(event.target).hasClass('menuActive'))
		{
			descasc = $(event.target).attr('class');		
			entries = $('.content').children();
		
			for(var i = 0; i < entries.length; i++)
			{
				positionOverviewEntry(entries[i], i);						
			}
		
			checkMenuClasses();
			sortEntries();
		}
	}
	
	function sortEntries()
	{
		$('.content .entry').tsort('*[class!=hidden]', {order: descasc, place: 'start', orderby: 'id'});
	}
	
	function checkMenuClasses()
	{
		$('.menuActive').removeClass('menuActive');
		$('.intro a.' + display).addClass('menuActive');
		$('.intro a.' + order).addClass('menuActive');
		$('.intro a.' + descasc).addClass('menuActive');
		$('.intro a.' + view).addClass('menuActive');
	}
	
	function duration()
	{
		var max = easingDuration;
		var min = easingDuration / 2;		
		var returnValue = Math.round(min + (Math.random() * (max - min)));
		return returnValue;
	}
	
	function overviewOver(event)
	{
		$(event.target).animate({opacity: 0.3}, 200);
		var entryId = $(event.target).parent().parent().attr('id');
		updateDetailContainer(entryId);
	}
	
	function overviewOut(event)
	{
		$(event.target).animate({opacity: 1}, 200);
		
		if(holdDetails == false)
		{
			$('.detailContainer').hide();
		}
	}
	
	function updateDetailContainer(entryId)
	{
		if(holdDetails == false)
		{
			$('.detailContainer').hide();
			$('.detailContainer .date').html($('#' + entryId + ' .date').text() + ' on ' + $('#' + entryId + ' .service').html());
			$('.detailContainer .details').html($('#' + entryId + ' .details').html());
			$('.detailContainer .details').html(replaceURLWithHTMLLinks($('.detailContainer .details').text()));
			$('.detailContainer').show();
		}
	}
	
	function replaceURLWithHTMLLinks(text)
	{
  		var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  		return text.replace(exp,"<a href='$1'>$1</a>");
	}
});