//	Array of classes for backgrounds
var backgrounds = ['tile01','tile02','tile03','tile04','tile05','tile06','tile07','tile08','tile09'];

$(function()
{
	//	Set doRevert to false
	var doRevert = false;
	//	Set active_poster to false
	var active_poster = false;
	//	Make an array of all the poster dom elements
	var p = $('.poster');
	//	Loop through each dom element
	for(var i=0;i<p.length;i++)
	{
		//	Make an array of all posteres categories
		var c = $('#'+p[i].id).attr('category');
			c = c.split(' ');
		//	Need to change the name of the category classes so that they don't
		//	Get confused with tag names, this was happening with Research
		//	The effect was that some images where not part of the tag set, but where
		//	Rendered as so, due to them also being part of the category Research
		//	Create a temporary str
		var str = '';	
		//	Cycle through each array
		for(var ii=0;ii<c.length;ii++)
		{
			//	Add -cat to each cat name so that tags and cats don't get confused
			if(ii==0)
			{
				str += c[ii]+'-cat';
			} else {
				str += ' '+c[ii]+'-cat';
			}
		}
		//	Add the categories to the items class
		$('#'+p[i].id).addClass(str);
	}
	//	Add in greyspace and collabo tag
	$('#content').append('<div id="greyspace">Gallery by <a href="http://greyspace.com.au">Greyspace</a>, database by <a href="http://collabo.net">Collabo</a></div>');
	// Your code here
	$('.poster').toggle(
		function(){	
			if(doRevert)
			{
				revertDom(this);
				setDomStructure (this);
			} else {
				setDomStructure(this);
			}
			//	Reverts the previous poster to a thumbnail
			if(active_poster)
			{
				revertImage('#'+active_poster);
			}
			//	Gets the current image src
			var url = $(this).find('img').attr('src');
			//	Changes current image src to point to the large folder
				url = url.replace(/thumbs/, "large");
			//	Get the ALT of the image
			var alt = $(this).find('img').attr('alt');
			//	Get the tags list
			var details = '<div id="details" class="deleteMe posterDetails"><p>';
				details += 'Poster by <b>'+$(this).find('img').attr('alt')+'</b>, '
				details += 'filled under <i>'+$(this).attr('category')+'</i>';
				details += ' tagged <i>'+$(this).attr('tags')+'</i></p></div>';
			//	Get the category list
			var cats = $(this).attr('category');
			//	Make a new image - it seems that SAFARI 3 has a bug and won't replace the image source
			var img = '<img class="deleteMe" title="" alt="'+alt+'" description="" src="'+url+'">';
			//	Set small image to hidden
			$(this).find('img').addClass('hide');
			//	Add the image - this can be cleaned up so that it fades through the old image
			$(this).append(img);
			$('#index').prepend(details);
			//$('.tags').after($(this));
			//	OLD solution : SAFARI 3 bug : Replaces the image src with the new one
			//$(this).find('img').attr('src',url);
			//	Set the current poster as the active poster
			active_poster = this.id;
			//	Sets revert to true
			doRevert = true;
		},function()
		{
			revertDom();
			revertImage('#'+active_poster);
			active_poster = false;
		}).hover(function(){
			$(this).addClass('hover');
		},function(){
			$(this).removeClass('hover');
		});
});

function revertImage (id)
{
	//	Gets the current image src of the previous image
	var url = $(id).find('img').attr('src');
	//	Changes current image src to point to the thumbs folder
		url = url.replace(/large/, "thumbs");
	//	Replaces the image src with the new one
	$(id).find('img[class!="hide"]').remove();
	$(id).find('img[class="hide"]').removeClass('hide');
	$('#details').remove();
	//$(id).find('img').attr('src',url);
}

function sortTags(tagList)
{	
	combinations = null;
	combinations = new Array();
	//	Sort taglist, make alphabetic
		tagList.sort();
	//	Get a list of tag permutations
	var tagListPermutations = permutations(tagList);
	// Get a list of the selected posters
	var posters = $('.poster').not('.portraitScaleSml').not('.portraitScaleLrg');
	
	for(var i=0;i<tagListPermutations.length;i++)
	{
		//	Create a basic string
		var str = '';
		//	Loop through the permutations
		for(var ii=0;ii<tagListPermutations[i].length;ii++)
		{
			// Create a jQuery usable string
			str += tagListPermutations[i][ii] + ' ';
		}
		//	Add the string to the dom to show tags
		var rn = Math.floor(Math.random()*backgrounds.length);
		var bc = backgrounds[rn];
		//$('#index').prepend('<div title="'+str+'" class="tagSet setBorder toDelete '+bc+'"><div id="tl'+i+'" class="tagList">'+str+'</div></div>');//'#ts'+i		
	}
	
	for(var i=0;i<posters.length;i++)
	{
		var id = posters[i].id;
		//	Gets the tags for each set of matched elements
		var mytags = $('#'+id).attr('tags');
			mytags = mytags.split(' ');
		//	Create a new temporary array
		var tmp = new Array();
		//	Does something, not quite sure - wrote it along time ago
		for(var ii=0;ii<mytags.length;ii++)
		{
			//	Check to see if there are common tags
			if(CleanArray.contains(tagList,mytags[ii]))
			{
				//	Adds confirmed tags to the temporay array
				tmp.push(mytags[ii]);
			}
		}
		//	Sorts the array alphabetically
		tmp.sort();
		//	Does something, not quite sure - wrote it along time ago
		if(CleanArray.contains(tagListPermutations,tmp.join()))
		{
			var j = CleanArray.indexReturn(tagListPermutations,tmp.join());
			var s = tagListPermutations[j];
				s = s.toString();
				s = s.replace(/,/, " ");
			$('div[title="'+s+' "]')
				.removeClass('toDelete')
				.append($('#'+id));
		}
	}
	//	Gets rid of any unused tag combinations
	$('.toDelete').remove();
	//	Scroll Window to Top - this isn't working that well, need to look at another option
	scroll(0,0);
	// $('#index').scrollTo(0);
}

//	Function orginally written by Troelskn : Feb 19, 2007
//	Found at http://snippets.dzone.com/posts/show/3545

function permutations (a)
{
	var fn = function(n, src, got, all) 
	{
		if (n == 0) 
		{
			if (got.length > 0) 
			{
				all[all.length] = got;
	      	}
			return;
		}
		for (var j = 0; j < src.length; j++) 
		{
	    	fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
	    }
	    return;
	}
	var all = [];
	for (var i=0; i < a.length; i++) 
	{
		fn(i, a, [], all);
	}
	all.push(a);
	return all;	
}

//	END

function setDomStructure (me)
{
	//	Get the complete list  of tags
	var mytags = $(me).attr('tags');
		mytags = mytags.split(' ');
	//	Set my scale to big, and wrap me in a div
	$(me).addClass('portraitScaleLrg')
	//	Create an empty string
	var str="";
	//	Loop through the tag list
	for(var i=0;i<mytags.length;i++)
	{	
		//	Add a jquery usable tag
		str += '.'+mytags[i];
		//	add in 
		if(i<(mytags.length-1))
		{
			str += ', ';
		}
	}
	$('.poster')
		.not(str)
		.addClass('portraitScaleSml')
		.wrapAll('<div class="tagSet setBorder extraPadding"></div>');
	//	Now sort all tagged elements
	sortTags(mytags);
	//	Move me to the top of the page
	$('#index').prepend($(me));
	//	Set revert to true
	doRevert = true;
}

function revertDom ()
{
	//	Remove extra stylings from images
	//	Move all posters outside of the dynamic rapper
	$('.poster')
		.removeClass('portraitScaleSml')
		.removeClass('portraitScaleMid')
		.removeClass('portraitScaleLrg')
		.appendTo('#index');
	//	Remove the dynamic poster wrappers
	//$('.tagSet:has(.poster)').appendTo('#index');
	$('.tagSet').remove();
}

/**
 * Simple JQuery Plugin to remove duplicates in an array
 * Author: Keith Deverell 2008
 * Built with functions by Johan Känngård, http://dev.kanngard.net
 */

var CleanArray = {
    combine: function(data) 
	{
		var tmp = new Array();
		for(var i=0;i<data.length;i++){
			tmp = data[i].categories.concat(tmp);
		}
		
		var tmp = CleanArray.unique(tmp);
		return tmp;
    },

	/**
	 * Removes duplicates in the array 'a'
	 * @author Johan Känngård, http://dev.kanngard.net
	 */
	
	unique: function(a)
	{
		var tmp = new Array(0);
		for(i=0;i<a.length;i++)
		{
			if(!CleanArray.contains(tmp,a[i]))
			{
				tmp.length+=1;
				tmp[tmp.length-1]=a[i];
			}
		}
		return tmp;
	},
	
	/**
	 * Returns true if 's' is contained in the array 'a'
	 * @author Johan Känngård, http://dev.kanngard.net
	 */
	
	contains: function(a,e) 
	{
		for(j=0;j<a.length;j++)if(a[j]==e)return true;
		return false;
	},

	indexReturn: function(a,e)
	{
		for(j=0;j<a.length;j++)if(a[j]==e)return j;
		return false;
	}
}

