$(function(){

//FAVORITES
(function(){
	var COOKIE_NAME = 'favorites';
	var COOKIE_PARAMS = { path:'/', expires: 7 };
	var favorites = {count:0};
	if( typeof( $.cookie( COOKIE_NAME ) ) == 'string' ){
		favorites = JSON.parse( $.cookie( COOKIE_NAME ) );
		}
	var $counter = $('#fav_counter');
	
	function set_counter(){
		if( favorites.count > 0 ){
			$counter.html( favorites.count+' поз.' );
			}
		else{
			$counter.html('');
			}
		}
	function save_favorites(){
		set_counter();
		$.cookie( COOKIE_NAME, JSON.stringify( favorites ), COOKIE_PARAMS );
		}
		
	function add_favorites( obj ){
		if( typeof( favorites[ obj.type ] ) != 'object' ){
			favorites[ obj.type ] = new Array();
			}
		favorites[ obj.type ].push( obj.id );
		favorites.count++;
		save_favorites();
		process_page();
		}
	
	function remove_favorites( obj ){
		if( typeof( favorites[ obj.type ] ) == 'object' ){
			var found_at = $.inArray( obj.id, favorites[ obj.type ] );
			if( found_at >= 0){
				favorites[ obj.type ].splice( found_at, 1 );
				--favorites.count;
				save_favorites();
				//process_page();
				}
			}
		}
	
	function is_in_favorites( obj ){
		if( typeof( favorites[ obj.type ] ) == 'object' && $.inArray( obj.id, favorites[ obj.type ] ) >= 0 ) return true;
		else return false;
		}
	
	function process_page(){
		$('div.favorites_button').each(function(){
			var $this = $(this);
			var this_obj = { id:$this.attr('obj_id'), type:$this.attr('obj_type') };
			if( is_in_favorites( this_obj ) ){
				$this.html('<input class="del" type="button" value="Избранное" title="Удалить из избранного"/>');
				$('input', $this).click( function(){ remove_favorites( this_obj ); process_page(); } );
				}
			else{
				$this.html('<input class="add" type="button" value="Избранное" title="Добавить в избранное"/>');
				$('input', $this).click( function(){ add_favorites( this_obj ); } );
				}
			});
		$('input.f_list_delete').each(function(){
			var $this = $(this);
			$this.click(function(){ remove_list_el( { id:$this.attr('obj_id'), type:$this.attr('obj_type') } ) });
			});
		$('input.f_list_clean').click(function(){
			favorites = {count:0};
			save_favorites();
			set_counter();
			$('#fav_conteiner').remove();
			$('#fav_nothing').show();
			});
		}
	
	function remove_list_el( obj ){
		$('#'+obj.type+'_'+obj.id).remove();
		remove_favorites( obj );
		if( !(favorites.count > 0) ){
			$('#fav_conteiner').remove();
			$('#fav_nothing').show();
			}
		else if( typeof(favorites[ obj.type]) == 'object' && !(favorites[ obj.type].length > 0) ){
			$('#fav_'+obj.type).remove();
			}
		}
	
	process_page();
	set_counter();
	
	
	
	})();


});