var Favorites = {};

/**
 * Массив с избранным
 */
Favorites.favorites = null;

Favorites.initFavorites = function(favorites) {
	this.favorites = [];
	var j = 0;
	for(var i in favorites) {
		if(!favorites.hasOwnProperty(i) || isNaN(parseInt(favorites[i]))) {
			continue;
		}
		this.favorites[j] = parseInt(favorites[i]);
		j ++;
	}
	return this;
};
/**
 * Добавляем в избранное
 *
 * @param {int} advertId
 */
Favorites.add = function(advertId) {
	var t = this;
	$.post('/irr/ajax/favorites.php?' + Math.random(), {op: 'add', id: advertId})
	.success(function(data) {
		if(data.success) {
			t.initFavorites(data.data.items)
				.updateCounter();
		} else {
			alert(data.msg);
		}
	});
};

/**
 * Обновляем сцётчик вверху страницы
 */
Favorites.updateCounter = function() {
	if($('#headerFavoritesCount').length) {
		$('#headerFavoritesCount').html(this.getAll().length);
	}
};

/**
 * @return Array
 */
Favorites.getAll = function() {
	if(null !== this.favorites) {
		return this.favorites;
	}
	if($.cookie('una')) {
		var favString = $.cookie('favorites');
		this.initFavorites(favString ? favString.split(',') : []);
	} else {
		var t = this;
		$.ajax({
			url: '/irr/ajax/favorites.php?' + Math.random(),
			type: 'POST',
			async: false,
			dataType: 'json',
			data: {op:'getFavList'}
		})
		.success(function(data){
			if(data.success) {
				t.initFavorites(data.data.items);
			} else {
				t.favorites = [];
			}
		});
	}
	return this.favorites;
};
