var Site = {
	start: function() {
		if( Browser.Engine.trident ) Site.fixExplorer();
		/* MT1.2 accepts css selectors as well as style definitions */
		Site.styles = {
			input: '.input',
			checked: '.checked',
			focused: '.focused',
			blurred: '.blurred'
		}

		this.init();
	},
	init: function() {
		var trs = $$('tr.checkbox, tr.radio');

		trs.each(function(tr) {
			tr.set('morph', {duration: 200});
			tr.addClass('pointer');

			var input = tr.retrieve('own:input', tr.getElement('input').store('parent', tr));

			var td = tr.retrieve('own:td', tr.getElement('td.check'));

			td.getElement('input').setStyle('display', 'none');

			var div = tr.retrieve('own:div', new Element('div', {'class': 'input', 'morph': {duration: 140}}).inject(td));

			tr.addEvent('click', function(event) {
				this.toggle(tr);
			}.bind(this) );

			var input = tr.getElement('input');
			if( $( input.get('id') + '.deps') ) {
				input.set('deps', $(input.get('id') + '.deps').get('text'));
			}
		}.bind(this) );

		// Initialise any default checked radio buttons
		if( !document.getElement('input[type=radio]:checked') ) {
			// IE
			$$('body input').each( function(input) {
				if( input.get('checked') ) this.check(input.retrieve('parent'));
			}.bind(this) )
		} else {
			$$('body input:checked').each( function(input) {
				this.check(input.retrieve('parent'));
			}.bind(this) )
		}
	},
	toggle: function(tr) {
		var input = tr.retrieve('own:input')
		if( input.get('checked')) {
			this.uncheck(tr,(!input.get('deps')?false:true));
		} else {
			this.check(tr);
		}
		input.fireEvent('change',input);
	},

	uncheckByName: function(tr, input) {
		$$('input[name=' + input.get('name') + ']').each(function(other) {
			if( other != input ) Site.uncheck(other.retrieve('parent'), true);
		});
	},

	uncheck: function(tr, force) {
		var input = tr.retrieve('own:input');
		if( !force && input.get('type') == 'radio' ) {
			if( input.get('checked') ) return;
		}
		input.set('checked', false);

		var deps = input.get('deps');
		if( deps ) {
			this.uncheckDepending(input.get('id'));
		}
		tr.retrieve('own:div').morph(this.styles.input);
		tr.morph(this.styles.blurred);
	},

	check: function(tr) {
		var input = tr.retrieve('own:input').set('checked', true);

		if( input.get('type') == 'radio' ) {
			this.uncheckByName(tr, input);
		}

		var deps = input.get('deps');
		if( deps ) {
			this.checkDependants(deps.split(','));
		}

		tr.retrieve('own:div').morph(Site.styles.checked);
		tr.morph(this.styles.focused);
	},

	checkDependants: function(deps) {
		deps.each( function(input) {
			input = $(input);
			//if( input && !input.get('checked')) Site.check(input.retrieve('parent'));
			// Above changed as FF will remember checked boxes on refresh (thus highlighting will not work)
			if( input ) this.check(input.retrieve('parent'));
		}.bind(this) );
	},

	uncheckDepending: function(component) {
		var depending = $$('input[deps]').each( function(input) {
			if( input.get('checked') )
				if( input.get('deps').split(',').contains(component)) this.uncheck(input.retrieve('parent'));
		}.bind(this) );
	},

	fixExplorer: function() {
		$$('table').set('cellspacing', 0);
	}
}

var Character = {
	start: function() {
		this.startPoints = 16;
		this.points = 0;

		$$('table.characterSelect input').each( function(input) {
			// Store the cost of this item (minus pre-req's)
			if( input.get('name') ) Character.getCost(input);
		});

		$$('table.characterSelect input').each( function(el) {
			el.addEvent('change', function() {
				Character.points = 0;
				$$('table.characterSelect input').each( function(input) {
					if( input.get('checked') ) {
						this.modify( input.retrieve('cost') );
					}
				}.bind(this) );
				this.update();
			}.bind(this) );
		}.bind(this) );

		this.update();
	},
	modify: function(amount) {
		this.points += amount;
	},
	update: function() {
		$('points').innerHTML = this.startPoints - this.points;
	},

	getCost: function(input) {
		// return the real cost of an item
		if( input && input.retrieve('parent').getElement('td.cost') ) {
			if( !input.retrieve('cost') ) {
				// Need to calculate this one
				var deps = input.get('deps');
				var cost = input.retrieve('parent').getElement('td.cost').innerHTML.replace('[','').toInt();
				if( !deps ) {
					input.store('cost', cost);
				} else {
					// Need to calculate dependancies
					deps = deps.split(',');
					deps.each( function(dep) {
						dep = $(dep);
						cost -= this.getCost(dep);
					}.bind(this) );
					input.store('cost', cost);
				}
			}
			return input.retrieve('cost');
		} else {
			return 0;
		}
	}
}

var OSPList = {
	lookup: null,   /* Text input box */
	textArea: null, /* Plain text list */
	list: null,     /* UL list */
	fallback: null, /* TD that contains the plain text list element */

	start: function() {
		this.lookup = $('OSP.Lookup');
		this.list = $('OSP.All');
		this.fallback = $('OSP.Fallback');
		this.textArea = this.fallback.getElement('textarea');

		$('OSP.LookupContainer').removeClass('hidden');
		this.list.set('html',''); // Need to empty the empty list placeholder

		this.loadTextArea(); // In case of pre-population


		this.fallback.addClass('hidden');

		new Autocompleter.Request.HTML( this.lookup, '/profiles/osplookup/', {
			'indicatorClass': 'autocompleter-loading',
			'injectChoice': function(choice) {
				var text = choice.getFirst();
				var value = text.innerHTML;
				choice.inputValue = value;
				text.set('html', this.markQueryValue(value));
				this.addChoiceEvents(choice);
			}
		} );
		$('OSP.Append').addEvent( 'click', function(event) {
			var event = new Event(event);
			event.stop();

			if( this.lookup.get('value').trim() != '' ) {

				this.makeLI(this.lookup.get('value'));

				this.lookup.set('value','');
				this.processList();
			}
		}.bind(this) );
	},

	loadTextArea: function() {
		if( this.textArea.get('value') != '' ) {
			this.textArea.get('value').split("\n").each( function(item) {
				this.makeLI( item );
			}, this );
		}
	},

	makeLI: function( text ) {
		var temp = new Element('li', {
			'html': '<span>' + text + '</span><a>[ click to remove ]</a>'
		} ).inject(this.list, 'inside');
		temp.addEvent('click', function(element) {
			this.removeLI(temp)
		}.bind(this) ).setStyle('cursor','pointer');
	},

	removeLI: function(li) {
		li.destroy();
		this.processList();
	},

	processList: function() {
		var allOSPs = this.list.getElements('li span').get('text');
		this.textArea.set('value', allOSPs.join("\n"));
	}
}

window.addEvent('domready',function() {
	if( $('OSP.All') ) {
		Site.start();
		Character.start();
		OSPList.start();
	}
});
