// Start functioning when DOM is ready
$( function()
{
	// Placeholder for old widths
	var oldWidth;
	
	// Copy the projects and their previews on loadUp
	// Create div placeholders first
	$('body').append('<div style="display:none;" id="datastore"><div/><div/></div>');
	
	// Set empty array in the data of datastore
	$('#datastore').data( 'order', new Array() );
	
	// Copy the projects
	$('#slides')
		.clone()
		.appendTo( '#datastore > div:first' );
	
	// Copy the previews
	$('#preview-panel')
		.clone()
		.appendTo( '#datastore > div:last');
		
	// Save the ordering of the projects
	$('#slides > li').each( function()
	{
		// Check if the project hasn't been already set in the array
		if ( $('#datastore').data('order').toString().indexOf( $(this).attr('id') ) == -1 )
		{
			// Push the project name into the order
			// array in the data of datastore
			$('#datastore')
				.data('order')
				.push( $(this).attr('id') );
		}
	});
	
	
	/**
	 * Function to animate the tags onLoad.
	 * 
	 * Also binds the hover effect on the tags.
	 */
	$('.relevancy-tag span').each( function()
	{
		// Get current width
		var w = $(this).css( 'width' );
		
		// Set width to 0
		$(this).css( 'width', '0' );
		
		// Animate the width
		$(this).animate({width: w}, 1000, 'easeOutExpo', function()
		{
			// Animate the tags at hover
			$('.relevancy-tag').hover( 
				function()
				{
					// Set the font size bigger
					$('span', this).css({fontSize: '13px'});
				},
				function()
				{
					// Set the fontsize small again
					$('span', this).css({fontSize: '11px'});
				}
			);
		});
	});
	
	
	/**
	 * Function to filter by tags onClick of tags
	 * 
	 * Old code:
	 * // Get the tag URL
	 * var url = $(this).attr( 'rel' );
	 * 
	 * // Goto the new location
	 * window.location = url;
	 */
	$('.project-filter > ul > li').live( 'click',  function()
	{
		// Close show_info if opened
		$('#show_info[class="selected"]').trigger( 'click' );
		
		// Get the tagname of the current clicked tag
		var tagName = $('span', this).html() || $(this).html();
		
		// Get the state of the current clicked tag
		var tagState = $(this).attr( 'class' );
		
		// Do the correct actions for the tag
		switch ( tagState )
		{
			case 'relevancy-tag':
				$(this)
					.removeClass()
					.addClass('active-tag')
					.empty()
					.html( tagName );
				break;
				
			case 'active-tag':
				$(this)
					.removeClass()
					.addClass('relevancy-tag')
					.empty()
					.prepend('<span>'+tagName+'</span>');
				break;
				
			default:
				return false;
				break;
		}
		
		// Get active tags
		var activeTags = getActiveTags();
		
		// If a tag is being turned off, recover projects
		if ( tagState == 'active-tag' ) recoverProjects();
		
		// Loop through all projects
		$('#viewport > #slides > li').each( function()
		{
			// Get the project id
			var projectID = $(this).attr( 'id' );
			
			// Remove project or not?
			if ( ! checkTags( $(this), activeTags ) )
			{
				// Remove this project
				$(this).remove();
				
				// Remove the corresponding preview
				$('#viewport + #preview-panel > li > div[rel="'+projectID+'"]').parent().remove();
			}
		});
		
		// Set the #slides to the top
		$('#viewport > #slides').css( 'top', '0' );
		
		// Remove any active current-slides
		$('#viewport > #slides > .current-slide').removeClass('current-slide');
		
		// Set first found project as active
		$('#viewport > #slides > li:first').addClass('current-slide');
		
		// Update the project information panel
		projectInfo();
		
		// Fix the taglist
		fixTags();
		
		// Fix the zebra style (odds and evens)
		fixZebra();
		
		// Fix the first project in the preview panel
		fixPreviewPanel();
		
		// Update project count
		updateProjectCount();
		
		// Update the arrows
		checkArrows();
		
		return false;
	});
	
	
	/**
	 * Function to  get the tags in an array
	 * with the number of times used.
	 */
	var getTags = function()
	{
		// Start array to put in all the found tags
		var tags = new Array();
		
		// Loop throug all the current projects tag container
		$('#viewport > #slides > li > .project_data > .related-services').each( function()
		{
			// Loop through all the tags
			$('li', this).each( function()
			{
				// Get the current tagname
				var tagName = trim( $(this).html() );
				
				// Check if tag exists or not
				if ( typeof tags[tagName] == 'undefined' )
					tags[tagName] = 0;
				
				// Increment the current tag
				tags[tagName]++;
			});
		});
		
		// Return the found tags in an Array
		return tags;
	};
	
	
	/**
	 * Function to fix tag states and percentages
	 */
	var fixTags = function()
	{
		// Get current used tags
		var allTags = getTags();
		
		// Loop through all tags
		$('.project-filter > ul > li:not(.active-tag)').each( function()
		{
			// Get the name of the current tag
			var currentTag = $('span', this).html() || $(this).html();
			
			// Check if the currentTag is being used
			if ( typeof allTags[currentTag] == 'undefined' ) {
				$(this)
					.empty()
					.html( currentTag )
					.removeClass();
			} else {
				// Calculate the percentage of this tag
				var tagPercentage = getPercentage( currentTag, allTags );
				
				// Set the percentage and fix the rest of the tag
				$(this)
					.empty()
					.removeClass()
					.addClass( 'relevancy-tag' )
					.html( '<span style="width: '+tagPercentage+'px">'+currentTag+'</span>' );
			}
		});
	};
	
	
	/**
	 * Function to count the max tags from the
	 * current tags array
	 */
	var countTags = function( allTags )
	{
		// Set var for the max tags
		var count = 0;
		
		// Count the max of tags
		for ( var i in allTags ) count += allTags[i];
		
		// Return the number of tags
		return count;
	};
	
	
	/**
	 * Function to calculate the percentage of a tag
	 * to use in css.
	 */
	var getPercentage = function( tagName, allTags )
	{
		// Get the total project count
		var total = $('#viewport > #slides > li').length;
		
		// Get the count of the current tag
		var count = allTags[ tagName ];
		
		// Calculate the percentage
		var perc = ( count / total );
		
		// Do some math
		var total = Math.round( perc * 219 );

		// Decrement total with 5px
		total -= 5;
		
		return total;
	};
	
	
	/**
	 * Function to get all names of the active
	 * tags, in an Array.
	 */
	var getActiveTags = function()
	{
		// Start empty array
		var tags = new Array();
		
		// Get all active tags
		$('.active-tag').each( function() {
			tags.push( $(this).html() );
		});
		
		// Return false if no items were found
		if ( tags.length < 1 ) return false;
		
		// Return the array with tags
		return tags;
	};
	
	
	/**
	 * Function to get an array with tags by
	 * project.
	 */
	var getTagsByProject = function( project )
	{
		// Set empty array for the tags
		var tags = new Array();
		
		// Loop through all the tags
		$('.project_data > .related-services > li', project).each( function()
		{
			// Set the tag in the tags array
			tags.push( $(this).html() );
		});
		
		// Return the array with tags
		return tags;
	};
	
	
	/**
	 * Function to check if all given tags are
	 * found in the project.
	 * @param	Project project
	 * @param	Array	tags
	 * @return	Boolean
	 */
	var checkTags = function( project, tags )
	{
		// Set state var which has true by default
		var state = true;
		
		// Get tags by project
		var projectTags = getTagsByProject( project );
		 
		// Loop through the array of given tags and set
		// state to false if either one of the tags is not
		// set in the project's tags
		for ( var k in tags ) {
			if ( projectTags.toString().indexOf( tags[k] ) == -1 )
				state = false;
		}
		
		// Return the final state
		return state;
	};
	
	
	/**
	 * Function to recover the copied projects
	 * back to the view
	 */
	var recoverProjects = function()
	{
		// Begin with removing the old data
		$('#slides, #preview-panel').remove();
		
		// Recover the slides
		$('#viewport').append( $('#datastore > div:first > ul').clone() );
			
		// Recover the previews
		$('#viewport').after( $('#datastore > div:last > ul').clone() );
	};
	
	
	/**
	 * Function to fix the information panel
	 */
	var projectInfo = function()
	{
		// Get correct HTML
		var html = $('.current-slide > .project_data').html();
		
		// Empty old project data and correctly
		// set the new HTML
		$('#viewmore')
			.empty()
			.html( html );
	};
	
	
	/**
	 * Function to set the number of active
	 * projects in the 'Showing XX of XX projects'
	 */
	var updateProjectCount = function()
	{
		// Count the number of active projects
		var projectCount = $('#viewport > #slides > li').length;
		
		// Update text
		$('.showproject > h4 > span:first').html( projectCount );
	};
	
	
	/**
	 * Function to check the arrows if they are
	 * allowed to be viewed or not.
	 */
	var checkArrows = function()
	{
		// Count the number of projects
		projectCount = $('#viewport > #slides > li').length;
		
		// If count is lower than five, hide both arrows
		if ( projectCount < 5 )
			$('#slide-up, #slide-down').hide();
			
		// ..else show both arrows
		else $('#slide-up, #slide-down')
			.show()
			.fadeTo('fast', 0.5);
	};
	
	
	/**
	 * Function to fix the zebra (odd/even) style in
	 * the project preview panel.
	 */
	var fixZebra = function()
	{
		// Walk through the current projects
		$('.leftpane > #preview-panel > li').each( function(i, e)
		{
			// Remove old classes and save element
			var el = $('div[rel]', this).removeClass();
			
			// Odd
			if ( i % 2 ) el.addClass( 'project-name-odd' );
				
			// Even
			else el.addClass( 'project-name-even' );
		});
	};
	
	
	/**
	 * Fix the first project in the preview panel
	 */
	var fixPreviewPanel = function()
	{
		$('.leftpane > #preview-panel > li:first')
			.hide()
			.prependTo( $(this).parent() );
	};
	
	
	/**
	 * Function to trim whitespaces in front and at
	 * the end of a string.
	 */
	var trim = function( string )
	{
		string = string.replace( /^\s+/, '' );
		string = string.replace( /\s+$/, '' );
		return string;
	};
	
});