function updateLength(field, current, maximum) {
    var remaining = maximum - current;

    field.text('(' + remaining + ' ' + (remaining == 1 ? 'character' : 'characters') + ' available)');
}

$(document).ready(function() {
    $('#submit_url_btn').attr('disabled', false);

    $('.viewComments a').click(function (e) {
        e.preventDefault();
        var private_key = $(this).attr('id').split('_')[1];
        $(this).parent().parent().children('#commentsDisplay_' + private_key).slideToggle('fast');
    });

    $('.newCommentBox .showNewCommentBox').click(function (e) {
        e.preventDefault();
        $(this).parent().parent().children('.addComment').slideToggle('fast');
    });

    $('#expiry_date').datepicker({
        dateFormat: 'D, d M yy',
        minDate: 0
    });
    $('#expiry_date').datepicker('setDate', +7);

    $('#expiry_time').timepickr({
        val: '12:00'
    });

    $('.choice').filter(":radio").attr('checked', false);

    $('.choice').click(function () {
        $('#vote').submit();
    });

    $('#newDilemmaForm').submit(function (e) {
        $('#share').val($('#share_check').is(':checked'));
        $('#twitter_share').val($('#twitter_share_check').is(':checked'));
        $('#twitter_follow').val($('#twitter_follow_check').is(':checked'));

        $('#submit_url_btn').attr('disabled', true);
        // convert the date into seconds from now so we don't have to worry about
        // timezones and shit on the server
        var date = new Date($('#expiry_date').val() + ' ' + $('#expiry_time').val() + ':00');
        var now = new Date();
        var ttl = parseInt((date.getTime() - now.getTime()) / 1000);

        if (ttl < 60) {
            alert('Deadline must be more than 1 minute in the future');
            e.preventDefault();
        }

        $('#deadline').val(ttl);
    });

    $('.add_or_remove_link').click(function (e) {
        e.preventDefault();
        var action_id = $(this).attr('id').split('_');
        var action = action_id[0];
        var id = action_id[1];
        var previous_id = id - 1;

        if (action == 'add') {
            $(this).hide();
            $('#newChoice' + id).slideDown(function () {
                $('#remove_' + previous_id).hide();
                $('#max_choice').val(id);
            });
        }
        else if (action == 'remove') {
            $('#newChoice' + id).slideUp(function () {
                $('#add_' + id).show();
                $('#remove_' + previous_id).show();
            });
            $('#max_choice').val(previous_id);
        }
    });

    $('.add_comment').submit(function (e) {
        var commentTextBox = $(this).find('#newCommentText');

        if (commentTextBox.val().length < 1) {
            return
        }

        $('#no_comments').hide();
        var comments_list = $(this).parent().parent().find('div#comments_list');
        comments_list.html(
                '<div><div class="commentText">'
                        + commentTextBox.val() +
                '</div><div class="closingIn">Added by you just now!</div></div>'
                        + comments_list.html()
                );

        commentTextBox.val('');
        $('#commentTextBox').trigger('keyup');
    });

    $('#dilemma, .choiceRadio').keyup(function (e) {
        $(this).val($(this).val().slice(0, 60));
        updateLength($(this).parent().children('.fieldLength'), $(this).val().length, 60);
        return true;
    });

    $('#detailsBox').keyup(function (e) {
        var length = $(this).val().length;
        var limit = 300;
        var lengthField = $(this).parent().children('.fieldLength');

        var remaining = limit - length;

        if (remaining >= 0) {
            updateLength(lengthField, length, limit);
        }
        else {
            lengthField.html('(Exceeding the limit by ' + remaining * -1 + ' characters)');
        }

        return true;
    });

    $('#newCommentText').keyup(function (e) {
        var excess = $(this).val().length - 800;

        if (excess > 0) {
            $('#commentTextLength').text('Exceeding the comment limit by ' + excess + ' characters')
            $('#commentTextLength').fadeIn('fast');
            $('#addCommentButton').attr('disabled', true);
            $('#addCommentButton').fadeTo('fast', 0.5);
        }
        else {
            $('#commentTextLength').fadeOut('fast');
            $('#addCommentButton').removeAttr('disabled');
            $('#addCommentButton').fadeTo('fast', 1);
        }

        return true;
    });

    $('#tags').tagSuggest({
        tags: $('#possibleTags').text().split(/\s+/),
        sort: false
    });

    $('#dilemma, #detailsBox, .choiceRadio, #newCommentText').trigger('keyup');

    $('#setEmailAddress').submit(function (e) {
        $('#savingSpinner').show();
        e.preventDefault();
        $('#setEmailAddress').ajaxSubmit(function () {
            $('#savingSpinner').hide();
        });
    });
});
