]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/js/qna.js
cf211d691244dab8b1d3ef907ff54f120718dac7
[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         $(document).on('submit', 'form.form_question_show', function () {
27             QnA.close(this);
28         });
29         $(document).on('submit', 'form.form_answer_show', 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         $(document).on('focus',
165             'li.qna-dummy-placeholder input.placeholder',
166             function () {
167                 var notice = $(this).closest('li.notice');
168                 QnA.NoticeInlineAnswerTrigger(notice);
169                 return false;
170             });
171
172     },
173
174     AnswerFormSetup: function (form) {
175
176         form.find('textarea').focus();
177
178         if (!form.data('NoticeFormSetup')) {
179             alert('gargargar');
180         }
181
182         if (!form.data('AnswerFormSetup')) {
183             //SN.U.NoticeLocationAttach(form);
184             QnA.FormAnswerXHR(form);
185             //SN.U.FormNoticeEnhancements(form);
186             //SN.U.NoticeDataAttach(form);
187             form.data('NoticeFormSetup', true);
188         }
189     },
190
191    /**
192      * Setup function -- DOES NOT trigger actions immediately.
193      *
194      * Sets up event handlers for special-cased async submission of the
195      * answer-posting form, including some pre-post validation.
196      *
197      * @fixme geodata
198      * @fixme refactor and unify with FormNoticeXHR in util.js
199      *
200      * @param {jQuery} form: jQuery object whose first element is a form
201      *
202      * @access public
203      */
204     FormAnswerXHR: function (form) {
205
206         //SN.C.I.NoticeDataGeo = {};
207         form.append('<input type="hidden" name="ajax" value="1"/>');
208
209         // Make sure we don't have a mixed HTTP/HTTPS submission...
210         form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
211
212         /**
213          * Show a response feedback bit under the new-notice dialog.
214          *
215          * @param {String} cls: CSS class name to use ('error' or 'success')
216          * @param {String} text
217          * @access private
218          */
219         var showFeedback = function (cls, text) {
220             form.append(
221                 $('<p class="form_response"></p>')
222                     .addClass(cls)
223                     .text(text)
224             );
225         };
226
227         /**
228          * Hide the previous response feedback, if any.
229          */
230         var removeFeedback = function () {
231             form.find('.form_response').remove();
232         };
233
234         form.ajaxForm({
235             dataType: 'xml',
236             timeout: '60000',
237
238             beforeSend: function (formData) {
239
240                 if (form.find('.notice_data-text:first').val() == '') {
241                     form.addClass(SN.C.S.Warning);
242                     return false;
243                 }
244                 form
245                     .addClass(SN.C.S.Processing)
246                     .find('.submit')
247                         .addClass(SN.C.S.Disabled)
248                         .attr(SN.C.S.Disabled, SN.C.S.Disabled);
249                 return true;
250             },
251             error: function (xhr, textStatus, errorThrown) {
252                 form
253                     .removeClass(SN.C.S.Processing)
254                     .find('.submit')
255                         .removeClass(SN.C.S.Disabled)
256                         .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
257                 removeFeedback();
258                 if (textStatus == 'timeout') {
259                     // @fixme i18n
260                     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.');
261                 }
262                 else {
263                     var response = SN.U.GetResponseXML(xhr);
264                     if ($('.'+SN.C.S.Error, response).length > 0) {
265                         form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
266                     }
267                     else {
268                         if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
269                             form
270                                 .resetForm()
271                                 .find('.attach-status').remove();
272                             SN.U.FormNoticeEnhancements(form);
273                         }
274                         else {
275                             // @fixme i18n
276                             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.');
277                         }
278                     }
279                 }
280             },
281             success: function (data, textStatus) {
282
283                 removeFeedback();
284                 var errorResult = $('#'+SN.C.S.Error, data);
285                 if (errorResult.length > 0) {
286                     showFeedback('error', errorResult.text());
287                 }
288                 else {
289
290                     // New notice post was successful. If on our timeline, show it!
291                     var notice = document._importNode($('li', data)[0], true);
292                     var notices = $('#notices_primary .notices:first');
293                     var answerItem = form.closest('li.notice-answer');
294                     var questionItem = form.closest('li.question');
295
296                     var dummyAnswer = form.find('ul.qna-dummy', questionItem).remove();
297                     if (answerItem.length > 0) {
298
299                     // If this is an inline answer, remove the form...
300                     var list = form.closest('.threaded-replies');
301
302                     // if the inserted notice's parent question needs it give it a placeholder
303                     var ans = questionItem.find('ul > li.hentry.notice.answer');
304                     if (ans.length == 0) {
305                         SN.U.NoticeInlineReplyPlaceholder(questionItem);
306                     }
307
308                     var id = $(notice).attr('id');
309                     if ($("#"+id).length == 0) {
310                         $(notice).insertBefore(answerItem);
311                             answerItem.remove();
312                         } else {
313                             // NOP
314                             // Realtime came through before us...
315                         }
316
317                     } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
318
319                         // Not a reply. If on our timeline, show it at the
320                         if ($('#'+notice.id).length === 0) {
321                             var notice_irt_value = form.find('#inreplyto').val();
322                             var notice_irt = '#notices_primary #notice-'+notice_irt_value;
323                             if($('body')[0].id == 'conversation') {
324                                 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
325                                     $(notice_irt).append('<ul class="notices"></ul>');
326                                 }
327                                 $($(notice_irt+' .notices')[0]).append(notice);
328                             }
329                             else {
330                                 notices.prepend(notice);
331                             }
332                             $('#'+notice.id)
333                                 .css({display:'none'})
334                                 .fadeIn(2500);
335                         }
336
337                         // realtime injected the notice first
338
339                     } else {
340                         // Not on a timeline that this belongs on?
341                         // Just show a success message.
342                         // @fixme inline
343                         showFeedback('success', $('title', data).text());
344                     }
345                 }
346             },
347             complete: function (xhr, textStatus) {
348                 form
349                     .removeClass(SN.C.S.Processing)
350                     .find('.submit')
351                         .removeAttr(SN.C.S.Disabled)
352                         .removeClass(SN.C.S.Disabled);
353             }
354         });
355     }
356 };
357
358 $(document).ready(function () {
359     QnA.init();
360 });