(function(){
    var favorites = {};
    favorites.list = [];
    favorites.in_favor_image = '/static/images/favorites_on_icon16.png';
    favorites.not_in_favor_image = '/static/images/favorites_icon16.png';

    favorites.add_to_favorites = function(lot_id) {
        favorites.list.push(lot_id);
        favorites.list_to_storage();
    };

    favorites.remove_from_favorites = function(lot_id, pos) {
        favorites.list.splice(pos, 1);
        favorites.list_to_storage();
    };

    favorites.list_to_storage = function() {
        window.localStorage.setItem('favorites', favorites.list.join('-'));
        favorites.check_favorites_link();
    };

    favorites.check_favorites_link = function() {
        var _has_favorites = favorites.list.length > 0;
        var _link_exist = $('#id_favorites').length > 0;
        if (_has_favorites && !_link_exist) {
            $('#id_auth_top').append('<a href="/favorites/" id="id_favorites" class="top_line_link">Избранное</a>');
            $('#id_favorites').click(favorites.click_favorites);
        }
        if (!_has_favorites && _link_exist) {
            $('#id_favorites').unbind().remove();
        }
    };

    favorites.pk = function(el) {
        return $(el).attr('id').replace('favorites', '');
    };
    
    favorites.click = function(e) {
        e.preventDefault();
        var _lot_id = favorites.pk(this);
        var _pos = $.inArray(_lot_id, favorites.list);
        if (_pos < 0) {
            favorites.add_to_favorites(_lot_id);
            $(this).children('img').attr('src', favorites.in_favor_image);
        }
        else {
            favorites.remove_from_favorites(_lot_id, _pos);
            $(this).children('img').attr('src', favorites.not_in_favor_image);
        }
    };

    favorites.load_from_storage = function() {
        var _list = [];
        if (window.localStorage.hasOwnProperty('favorites')) {
            _list = window.localStorage.getItem('favorites').split('-');
        }
        $(_list).each(function(inx, item) {
            if (item) {
                favorites.list.push(item);
            }
        });
    };

    favorites.click_favorites = function(e) {
        e.preventDefault();
        if (favorites.list.length > 0) {
            location.href = probegauto.favorites_base_url + favorites.list.join('-');
        }
    };

    document.probegauto_attach_favorites = function() {
        $('a.favorites').each(function(inx, el){
            var _lot_id = favorites.pk(el);
            var _pos = $.inArray(_lot_id, favorites.list);
            if (_pos >= 0) {
                $(this).children('img').attr('src', favorites.in_favor_image);
            }
            $(el).click(favorites.click);
            $(el).removeClass('favorites');
        });
    };

    favorites.init = function() {
        favorites.load_from_storage();
        document.probegauto_attach_favorites();
        favorites.check_favorites_link();
    };
    $().ready(favorites.init);
}) ( );

