var PortfolioSidemenu = {
	el_menus: null,
	el_globalMenu: null,
	el_industryMenu: null,
	el_mediumMenu: null,
	
	selected: null,
	
	options: {
		onChange: null
	},
	
	init: function(options) {
		// Save pointers to elements
		PSM.el_globalMenu = jQuery('#sidemenuGlobal');
		PSM.el_industryMenu = jQuery('#sidemenuIndustry');
		PSM.el_mediumMenu = jQuery('#sidemenuMedium');
		PSM.el_template = jQuery('#sidemenuTemplate')
			.removeAttr('id')
			.remove()
			;
		PSM.el_menus = PSM.el_globalMenu.add(PSM.el_mediumMenu).add(PSM.el_industryMenu);
			
		// Save options
		jQuery.extend(PSM.options, options);
	},
	
	load: function(categories) {
		// Go through each category, turn it into a menu element and append it to the correct menu
		jQuery.each(categories, function(key, val) {
			// Replace slidefilter reference with the actual tag value
			var slidefilter = Portfolio.Tags.getById(val.slidefilter);
			
			PSM.el_template.clone()
				.find('a')
					.attr('name', val.code)
					.attr('slidefilter', slidefilter)
					.attr('clients', val.clients.join(","))
					.html(val.title)
					.click(PSM.onClick)
					.end()
				.appendTo(PSM['el_'+val.type+'Menu'])
				;
		});
		
		// Find the last items in each of the menus and set them to class 'last'
		PSM.el_menus.find('li:last-child').addClass('last');
	},
	
	onClick: function(ev) {
		var obj = PSM.get(this);
		
		// If we're selecting the same category, don't do anything
		if (PSM.selected  &&  PSM.selected.id == obj.id) return;
		PSM.selected = obj;
		
		if (PSM.options.onChange)
			PSM.options.onChange(obj);
		return false;
	},
	
	get: function (id) {
		var item = (typeof id == 'string') ? PSM.el_menus.find('li a[name='+id+']') : jQuery(id);
		if (item.size() == 0) return false;
		var clientList = item.attr('clients') ? item.attr('clients').split(',') : [];
		var result = {
			id: item.attr('name'),
			title: item.html(),
			clients: clientList,
			slidefilter: item.attr('slidefilter')
		};

		if (result.title == 'View All') result.title = 'Our Work';
		return result;
	}
};

var PSM = PortfolioSidemenu;
Portfolio.Sidemenu = PSM;