$(document).ready(function() {
    $('.addWatch').click(function() {
        $(this).next().toggle();
        $(this).toggleClass('addWatchOn');

        return false;
    });

    $('.addWatchLink').click(function(event) {
        if($(this).hasClass('greyed')) {
            return false;
        }

        var watchlistID = $(this).attr('href').slice(1);
        var companyID = $('.compName').attr('id').slice('company_'.length);
        var watchlistRef = $(this);

        $.ajax({
            url: '/watchlists/' + watchlistID + '/companies/' + companyID + '/add',
            success: function() {
                $(watchlistRef).addClass('greyed');

                $(".watchTab .xClose[href='#" + watchlistID + "']").parents('.watchTab').fadeIn();

                $('.addWatchMenuWrap').toggle();
                $('.addWatch').toggleClass('addWatchOn');
            },
            error: function() {
                $('.addWatchMenuWrap').toggle();
                $('.addWatch').toggleClass('addWatchOn');
            }
        })

        return false;
    });
    
    $('.watchTab .xClose').click(function() {
        var watchlistID = $(this).attr('href').slice(1);
        var companyID = $('.compName').attr('id').slice('company_'.length);
        var tabRef = $(this).parents('.watchTab');

        $.ajax({
            url: '/watchlists/' + watchlistID + '/companies/' + companyID + '/delete',
            success: function() {
                $(".addWatchLink[href='#" + watchlistID + "']").removeClass('greyed');
                $(tabRef).fadeOut(300);
            }
        });

        return false;
    });
});