// requires Prototype.js version 1.6.0_rc1 or greater
var MemberList = Class.create({
	initialize: function(column_size) {
		this.hash_fix = false;                      // check to ensure that the members have been put into a hash
		this.list = $$('#membersList ul li:not(.last)');       // each member in the submenu
		this.submenu_lists = $$('#membersList ul'); // now they've changed their minds
		
		this.hash_list = new Hash();                // creates an empty hash object
		this.column_size = column_size || 27;       // usually 27
		
		this.up = $('membersList');
		this.cache = {};
		
		this.fixHash().reorder(window.location.hash.replace(/^#/, ''));
		
		$('reorder-name').observe('click', function() { this.reorder('name'); }.bindAsEventListener(this));
		$('reorder-year').observe('click', function() { this.reorder('year'); }.bindAsEventListener(this));
		
		return this;
	},
	
	fixHash: function() {
		this.hash_fix = true;
		this.list.each(function(member) {
			var name = member.innerHTML.stripTags();
			var surname = $w(name)[1] || name;
			var link = ( $(member.down('a')) ) ? $(member.down('a')).href : false;
			
			this.hash_list.set(
				surname + '__' + name, {
					name : name,
					link_content : name,
					surname : surname,
					link_url : link,
					classNames : $w(member.className)
				}
			);
		}.bind(this));
		
		return this;
	},
	
	reorder: function(reorder_by) { // either reorder by name or year; default is year
		// console.log('reorder', arguments);
		var ordered_by = ( reorder_by == 'name' ) ? 'alphabetically' : 'in order of seniority';
		$('ordered').update(ordered_by);
		
		if ( this.cache.hasOwnProperty(reorder_by) ) {
		
			$(this.up).innerHTML = this.cache[reorder_by];
			
		} else {
			if ( !this.hash_fix ) { this.fixHash(); }
			var list = ( reorder_by == 'name' ) ? this.hash_list.keys().sort() : this.hash_list.keys();
			
			var j = 0;
			
			$(this.submenu_lists).invoke('update'); // empty the submenu <ul>s
			
			list.each(function(member, i) {			
				var link = new Element('a', { href: this.hash_list.get(member).link_url });
				var listr = new Element('li', {'class': this.hash_list.get(member).classNames });
				
				
				if ( this.hash_list.get(member).link_url ) {
				
					link.update(this.hash_list.get(member).link_content);
					listr.insert({ bottom : link });
					
				} else {
				
					listr.update(this.hash_list.get(member).link_content);
					
				}
				
				// check if the <li> should be in the next <ul>
				if ( i == this.column_size || i == this.column_size*2 ) { ++j; }
				
				$(this.submenu_lists[j]).insert({ bottom : listr }); // append the formatted <li> to the members <ul>
			}, this);
			
			$(this.submenu_lists[j]).insert({ bottom: '<li class="last link"><strong><a href="../barristers-and-staff-profiles/door-tenants.asp">Door tenants</a></strong></li>' });
			
			this.cache[reorder_by] = $(this.up).innerHTML;
		}
				
		return this;
	}
});