function Favorites(options) {
    
    this.vehicle_ids = options.vehicle_ids || new Array();
    this.url_add = options.url_add;
    this.url_remove = options.url_remove;
    this.url_fragment = options.url_fragment;
    this.url_switcher = options.url_switcher;
    this._current_id = null;
    
}

Favorites.prototype = {
    setCurrentId: function(id) {
        this._current_id = id;
    },
    
    add: function(vehicle_id, callback) {
        if ($.inArray(vehicle_id, this.vehicle_ids) >= 0) {
            return false;
        }        

        if (this.vehicle_ids.length >= 5) {
            tb_show('', this.url_switcher + '?id=' + vehicle_id +'&TB_iframe=true&height=250&width=720', null);
            return false;
        }
        
        var self = this;
        var random = Math.floor((Math.random() * 1e10))
       
        $.getJSON(this.url_add, { id: vehicle_id, random: random }, function(data) {
            if (data.success) {
                $('#remove-from-favorite').show();
                $('#add-to-favorite').hide();
                self._createNode(vehicle_id);
                self.vehicle_ids.push(vehicle_id);
                if (callback) {
                    callback();
                }
            }
        });
        
        return true;

    },
    
    remove: function(vehicle_id, callback) {

        var self = this;

        var idx = $.inArray(vehicle_id, this.vehicle_ids);
        if (idx >= 0) {
            this.vehicle_ids.splice(idx, 1);
        }
        
        var random = Math.floor((Math.random() * 1e10));
        $.getJSON(this.url_remove, { id: vehicle_id, random: random }, function(data) {
            if (data.success) {
                var elm = $("#favorites ul li div[rel=" + vehicle_id +"]");
                elm.fadeOut("normal", function(){
                    $(this).remove();
                });
        
                if (parseInt(vehicle_id, 10) == parseInt(self._current_id, 10)) {
                    $('#remove-from-favorite').hide();
                    $('#add-to-favorite').show();
                }
                if (callback) {
                    callback();
                }
            }
        });
    },
    
    _createNode: function(id)
    {
        var elm = $('#favorite-vehicle-'+ id);
        var self = this;
        $.get(this.url_fragment, { id: id }, function(data, status){
            
            // Search empty container
            var containers = $('#favorites ul li').not(':has(div)');
            if (containers.length > 0) {
                node = $(data);
                node.hide();
                
                node.find('a.bin').click(function(){
                    self.remove(id);
                    return false;
                });
                
                $(containers.get(0)).append(node);
                node.fadeIn();
            }

        });
              
    }
};
