
Tauri.Activation = Class.create({
	
	planets : null,
	
	current: null,
	
	initialize : function () {
		this.planets = $H();
		$('p-submit').observe('click', this.submit.bind(this));
	},
		
	select : function (id) {
		if (this.current) {
			this.current.deactivate();
			$('pc-planet').update('-');
			$('pc-sector').update('-');
		}
		this.current = this.planets.get(id);
		this.current.activate();
	},
	
	addPlanet : function (id, opts) {
		this.planets.set(id, (new Tauri.Activation.Planet(id, this.select.bind(this), opts)));
	},
	
	submit : function () {
		if (this.current && !this.sent) {
			this.sent = true;
			$('f-planet').value = this.current.planetId;
			$('f-sector').value = this.current.sector;
			$('f-activation').submit();
		}
	}
		
});

Tauri.Activation.Planet = Class.create({
	
	sectors : ['NW', 'NE', 'SW', 'SE'],
	
	id : null,
	
	planetId: 0,
	name : '-',
	users: 0,
	free: 0,
	usersNW: 0,
	usersSW: 0,
	usersNE: 0,
	usersSE: 0,
	freeNW: 0,
	freeSW: 0,
	freeNE: 0,
	freeSE: 0,
	
	sector : 'NE',
	
	onSelect : null,
	
	active : false,
	
	initialize : function (id, onSelect, opts) {
		var t = this;
		this.id = id;
		this.onSelect = onSelect;
		$H(opts).each(function (p) {
			t[p.key] = p.value;
		});
		$('p' + this.id + '-btn').observe('click', this.select.bindAsEventListener(this));
		$('p' + this.id + '-name').update(this.name);
		$('p' + this.id + '-players').update(this.users);
		this.sectors.each(function (sector) {
			$('p' + t.id + '-s' + sector + '-players').
				update(t['users' + sector]);
			$('p' + t.id + '-s' + sector + '-btn').
				observe('click', t.setSector.bindAsEventListener(t, sector));
		});
	},
	
	select : function (event) {
		Event.stop(event);
		if (!this.active) {
			this.onSelect(this.id);
		}
		return false;
	},
	
	setSector : function (event, sector) {
		this.select(event);
		if (this.sector !== sector) {
			this.sector = sector;
			this.write();
			this.writeSectors();
		}
		return false;
	},
	
	write : function () {
		$('pc-planet').update(this.name);
		$('pc-sector').update(this.sector);	
	},
	
	writeSectors : function () {
		var t = this;
		this.sectors.each(function (sector) {
			var ico, img;
			ico = $('p' + t.id + '-s' + sector + '-ico');
			img = '/sector' + (t.active ? (t.sector === sector ? '-select' : '') : '-gray') + '.gif';
			ico.src = ico.src.replace(/\/sector[^\.]*\.gif$/, img);
		});
	},
	
	writeIco : function () {
		var ico = $('p' + this.id + '-ico');
		ico.src = ico.src.replace(/\/planet[0-9]+[^\.]*\.gif$/, '/planet' + this.id + (this.active ? '-select' : '') + '.gif');
	},
	
	activate : function () {
		this.active = true;
		this.write();
		this.writeIco();
		this.writeSectors();
	},
	
	deactivate : function () {
		this.active = false;
		this.writeIco();
		this.writeSectors();
	}
	
})


