REPLY_OK = 0;
REPLY_EMPTY = -1;
REPLY_BAD_USER = -2;

function checkReply(user, status)
{
    var re_user = new RegExp('@' + user + '([^a-zA-Z0-9_]|$)', 'gi');
    var empty = ('' == status.replace(re_user, '').replace(/[^a-zA-Z]/g, ''));
    if (empty) {
        return REPLY_EMPTY;
    }

    re_user = new RegExp('@' + user + '([^a-zA-Z0-9_]|$)', 'i');
    if (!re_user.test(status)) {
        return REPLY_BAD_USER;
    }

    return REPLY_OK;
}

$(function() {
    $('a.getnew').click(function() {
        $('.tweet').load('/getnew');
    });

    
    var keyHandler = function() {
        var len = 140 - $(this).val().length;
        $('#remaining').html(len).show();
    }
    $('#status').keypress(keyHandler).keydown(keyHandler).keypress();

    var fadeOutNotifications = function() {
        $('#notifications div.notification.success').fadeTo(5000, 0);
    }
    setTimeout(fadeOutNotifications, 5000);

    $('#status').focus(function() {
        $('#sign-in-notice').show();
    });

    $('#reply-form').submit(function() {
        var user = $('.message .user').html();
        var status = $('#status').val();

        var res = checkReply(user, status);
        if (res == REPLY_OK) {
            $('.error-notice').hide();
            return true;
        } else if (res == REPLY_BAD_USER) {
            $('#empty-status-notice').hide();
            $('#bad-reply-notice').show();
            return false;
        } else if (res == REPLY_EMPTY) {
            $('#bad-reply-notice').hide();
            $('#empty-status-notice').show();
            return false;
        }

        return true;
    });
});



