$(document).ready(function() {
    $.fn.add_package_to_compare = function() {
        if ($(this).hasClass('incompare'))
            return true;
        var id = $(this).nextAll('input.id').val();
        var ai = $(this).nextAll('input.arrival');       
        var arrival = (ai.length == 1)? ai.val() : null;
        var button = this;        
        $.json('package', 'addtocompare',  {id : id, arrival : arrival}, function(r) {        
            if (r.html) { 
                $('.quick_compare').remove();                   
                $('#main_header').append(r.html);
                $.remove_package_to_compare();                   
                $(button)
                    .addClass('incompare')
                    .text(r.viewbuttontext);                
            }        
        });
        return false;    
    }
    $.remove_package_to_compare = function() {
        $('.quick_compare .item a.del').click(function() {      
            var id = $(this).attr('href').split('/').pop();
            element = this;
            $.json('package', 'removefromcompare',  {id :id}, function(r) {
                if (r.addbuttontext) {
                    $(element).parent().remove();
                    $('input.id[value=' + id + ']').prev()
                        .removeClass('incompare')
                        .text(r.addbuttontext);
                    if ($('.quick_compare .item').length == 0)
                        $('.quick_compare').remove();
                                                    
                }
            });                         
            return false;
        });
    }  
    $.remove_package_to_compare();
    $('a.comparebutton').click($.fn.add_package_to_compare);
});            

