
var favs = new Hash({
	decodeURL: function (str) {
		str = unescape(str);
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < str.length ) {
 
			c = str.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = str.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = str.charCodeAt(i+1);
				c3 = str.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	},
	fromCookie: function() {
		var str = Cookie.read('favorites');
		if (!str)
			return;
		var sarr = str.split('&');
		var key;
		var value;
		for(var i=0; i<sarr.length; i++) {
			key = this.decodeURL(sarr[i]).split('=');
			value = key[1].split('::');
			this.addFav(key[0], value[0], value[1]);
		}
	},
	saveCookie: function() {
		Cookie.write('favorites', Hash.toQueryString(this.filter(function(value, key) {
			return !/fromCookie|saveCookie|decodeURL|addFav|delFav/.test(key);
		})), {
			'domain': Html.urlBase,
			'path': Html.uriBase,
			'duration': 5
		});
	},
	addFav: function(id, street, url) {
		var fvcont = $('favorites');
		if (!fvcont)
			return;
		
		if ($(id))
			return;
		
		var d = new Element('div', { 'id': id, 'class': 'fav' });
		
		d.set('html', "\t<a href=\"#\" class=\"delfav\" onclick=\"favs.delFav('"+id+"'); return false;\"</a><a href=\""+url+"\">"+id+"</a>\n\t"+street+"\n");
		d.inject(fvcont, 'bottom');
		
		this.set(id, street+'::'+url);
		this.saveCookie();
	},
	delFav: function(id) {
		if (this.has(id))
			this.erase(id);
		if ($(id))
			$(id).dispose();
		this.saveCookie();
	}
})

document.addEvent('domready', function() {
	// render favorites from cookie!
	var fvcont = $('favorites');
	if (!fvcont)
		return;
	
	favs.fromCookie();
});
