Favorite = {
    add: function(link,id) {
        var link = link;
        // Send request to server
        $.getJSON('/favorite/ajax-add-to-favorite/', {
            id: id
        }, function(data,status){
            if (data) {
                Favorite.setCount(data.count);
                if (data.ok) {
                    link.hide();
                    $('a#remove_favorite_' + link.attr('id').replace('add_favorite_','')).show();
                }
            }
        });
    },

    remove: function(link,id) {
        var link = link;
        // Send request to server
        $.getJSON('/favorite/ajax-remove-from-favorite/', {
            id: id
        }, function(data,status){
            if (data) {
                Favorite.setCount(data.count);
                if (data.ok) {
                    link.hide();
                    $('a#add_favorite_' + link.attr('id').replace('remove_favorite_','')).show();
                    if ($('#favorites_count_h1').length) {
                        // We view favorites page, so we have to remove all data
                        link.parents('.item').remove();
                    }
                }
            }
        });
    },

    setCount: function(count) {
        $('#user_favorites_count').text(count);
    }
}

$(function(){
    $('span.favorite a').click(function(){
        link = $(this);
        action = link.attr('id').split('_');

        if (action[0]=='add') {
            Favorite.add(link,action[2]);
        } else {
            Favorite.remove(link,action[2]);
        }

        return false;
    });
});

