post_comment.js, media.html: Add AJAX for posting comments
[mediagoblin.git] / mediagoblin / static / js / post_comment.js
1 /**
2 * GNU MediaGoblin -- federated, autonomous media hosting
3 * Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 $(document).ready(function(){
20 $(function() {
21 // Hide this button if script is enabled
22 $('.form_submit_buttons').find('input').hide();
23
24 // Include this link if script is enabled
25 $('.form_submit_buttons').append(
26 '<a class="button_action" id="post_comment" type="button">' +
27 'Add this comment </a>');
28
29 $('#post_comment').click(function() {
30 $.ajax({
31 url: $('#postCommentURL').val(),
32 data: $('#form_comment').serialize(),
33 type: 'POST',
34 success: function(response) {
35 var message = $(response).find('.mediagoblin_messages');
36 var commentsInResponse = $($(response).find('.media_comments')).find('li');
37 var commentsInPage = $('.media_comments').find('ul');
38
39 // Post the message
40 message.css({"position":"fixed", "top":"50px", "width":"100%"});
41 $('body').append(message);
42 message.delay(1500).fadeOut();
43
44 // Checking if there is new comment
45 if(commentsInResponse.length != $(commentsInPage).find('li').length) {
46 // Post comment and scroll down to it
47 var newComment = commentsInResponse[commentsInResponse.length - 1];
48 $('#form_comment').fadeOut('fast');
49 $('#button_addcomment').fadeIn('fast');
50 $('#comment_preview').replaceWith("<div id=comment_preview></div>");
51 $(commentsInPage).append(newComment);
52 $('html, body').animate({
53 scrollTop: $(newComment).offset().top
54 }, 1000);
55 }
56 },
57 error: function(error) {
58 console.log(error);
59 }
60 });
61 });
62 });
63 });