var Favorites = new Class({

	options: {
		'empty-message': 'You have no property offers bookmarked here'
	},

	cookieKey: 'CakeCookie[favorites]',

	favorites: null,

	initialize: function(options) {
		this.setOptions(options);
		this.favorites = this.read();
		$ES('a.favourites').each(function(el) {
			el.addEvent('click', this.favorite.bindWithEvent(this));
		}, this);		
	},

	favorite: function(e) {
		el = e.stop().target;
		id = this.getId(el);
		if (this.favorites.contains(id)) {
			this.off(el);
			this.favorites.remove(id);
			if ($('my-favorites')) 
			{				
				container = el.getParent().getParent().getParent();
				container.remove();
				if (this.favorites.length == 0) 
				{
					new Element('p', {'class': 'instructions empty'}).setHTML(this.options['empty-message']).injectAfter($('title'));
				}
			}
		} else {
			this.on(el);
			this.favorites.push(id);
		}

		this.write();
	},

	getId: function(el) {
		return el.id.split('-').getLast();
	},

	on: function(el) {
		el.addClass('on');

		var tmp = el.innerHTML;
		el.innerHTML = el.rel;
		el.rel = tmp;
	},

	off: function(el) {
		el.removeClass('on');
		var tmp = el.innerHTML;		
		el.innerHTML = el.rel;		
		el.rel = tmp;		
	},

	read: function() {
		favs = Cookie.get(this.cookieKey);
		if (!favs) {
			favs = new Array();
		} else {
			favs = favs.split(',');
		}
		return favs;
	},

	write: function() {
		Cookie.set(this.cookieKey, this.favorites, {path: '/', duration: 365});
	}
});

Favorites.implement(new Options());

window.addEvent('domready', function() {
	new Favorites();
});

