]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/js/qna.js
5b1a5fef31eb073a3a02b3c006a988c92710c84e
[quix0rs-gnu-social.git] / plugins / QnA / js / qna.js
1 var QnA = {
2
3     // @fixme: Should use ID
4     close: function(form, best) {
5         var notice = $(form).closest('li.hentry.notice.question');
6
7         notice.find('input#qna-best-answer,#qna-question-close').hide();
8         notice.find('textarea').hide();
9
10         var list = notice.find('ul');
11
12         notice.find('ul > li.notice-answer-placeholder').remove();
13         notice.find('ul > li.notice-answer').remove();
14
15         if (best) {
16             var p = notice.parent().find('div.question-description > form > fieldset > p');
17             if (p.length != 0) {
18                 p.append($('<span class="question-closed">This question is closed.</span>'));
19             }
20         }
21     },
22
23     init: function() {
24         QnA.NoticeInlineAnswerSetup();
25
26         $('form.form_question_show').live('submit', function() {
27             QnA.close(this);
28         });
29         $('form.form_answer_show').live('submit', function() {
30             QnA.close(this, true);
31         });
32     },
33
34     /**
35      * Open up a question's inline answer box.
36      *
37      * @param {jQuery} notice: jQuery object containing one notice
38      */
39     NoticeInlineAnswerTrigger: function(notice) {
40         // Find the notice we're replying to...
41         var id = $($('.notice_id', notice)[0]).text();
42         var parentNotice = notice;
43
44         // Find the threaded replies view we'll be adding to...
45         var list = notice.closest('.notices');
46         if (list.hasClass('threaded-replies')) {
47
48             // We're replying to a reply; use reply form on the end of this list.
49             // We'll add our form at the end of this; grab the root notice.
50             parentNotice = list.closest('.notice');
51
52         } else {
53
54             // We're replying to a parent notice; pull its threaded list
55             // and we'll add on the end of it. Will add if needed.
56             list = $('ul.threaded-replies', notice);
57         }
58
59         // See if the form's already open...
60         var answerForm = $('.qna_answer_form', list);
61
62         var hideReplyPlaceholders = function(notice) {
63             // Do we still have a dummy answer placeholder? If so get rid of
64             // reply place holders for this question. If the current user hasn't
65             // answered the question we want to direct her to providing an
66             // answer. She can still reply by hitting the reply button if she
67             // really wants to.
68             var dummyAnswer = $('ul.qna-dummy', notice);
69             if (dummyAnswer.length > 0) {
70                 notice.find('li.notice-reply-placeholder').hide();
71             }
72         }
73
74         var nextStep = function() {
75             var dummyAnswer = $('ul.qna-dummy', notice);
76             dummyAnswer.hide();
77
78              // Set focus...
79             var text = answerForm.find('textarea');
80
81             if (text.length == 0) {
82                 throw "No textarea";
83             }
84
85             text.focus();
86
87             $('body').click(function(e) {
88                 var dummyAnswer = $('ul.qna-dummy', notice);
89                 var style = dummyAnswer.attr('style');
90                 var ans = $(notice).find('li.hentry.notice.anwer', notice)
91                 if (ans > 0) {
92                     hideReplyPlaceholders(notice);
93                 }
94
95                 var openAnswers = $('li.notice-answer');
96                     if (openAnswers.length > 0) {
97                         var target = $(e.target);
98                         openAnswers.each(function() {
99
100                             // Did we click outside this one?
101                             var answerItem = $(this);
102                             var parentNotice = answerItem.closest('li.notice');
103
104                             if (answerItem.has(e.target).length == 0) {
105                                 var textarea = answerItem.find('.notice_data-text:first');
106                                 var cur = $.trim(textarea.val());
107                                 // Only close if there's been no edit.
108                                 if (cur == '' || cur == textarea.data('initialText')) {
109                                     answerItem.remove();
110                                     dummyAnswer.show();
111                                 }
112                             }
113                         });
114                     }
115                 });
116         };
117
118         // See if the form's already open...
119         if (answerForm.length > 0 ) {
120             nextStep();
121         } else {
122             var placeholder = list.find('li.qna-dummy-placeholder').hide();
123
124             // Create the answer form entry at the end
125             var answerItem = $('li.notice-answer', list);
126
127             if (answerItem.length == 0) {
128                  answerItem = $('<li class="notice-answer"></li>');
129                  var intermediateStep = function(formMaster) {
130                     // @todo cache the form if we can (worth it?)
131                     var formEl = document._importNode(formMaster, true);
132                     $(formEl).data('NoticeFormSetup', true);
133                     answerItem.append(formEl);
134                     list.prepend(answerItem); // *before* the placeholder
135                     var form = answerForm = $(formEl);
136                     QnA.AnswerFormSetup(form);
137                     nextStep();
138                 };
139
140                 if (QnA.AnswerFormMaster) {
141                     // @todo if we had a cached for here's where we'd use it'
142                     intermediateStep(QnA.AnswerFormMaster);
143                 } else {
144                     // Fetch a fresh copy of the answer form over AJAX.
145                     // Warning: this can have a delay, which looks bad.
146                     // @fixme this fallback may or may not work
147                     var url = $('#answer-action').attr('value');
148                      $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
149                          intermediateStep($('form', data)[0]);
150                      });
151                  }
152              }
153          }
154      },
155
156     /**
157      * Setup function -- DOES NOT apply immediately.
158      *
159      * Sets up event handlers for inline reply mini-form placeholders.
160      * Uses 'live' rather than 'bind', so applies to future as well as present items.
161      */
162     NoticeInlineAnswerSetup: function() {
163
164         $('li.qna-dummy-placeholder input.placeholder')
165             .live('focus', function() {
166                 var notice = $(this).closest('li.notice');
167                 QnA.NoticeInlineAnswerTrigger(notice);
168                 return false;
169             });
170
171     },
172
173     AnswerFormSetup: function(form) {
174
175         form.find('textarea').focus();
176
177         if (!form.data('NoticeFormSetup')) {
178             alert('gargargar');
179         }
180
181         if (!form.data('AnswerFormSetup')) {
182             //SN.U.NoticeLocationAttach(form);
183             QnA.FormAnswerXHR(form);
184             //SN.U.FormNoticeEnhancements(form);
185             //SN.U.NoticeDataAttach(form);
186             form.data('NoticeFormSetup', true);
187         }
188     },
189
190    /**
191      * Setup function -- DOES NOT trigger actions immediately.
192      *
193      * Sets up event handlers for special-cased async submission of the
194      * answer-posting form, including some pre-post validation.
195      *
196      * @fixme geodata
197      * @fixme refactor and unify with FormNoticeXHR in util.js
198      *
199      * @param {jQuery} form: jQuery object whose first element is a form
200      *
201      * @access public
202      */
203     FormAnswerXHR: function(form) {
204
205         //SN.C.I.NoticeDataGeo = {};
206         form.append('<input type="hidden" name="ajax" value="1"/>');
207
208         // Make sure we don't have a mixed HTTP/HTTPS submission...
209         form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
210
211         /**
212          * Show a response feedback bit under the new-notice dialog.
213          *
214          * @param {String} cls: CSS class name to use ('error' or 'success')
215          * @param {String} text
216          * @access private
217          */
218         var showFeedback = function(cls, text) {
219             form.append(
220                 $('<p class="form_response"></p>')
221                     .addClass(cls)
222                     .text(text)
223             );
224         };
225
226         /**
227          * Hide the previous response feedback, if any.
228          */
229         var removeFeedback = function() {
230             form.find('.form_response').remove();
231         };
232
233         form.ajaxForm({
234             dataType: 'xml',
235             timeout: '60000',
236
237             beforeSend: function(formData) {
238
239                 if (form.find('.notice_data-text:first').val() == '') {
240                     form.addClass(SN.C.S.Warning);
241                     return false;
242                 }
243                 form
244                     .addClass(SN.C.S.Processing)
245                     .find('.submit')
246                         .addClass(SN.C.S.Disabled)
247                         .attr(SN.C.S.Disabled, SN.C.S.Disabled);
248                 return true;
249             },
250             error: function (xhr, textStatus, errorThrown) {
251                 form
252                     .removeClass(SN.C.S.Processing)
253                     .find('.submit')
254                         .removeClass(SN.C.S.Disabled)
255                         .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
256                 removeFeedback();
257                 if (textStatus == 'timeout') {
258                     // @fixme i18n
259                     showFeedback('error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
260                 }
261                 else {
262                     var response = SN.U.GetResponseXML(xhr);
263                     if ($('.'+SN.C.S.Error, response).length > 0) {
264                         form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
265                     }
266                     else {
267                         if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
268                             form
269                                 .resetForm()
270                                 .find('.attach-status').remove();
271                             SN.U.FormNoticeEnhancements(form);
272                         }
273                         else {
274                             // @fixme i18n
275                             showFeedback('error', '(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
276                         }
277                     }
278                 }
279             },
280             success: function(data, textStatus) {
281
282                 removeFeedback();
283                 var errorResult = $('#'+SN.C.S.Error, data);
284                 if (errorResult.length > 0) {
285                     showFeedback('error', errorResult.text());
286                 }
287                 else {
288
289                     // New notice post was successful. If on our timeline, show it!
290                     var notice = document._importNode($('li', data)[0], true);
291                     var notices = $('#notices_primary .notices:first');
292                     var answerItem = form.closest('li.notice-answer');
293                     var questionItem = form.closest('li.question');
294
295                     var dummyAnswer = form.find('ul.qna-dummy', questionItem).remove();
296                     if (answerItem.length > 0) {
297
298                     // If this is an inline answer, remove the form...
299                     var list = form.closest('.threaded-replies');
300
301                     // if the inserted notice's parent question needs it give it a placeholder
302                     var ans = questionItem.find('ul > li.hentry.notice.answer');
303                     if (ans.length == 0) {
304                         SN.U.NoticeInlineReplyPlaceholder(questionItem);
305                     }
306
307                     var id = $(notice).attr('id');
308                     if ($("#"+id).length == 0) {
309                         $(notice).insertBefore(answerItem);
310                             answerItem.remove();
311                         } else {
312                             // NOP
313                             // Realtime came through before us...
314                         }
315
316                     } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
317
318                         // Not a reply. If on our timeline, show it at the
319                         if ($('#'+notice.id).length === 0) {
320                             var notice_irt_value = form.find('#inreplyto').val();
321                             var notice_irt = '#notices_primary #notice-'+notice_irt_value;
322                             if($('body')[0].id == 'conversation') {
323                                 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
324                                     $(notice_irt).append('<ul class="notices"></ul>');
325                                 }
326                                 $($(notice_irt+' .notices')[0]).append(notice);
327                             }
328                             else {
329                                 notices.prepend(notice);
330                             }
331                             $('#'+notice.id)
332                                 .css({display:'none'})
333                                 .fadeIn(2500);
334                         }
335
336                         // realtime injected the notice first
337
338                     } else {
339                         // Not on a timeline that this belongs on?
340                         // Just show a success message.
341                         // @fixme inline
342                         showFeedback('success', $('title', data).text());
343                     }
344                 }
345             },
346             complete: function(xhr, textStatus) {
347                 form
348                     .removeClass(SN.C.S.Processing)
349                     .find('.submit')
350                         .removeAttr(SN.C.S.Disabled)
351                         .removeClass(SN.C.S.Disabled);
352             }
353         });
354     }
355 };
356
357 $(document).ready(function() {
358     QnA.init();
359 });