var compareLinks = {
	items: new Array(),
	compared: new Array(),

	init: function() {
		var t = this;
		$$('#compare .comparing').each(function(i){
			t.compared.push(i.readAttribute('stwCompareId'));
		});

		$$('a.compare').each(function(a) {
			var i = new compareLink(a);
			t.items.push(i);
		});
	},

	update: function() {
		this.items.each(function(link) {
			link.setState();
		});
	},

	remove: function(id) {
		if (-1 != this.compared.indexOf(id)) this.compared = this.compared.without(id);
		this.update();
	},

	clear: function() {
		this.compared = new Array();
		this.update();
	},

	blockRemove: function(a) {
		a = $(a);
		a.up('TR').remove();
		new Ajax.Request(a.readAttribute('href') + 'ajax/');
		this.remove(a.readAttribute('stwCompareId'));
		return false;
	}
}

var compareLink = function(a) {
	this.a = $(a);
	this.id = this.a.readAttribute('stwCompareId');
	this.setState();
	this.a.onclick = this.click.bind(this);

}

compareLink.prototype = {
	a: null,
	id: null,
	state: false,
	div: 'compare',

	click: function() {
		new Ajax.Updater(this.div, this.a.readAttribute('href') + 'ajax/');
		if (this.state) compareLinks.compared = compareLinks.compared.without(this.id);
		else compareLinks.compared.push(this.id);

		this.setState();
		compareLinks.update();

		return false;
	},

	setState: function() {
		this.state = compareLinks.compared.include(this.id);
		this.a.update( this.state ? 'Убрать из сравнения' : 'Добавить к сравнению');
	}

}

document.observe('dom:loaded', compareLinks.init.bind(compareLinks));
