 $(document).ready(function(){
   $('.vote').click(comment_vote);
   $('.unhide_comment').click(unhide_comment);
   $('#calendar_id td').mouseenter(show_post_event);
   $('#calendar_id td').mouseleave(hide_post_event);
   $('table.sortable').tablesorter();
 });





function show_post_event() {
    // adds a small link to post an event on a given date

    var months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    var thisid = this.id;
    var dateid = thisid.replace('calendar_id_cell_', '');
    var thisdate = dateid.split('-');
    var url = '/post_event?y=' + thisdate[0] + '&m=' + thisdate[1] + '&d=' + thisdate[2];

    var newlink = $(document.createElement('a'));
    newlink.attr('id', thisid.replace('_cell_', '_innerdiv_'));
    newlink.attr('href', url);
    newlink.attr('title', 'Post a new event on '+months[thisdate[1]]+' '+thisdate[2]+', '+thisdate[0]);
    newlink.addClass('post_event_on_this_day');
    newlink.text('Post Event');

    $('#'+thisid+' div').append(newlink);

}

function hide_post_event() {
    // removes small link to post an event on a given date
    var thisid = this.id;
    var divid = thisid.replace('_cell_', '_innerdiv_');

    if ($('#' + divid + '').length > 0) {
        $('#' + divid + '').remove();
    }
}

function comment_vote() {
    // posts a comment vote to the site and updates the HTML page with the vote result
    var thisname = this.name;
    var comment_id = this.id.replace(thisname+'-', '');
    if (thisname == 'upvote') {
        var formdata = { 'comment_id': comment_id, 'upvote': 1 }
    } else {
        var formdata = { 'comment_id': comment_id, 'downvote': 1 }
    }
    $.ajax({
        async: false,
        type: 'POST',
        url: '/ajax/post_vote/',
        data: formdata,
        success: function(html){
            $('#vote-form-container-'+comment_id).html(html);
        }
    });
    $('.vote').click(comment_vote); // re-attach comment vote event handlers
    return false;
}

function unhide_comment() {
    // posts a request to unhide a hidden comment with a low score
    var comment_id = this.id.replace('unhide_this_comment_', '');

    var formdata = { 'unhide_comment_id': comment_id }

    $.ajax({
        async: false,
        type: 'POST',
        url: '/ajax/unhide_comment/',
        data: formdata,
        success: function(html){
            $('#comment_class_for_'+comment_id).html(html);
        }
    });
    $('.vote').click(comment_vote); // re-attach comment vote event handlers
    return false;
}
