/*
// tagFilter - Initialize the tag filtering plugin
*/
var filter_selector = '.filter'; //This is the class that is attached to each tag filter
var tag_selector = "#search_filters"; //This is the id of the div that contains the tags
function tagFilter()
{
	$(filter_selector).unbind('click');
	
	//Construct the global asset array that we'll use for searching and tag display
	assetsToTags();
	
	//reset display of all assets and tags
	resetAssetDisplay();
	
	//Initialize the click function for tags
	$(filter_selector).click(function()
	{
		$_GET = urlToArray();
		
		//Get the clicked tag id
		var tag_id = $(this).attr('tag');
		
		if (tag_id == 'all')
		{
			//reset display of all assets and tags
			resetAssetDisplay();
			
			//Update the href of the object that was clicked 
			//so that the url updates at the end of the function.
			delete $_GET['tags'];
			var href = urlToString($_GET);
			$(this).attr('href', href);
			
			return true;
		}
		else
		{
			//If the clicked tag is not selected ...
			if (!$(this).is('.selected')) 
			{
				//Select the clicked tag
				$(this).addClass('selected');
				//Update the active tag array, add the new tag
				updateTagsActive(tag_id, 'add');
			} 
			else 
			{
				//De-Select the clicked tag		
				$(this).removeClass('selected');
				
				//Update the active tag array, remove the tag
				updateTagsActive(tag_id, 'remove');

				//Update the href of the object that was clicked 
				//so that the url updates at the end of the function.
				$_GET['tags'] = asset_array['tags_active'];
				var href = urlToString($_GET);
				$(this).attr('href', href);
				
				//Is this the only selected tag?
				
				if (empty(asset_array['tags_active']))
				{
					//Then unselecting it has reset the asset display
					resetAssetDisplay();
					
					return true;
				}
			}
			
			$('#featured_asset').hide();
			
			//Perform asset filtering based on selected tags
			updateAssetDisplay(asset_array['tags_active']);
			
			//Hide tags that don't have visible assets
			updateTagsByID(asset_array['visible_asset_ids']);
			
			//update search feedback message
			updateSearchFeedback();
						
			//Update the href of the object that was clicked 
			//so that the url updates at the end of the function.
			$_GET['tags'] = asset_array['tags_active'];
			var href = urlToString($_GET);
			$(this).attr('href', href);
		}
	});
}

/*
// assetsToTags - Construct a global asset array that we'll use for tag filtering
// RETURNS global ( array asset_ids ) , ( array asset_tags ) , ( array tags_assets )
// DETAILS 
//   asset_ids:   ('asset_id','asset_id','asset_id');
//   asset_tags:  ('asset_id' => ('tag_name', 'tag_name', 'tag_name') );
//   tags_assets: ('tag_id' => ('asset_id','asset_id','asset_id') );
*/
var asset_array = new Array();
function assetsToTags()
{
	asset_array['asset_ids'] = [];
	asset_array['asset_tags'] = [];
	asset_array['tags_assets'] = [];
	asset_array['tags_active'] = [];
	
	$('#asset_results li').each(function()
	{
		//Get the asset id from <li id>
		var asset_id = $(this).attr("id");
		//Get the tag string from contained field .searchtags
		var tags = $(this).children(".searchtags").html();
		//Throw them into an array for parsing
		tags = tags.split(' ');
		
		//loop through each tag and perform necassary operations
		for (var tag in tags)
		{
			//this is the tag name
			var tag_id = tags[tag];
			//is the tag_name already defined?
			if (!asset_array['tags_assets'][tag_id])
			{
				asset_array['tags_assets'][tag_id] = new Array();
			}
			//insert the asset_id into the tag id array
			asset_array['tags_assets'][tag_id].push(asset_id);
			
			//is the asset_id array already defined?
			if (!asset_array['asset_tags'][asset_id])
			{
				asset_array['asset_tags'][asset_id] = new Array();
			}
			//insert the tag_name into the asset array
			asset_array['asset_tags'][asset_id].push(tag_id);			
		}
		
		//add each asset id to an array
		asset_array['asset_ids'].push(asset_id);
	});
}

/*
// resetAssetDisplay - Reset the display on all assets and tags
*/
function resetAssetDisplay()
{
	//Reset visible assets to default - everything becomes visible
	asset_array['visible_asset_ids'] = asset_array['asset_ids'];	
	asset_array['tags_active'] = [];
	
	//this function will hide tags that don't have visible assets.
	//passes array of asset_ids
	updateTagsByID(asset_array['asset_ids']);
	
	//Reset tag selection
	$(tag_selector + ' li a').removeClass('selected');
	$(tag_selector + ' #all-option').addClass('selected');
	
	//Reset search-feedback
	var category_id = $('#categories li a.selected').attr('category_id');
	
	if (category_id != 'featured')
	{
		$('#search_feedback').html(page_copy.search_feedback_1);
	}
	else
	{
		$('#search_feedback').html('');
	}
	
	//Reset asset visibility
	$('#asset_results li').show();
	
	$('#featured_asset').show();
}

/*
// updateTagsActive - Update the tags_active array by adding or removing a tag
// PASSES ( string tag_id ), ( string type )
// DETAILS
//   tag_id: the clicked tag
//   type: specifies whether to add or remove an element from the array
*/
function updateTagsActive(tag_id, type)
{
	//If the type is add then we're adding an element to the active tag array
	if (type == 'add')
	{
		if (!in_array(tag_id, asset_array['tags_active']))
		{
			asset_array['tags_active'].push(tag_id);
		}
	}
	//otherwise we're removing an element
	else if (type == 'remove')
	{
		if (in_array(tag_id, asset_array['tags_active']))
		{
			asset_array['tags_active'] = removeItem(asset_array['tags_active'], tag_id);
		}
	}
}

/*
// updateAssetDisplay - Update the visibility of all assets based on selected tags.
// PASSES ( array search_tags )
// DETAILS
//   search_tags: an array of tag_ids 
*/
function updateAssetDisplay(search_tags)
{
	if (search_tags)
	{
		$('#all-option').removeClass('selected');
		
		var asset_tags = asset_array['asset_tags'];
		var tags_assets = asset_array['tags_assets'];
		
		//reset visible asset ids since it will be repopulated
		asset_array['visible_asset_ids'] = [];
		
		for (var asset_id in asset_tags) //looking at each asset: asset_1, asset_2, etc
		{
			
			//The asset is to be shown unless determined otherwise
			var show_this = true;
			
			//Are we looking at an array of tags?
			if (isArray(search_tags))
			{
				//Then loop through and perform checks on each tag
				for (var tag_key in search_tags) //looking at selected search tags: tag_1, tag_2, etc
				{
					var tag_id = search_tags[tag_key];

					if (tag_id != null)
					{						
						//Look for asset id in tags_assets array
						var is_tagged = in_array(asset_id, tags_assets[tag_id]);
						
						//If the asset id is found in tag array, then this asset is tagged
						if (is_tagged == false)
						{
							//if the tag search fails then the asset should be hidden
							show_this = false;
						}
					}
				}
			}
			//Otherwise we're looking at a single selected tag
			else
			{
				var tag_id = search_tags;
								
				//Look for asset id in tags_assets array
				var is_tagged = in_array(asset_id, tags_assets[tag_id]);
				
				//If the asset id is found in tag array, then this asset is tagged
				if (is_tagged == false)
				{
					//if the tag search fails then the asset should be hidden
					show_this = false;
				}		
			}
			
			if (show_this == true)
			{
				asset_array['visible_asset_ids'].push(asset_id);
				$("#"+asset_id).show();
			}
			else
			{
				$("#"+asset_id).hide();
			}
		}
	}
}

/*
// updateTagsByID - Display tags that have visible assets and highlight tags that are selected.
// PASSES ( array asset_ids )
// DETAILS
//   asset_ids: ('asset_id','asset_id','asset_id')
*/
function updateTagsByID(asset_ids)
{
	//reset the visible tags
	asset_array['visible_tag_ids'] = [];
	
	//loop through the visible assets and collect an array of available tags
	for (var asset_key in asset_ids) //looking at each asset: asset_1, asset_2, etc
	{
		var asset_id = asset_ids[asset_key];
		
		var visible_asset_tags = asset_array['asset_tags'][asset_id]; //looking at the tags for iterated asset
		
		for (tag_id in visible_asset_tags) //looking at each tag: tag_1, tag_2, etc
		{
			asset_array['visible_tag_ids'].push(visible_asset_tags[tag_id]);
		}
	}
	
	//remove duplicate tags from the array
	asset_array['visible_tag_ids'] = (unique(asset_array['visible_tag_ids']));
	
	//hide all tags
	$(tag_selector + " li").hide();
	$(tag_selector + " li a#all-option").parent().show();
	
	for (var tag_key in asset_array['visible_tag_ids'])
	{
		var tag_id = asset_array['visible_tag_ids'][tag_key];
		
		//show tags that are required
		$(tag_selector + " li a#" + tag_id).parent().show();
	}
	
	for (var tag_key in asset_array['tags_active'])
	{
		
		var tags_active = asset_array['tags_active'];
		var tag_id = tags_active[tag_key];
				
		$('#' + tag_id).addClass('selected')
	}
}

/*
// updateSearchFeedback - Update the message that is display on the page.
*/
function updateSearchFeedback()
{
	var selectedTagNames = '';
	var count = 0;
	$(tag_selector + ' li a.selected').each(function(){
		selectedTagNames += '[' + $(this).html();
		selectedTagNames += '], ';
		count++;
	});	
	selectedTagNames = selectedTagNames.slice(0, -2);
		
	var asset_count = asset_array['visible_asset_ids'].length;
	if (asset_count == 1)
	{
		$('#search_feedback').html('1 ' + page_copy.search_feedback_2 + ' ' + selectedTagNames);
	}
	else
	{
		$('#search_feedback').html(asset_count + ' ' + page_copy.search_feedback_3 + ' ' + selectedTagNames);
	}
}
