//
// reuires jquery, jquery.cookie
//

var
FAV = {
	ids: [],
	text: null,

	init: function()
	{
		$.each($('.flat ul.flat-service a[rel="fav"]'), function(i, val) {
			//alert(this.nodeName);
			$(val).click(function(){
				$(this).html(FAV.toggle(parseInt(this.parentNode.parentNode.id.substring(1), 10)))
				return false;
			})


			if ($.inArray(parseInt(this.parentNode.parentNode.id.substring(1), 10), FAV.ids) != -1) {
				$(this).html('Удалить из избранного')
			}
		})
	},


	prepare: function()
	{

		if (ids = document.cookie.match(/\bfav=([^;]+)/)) {

			FAV.ids = unescape(ids[1]).split(',')

			FAV.ids = $.map(FAV.ids, function(n, i){
				return parseInt(n, 10)
			})
		}
	},


	toggle: function(id_flat)
	{

		if ($.inArray(id_flat, FAV.ids) != -1) {

			FAV.ids = $.grep(FAV.ids, function(n, i){
				return (n != id_flat)
			})
			value = FAV.ids.join(',')
			FAV.text = 'Добавить в избранное'
		} else {

			FAV.ids.push(id_flat)
			value = FAV.ids.join(',')
			FAV.text = 'Удалить из избранного'
		}


		var expiredays = 360
		var exdate = new Date()
		exdate.setDate(exdate.getDate()+expiredays)


		document.cookie="fav="+escape(value)+"; path=/; expires="+exdate.toGMTString()


		FAV.saved()

		return FAV.text
	},


	saved: function()
	{
		num = FAV.ids.length
		if (num) {

			$('a#fav span').text(num)
			$('#fav').show()
		} else {

			$('#fav').hide()
			$('a#fav span').empty();
		}
	}
}

FAV.prepare()

$(function(){ 
FAV.init() 
FAV.saved() 
})

