view = {

    cookie : {
        expires: 365,
        path: root
    },

    init : function() {

        $('.favorite').click(function() {
            $(this).html(view.favorite(this.rel) ? 'удалить из избранного' : 'добавить в избранное');
        });

        $('.toName').hover(view.showTip, view.hideTip);

        view.calculate();

    },

    favorite : function(aid) {

        var list = $.cookie('fav');
        var item;

        if(list === null) {
            $.cookie('fav', aid, view.cookie);
            view.calculate();
            return true;
        }

        list = list.split(',');
        item = list.search(aid);

        if(item === null) list.push(aid);
        else delete list[item];

        list = list.join(',').replace(/^,+|,+$/g, '').replace(/,,+/g, ',');

        $.cookie('fav', list, view.cookie);

        view.calculate();

        return item === null;

    },

    calculate : function() {

        var fav = $.cookie('fav');
        var num = fav ? fav.split(',').length : 0;
        var obj = $('#favoriteContainer');

        $('#favoriteCount').html(num.toString());
        num ? obj.slideDown(300) : obj.slideUp(300);

    },

    deleteComment : function (id) {

        confirm('Удалить комментарий?') &&

        $.post(
            root + 'ajax/comment',
            {id : id},
            function(data) {
                if(data) {
                    alert(data);
                    return false;
                }
                $('#comment-'+ id).slideUp(300);
            }
        );

    },

    showTip : function() {

        var obj = $('#tooltip');
        var com = $('#comment-'+ this.id);

        if(!com.length) return false;

        var pos  = $(this).offset();
        pos.top += $(this).innerHeight();

        obj.css(pos).html(com.html()).fadeIn(100);

    },

    hideTip : function() {
        $('#tooltip').fadeOut(100);
    },

    reply : function(cid) {
        $('input[name="rid"]').val(cid);
        $('textarea[name="text"]')[0].focus();
    }

}

Array.prototype.search = function(needle) {

    for(var i in this) if(this[i] == needle) return i;
    return null;
    
}


$(view.init);
