/**
 * The ListConverter class
 * 
 */
var ListConverter = new Class({
	
	/**
	 * Initializes the ListConverter object
	 * 
	 * @constructor
	 */
	initialize: function(el) {
		this._list = $E('ul', el);
		
		// Find the type
		if(el.hasClass('project'))
			this._type = ListConverter.PROJECT;
		else
			this._type = ListConverter.CLIENT
		
		var newselect = new Element('select', {
			'events': {
				'change': function() {
					document.location = this.options[this.selectedIndex].value;
				}
			}
		});
		
		$ES('li a', this._list).each(function(anch) {
			sel = (anch.getAttribute('rel') == 'selected') ? 'selected' : '';
			this.newoption = new Element('option', {
				'value': anch.getAttribute('href'),
				'selected': sel
			});
			this.newoption.setHTML(anch.innerHTML);
			this.newoption.injectInside(newselect);
		});
		el.empty();
		

		this.dummyform = new Element('form');
		newselect.injectInside(this.dummyform);
		
		this.dummyform.injectInside(el);
		
		// Set the selected value
		this.updateSelected(el);
		el.style.overflow = 'visible';
		el.style.height = 'auto';
	},
	
	updateSelected: function(el) {
		this._list = $E('select', el);
		
		var docloc = new String(document.location)
		docloc = docloc.substr(docloc.lastIndexOf('/') + 1);
		
		if (this._type == ListConverter.CLIENT) {
			// Client uses everything before '_'
			docloc = docloc.substr(0, docloc.lastIndexOf('.'));
			if (docloc.indexOf('_') != -1) {
				docloc = docloc.substr(0, docloc.lastIndexOf('_'));
			}
			
			for (var o = 0; o < this._list.options.length; o++) {
				anchloc = this._list.options[o].getAttribute('value');
				anchloc = anchloc.substr(anchloc.lastIndexOf('/') + 1);
				anchloc = anchloc.substr(0, anchloc.lastIndexOf('.'));
				if (anchloc.indexOf('_') != -1) {
					anchloc = anchloc.substr(0, anchloc.lastIndexOf('_'));
				}
				
				if (anchloc == docloc) {
					this._list.selectedIndex = o;
					break;
				}
			}
		} else if(this._type == ListConverter.PROJECT) {
			// Project uses the full name
			for (var o = 0; o < this._list.options.length; o++) {
				anchloc = this._list.options[o].getAttribute('value');
				anchloc = anchloc.substr(anchloc.lastIndexOf('/') + 1);
				
				if(anchloc == docloc) {
					this._list.selectedIndex = o;
					break;
				}
			}
		}
	}
});

// Type enum
ListConverter.CLIENT = 0;
ListConverter.PROJECT = 1;

/**
 * Adds the event to the window onLoad function
 */
$(window).addEvent('domready', function() {
	$$('div.convertlist').each(function(el) {
		new ListConverter(el);
	});
});