var News = {

	// Config
	path : '/',
	template : 2934,
	columns : 4,
	imageWidth : 100,
	profileUrlPrefix : '/page/Our_Team/All_Team/',
	searchUrlPrefix : '/page/Our_Team/',
	urlCache : null,

	// DOM Elements
	content : null,
	spinner : null,
	heading : null,
	filters : {},
	submitButton : null,

	init: function() {

		News.content			= $('team-items-container');
		News.spinner			= News.content ? new Spinner(News.content) : new Spinner('final-content');
		News.heading			= $('position-title');
		News.urlCache			= new Hash();

		News.submitButton		= $('filter-search');
		News.filters.team		= $('filter-team');
		News.filters.position	= $('filter-position');
		News.filters.profile	= $('filter-profile');

		News.addEventListeners();
		News.loadStateFromUrl();
	},

	// Listen for value changes on the button.
	addEventListeners: function() {
		News.submitButton.addEvent('click', function() {

			// If user has filtered for a specific person then go to that profile.
			if (News.filters.profile.value) {
				document.location = News.filters.profile.value;
			}

			// Run searches from a central URL
			else if (document.location.pathname != News.searchUrlPrefix) {
				News.redirectToSearchUrl();
			}
			
			//Default case
			else {
				News.saveStateToUrl();
				News.search();
			}
		});
	},

	// Get fragment from URL and load values into select boxes.
	loadStateFromUrl : function() {

		// Values are encoded in URL hash seperated by hypen
		var values = String.split(new URI().get('fragment'), '-');
		var index = 0;

		// Change input values based on URL hash.
		for (var name in News.filters) {
			if (values.length > index && typeof values[index] != 'undefined') {
				News.filters[name].selectedIndex = values[index];
			}
			index++;
		}

		// Was user filtering? Run the filter again.
		if (values.length) {
			News.search();
		}
	},

	// Get values from select boxes.
	getStateHash : function() {
		var filters = [];
		var active = false;
		var selectedIndex = null;

		for (var name in News.filters) {
			selectedIndex = News.filters[name].selectedIndex;
			active = active || (selectedIndex > 0);
			filters.push(selectedIndex);
		}
		return active ? filters.join('-') : '';
	},

	// Get values from select boxes and tack onto URL.
	saveStateToUrl : function() {
		document.location.hash = News.getStateHash();
	},

	// Go to search page on main URL.
	redirectToSearchUrl : function() {
		var hash = News.getStateHash();
		if (hash) {
			document.location = News.searchUrlPrefix + '#' + hash;
		}
	},

	// Load items from the filters...
	search: function() {
		var urls = [];
		var responses = [];
		var heading = [];

		// Apply select box filters
		var applyFilter = function(select) {
			if (select.value) {
				urls.push(select.value);
				heading.push(select.options[select.selectedIndex].text);
			}
		};

		// Get list of all URLs to filter
		applyFilter(News.filters.team);
		applyFilter(News.filters.position);
		
		// Run after each filter has returned
		var complete = function(response) {
			responses.push(response);
			if (responses.length == urls.length) {
				News.spinner.hide(true);
				News.loaded(responses);
				News.heading[heading.length ? 'show' : 'hide']();
				News.heading.set('text', heading.join(' '));
			}
		}

		// Do the requests
		if (urls.length) {
			News.spinner.show(true);
			News.content.empty();

			urls.each(function(url) {
				News.load(url, complete);
			});
		}
	},

	// Load data from URL
	load: function(url, callback) {

		if (News.urlCache.has(url)) {
			callback.call(this, News.urlCache.get(url));
			return;
		}
		
		News.content.empty();
		new Request.JSON({
			url: News.path + 'index.php' +
				'?action=getPageFromName' +
				'&page=' + url.replace(/\/page\//, '') +
				'&rtemplate=' + News.template +
				'&type=json',
			onComplete: function(response) {
				News.urlCache.set(url, response);
				callback.call(this, response);
			}
		}).send();
	},

	// Parse a set of responses and show items which appear in ALL responses.
	loaded: function(responses) {
		var count = {};
		var nodes = {};

		// Iterate through all responses, tracking how often each node appears
		responses.each(function(response) {
			if (response !== null && typeof response == 'object' && typeof response.items == 'object') {
				for (var key in response.items) {
					if (key != 'final') {
						count[key] = typeof count[key] == 'undefined' ? 1 : count[key] + 1;
						nodes[key] = response.items[key];
					}
				}
			}
		});

		// Get array of node which appear in every response
		var intersected = [];
		for (var key in count) {
			if (count[key] == responses.length) {
				intersected.push(nodes[key]);
			}
		}

		News.show(intersected);
	},

	// Update the content container with either list of items or error message.
	show: function(nodes) {

		// If there are no items then tell the user
		if (nodes.length == 0) {
			new Element('p', {
				'text' : 'None of our team matches your query. Please try again.'
			}).inject(News.content);
			return;
		}

		// Add list to contain nodes.
		var ul = new Element('ul', {
			'id' : 'team-items'
		}).inject(News.content);

		// Add each node to the list.
		nodes.each(function(item) {

			var li = new Element('li', {
				'class' : item.type + (item.ext ? ' ' + item.ext : '')
			});

			var titleDiv = new Element('div', {
				'class' : 'item-title'
			});

			var titleA = new Element('a', {
				'target' : item.type == 'document' ? '_blank' : '',
				'href' : News.normalizeProfileUrl(item.pageurl),
				'title' : item.title,
				'text' : item.title
			});

			var imageDiv = new Element('div', {
				'class' : 'item-photo'
			});

			var imageA = new Element('a', {
				'target' : item.type == 'document' ? '_blank' : '',
				'href' : News.normalizeProfileUrl(item.pageurl),
				'title' : item.title
			});

			var image = new Element('img', {
				'src' : item.photo || '/images/interface/unknown.jpg',
				'alt': item.title,
				'width': News.imageWidth,
				'height': null
			});


			// Add item parts to containers
			titleA.inject(titleDiv);
			imageA.inject(imageDiv);
			image.inject(imageA);

			// Add containers to list item
			imageDiv.inject(li);
			titleDiv.inject(li);

			// Add list item to list
			li.inject(ul);
		});

		//Add clearing element
		new Element('li', {
			'class' : 'team-clear'
		}).inject(ul);
	},

	normalizeProfileUrl : function(url) {
		return url.replace(new RegExp('/page/Our_Team/.*?/.*?/'), News.profileUrlPrefix);
	}
};

window.addEvent('domready', News.init);
