]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/js/qna.js
OMG I think ajax works right now
[quix0rs-gnu-social.git] / plugins / QnA / js / qna.js
1
2 var QnA = {
3
4     // @fixme: Should use ID
5     close: function(closeButt) {
6         var notice = $(closeButt).closest('li.hentry.notice.question');
7
8         console.log("close");
9
10         notice.find('input#qna-best-answer,#qna-question-close').hide();
11         notice.find('textarea').hide();
12
13         var list = notice.find('ul');
14
15         console.log("found this many uls: " + list.length);
16
17         notice.find('ul > li.notice-answer-placeholder').remove();
18         notice.find('ul > li.notice-answer').remove();
19     },
20
21     init: function() {
22
23         QnA.NoticeInlineAnswerSetup();
24
25         $('form.form_question_show').live('submit', function() {
26             QnA.close(this);
27         });
28         $('form.form_answer_show').live('click', function() {
29             QnA.close(this);
30         });
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
43         console.log("NoticeInlineAnswerTrigger - answering notice " + id);
44
45         var parentNotice = notice;
46
47         // Find the threaded replies view we'll be adding to...
48         var list = notice.closest('.notices');
49
50         if (list.hasClass('threaded-replies')) {
51             console.log("NoticeInlineAnswerTrigger - there's already a threaded-replies ul above me");
52             // We're replying to a reply; use reply form on the end of this list.
53             // We'll add our form at the end of this; grab the root notice.
54             parentNotice = list.closest('.notice');
55             console.log("NoticeInlineAnswerTrigger - trying to find the closest .notice above me");
56             if (parentNotice.length > 0) {
57                 console.log("NoticeInlineAnswerTrigger - found that closest .notice - length = " + parentNotice.length);
58             }
59         } else {
60             console.log("NoticeInlineAnswerTrigger - this notice does not have a threaded-reples ul");
61             // We're replying to a parent notice; pull its threaded list
62             // and we'll add on the end of it. Will add if needed.
63             list = $('ul.threaded-replies', notice);
64         }
65         
66         // See if the form's already open...
67         var answerForm = $('.qna_answer_form', list);
68
69         var hideReplyPlaceholders = function(notice) {
70             // Do we still have a dummy answer placeholder? If so get rid of
71             // reply place holders for this question. If the current user hasn't
72             // answered the question we want to direct her to providing an
73             // answer. She can still reply by hitting the reply button if she
74             // really wants to.
75             var dummyAnswer = $('ul.qna-dummy', notice);
76             if (dummyAnswer.length > 0) {
77                 console.log("hiding any reply placeholders");
78                 notice.find('li.notice-reply-placeholder').hide();
79             }
80         }
81
82
83         var nextStep = function() {
84             console.log("NoticeInlineAnswerTrigger (nextStep) - begin");
85
86             var dummyAnswer = $('ul.qna-dummy', notice);
87             dummyAnswer.hide();
88
89              // Set focus...
90             var text = answerForm.find('textarea');
91
92             if (text.length == 0) {
93                 throw "No textarea";
94             }
95
96             text.focus();
97
98             console.log("NoticeInlineAnswerTrigger (nextStep) - setting up body click handler to hide open form when clicking away");
99             $('body').click(function(e) {
100                 console.log("body click handler - got click");
101
102                 hideReplyPlaceholders(notice);
103
104                 var openAnswers = $('li.notice-answer');
105                     if (openAnswers.length > 0) {
106                         console.log("body click handler - Found one or more open answer forms to close");
107                         var target = $(e.target);
108
109                         openAnswers.each(function() {
110                             console.log("body click handler - found an open answer form");
111                             // Did we click outside this one?
112                             var answerItem = $(this);
113                             var parentNotice = answerItem.closest('li.notice');
114                             
115                             if (answerItem.has(e.target).length == 0) {
116                                 var textarea = answerItem.find('.notice_data-text:first');
117                                 var cur = $.trim(textarea.val());
118                                 // Only close if there's been no edit.
119                                 if (cur == '' || cur == textarea.data('initialText')) {
120                                     console.log("body click handler - no text in answer form, closing it");
121                                     answerItem.remove();
122                                     console.log("body click handler - showing dummy placeholder");
123                                     dummyAnswer.show();
124                                     
125                                 } else {
126                                     console.log("body click handler - there is text in the answer form, wont close it");
127                                 }
128                             }
129                         });
130                     }
131
132                 console.log('body click handler - exit');
133                 });
134         };
135
136         // See if the form's already open...
137
138         if (answerForm.length > 0 ) {
139             console.log("NoticeInlineAnswerTrigger - found an open .notice-answer-form - doing nextStep()");
140             nextStep();
141         } else {
142
143             console.log("NoticeInlineAnswerTrigger - hiding the dummy placeholder");
144             var placeholder = list.find('li.qna-dummy-placeholder').hide();
145
146             // Create the answer form entry at the end
147
148             var answerItem = $('li.notice-answer', list);
149
150             if (answerItem.length > 0) {
151                 console.log("NoticeInlineAnswerTrigger - Found " + answerItem.length + " answer items (notice-answer li)");
152             }
153
154             if (answerItem.length == 0) {
155                  console.log("NoticeInlineAnswerTrigger - no answer item (notice-answer li)");
156                  answerItem = $('<li class="notice-answer"></li>');
157
158                  var intermediateStep = function(formMaster) {
159
160                      // cache it
161                      //if (!QnA.AnswerFormMaster) {
162                      //    QnA.AnswerFormMaster = formMaster;
163                      //}
164
165
166                      console.log("NoticeInlineAnswerTrigger - (intermediate) step begin");
167                      var formEl = document._importNode(formMaster, true);
168
169                      console.log("NoticeInlineAnswerTrigger - (intermediate step) appending answer form to answer item");
170                      $(formEl).data('NoticeFormSetup', true);
171
172                      answerItem.append(formEl);
173
174                      console.log("NoticeInlineAnswerTrigger - (intermediate step) appending answer to replies list, after placeholder");
175                      list.prepend(answerItem); // *before* the placeholder
176                      var form = answerForm = $(formEl);
177                      console.log("NoticeInlineAnswerTrigger - (intermediate step) calling QnA.AnswerFormSetup on the form")
178                      QnA.AnswerFormSetup(form);
179                      console.log("NoticeInlineAnswerTrigger - (intermediate step) calling nextstep()");
180                      nextStep();
181                  };
182
183                  if (QnA.AnswerFormMaster) {
184                      console.log("NoticeInlineAnswerTrigger - found a cached copy of the answer form");
185                      // We've already saved a master copy of the form.
186                      // Clone it in!
187                      console.log("NoticeInlineAnswerTrigger - calling intermediateStep with cached form");
188                      intermediateStep(QnA.AnswerFormMaster);
189                  } else {
190                      // Fetch a fresh copy of the answer form over AJAX.
191                      // Warning: this can have a delay, which looks bad.
192                      // @fixme this fallback may or may not work
193                      var url = $('#answer-action').attr('value');
194
195                      console.log("NoticeInlineAnswerTrigger - fetching new form via HXR");
196
197                      $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
198                          console.log("NoticeInlineAnswerTrigger - got a new form via HXR, calling intermediateStep");
199                          intermediateStep($('form', data)[0]);
200                      });
201                  }
202              }
203          }
204          console.log('NoticeInlineAnswerTrigger - exit');
205
206      },
207
208     /**
209      * Setup function -- DOES NOT apply immediately.
210      *
211      * Sets up event handlers for inline reply mini-form placeholders.
212      * Uses 'live' rather than 'bind', so applies to future as well as present items.
213      */
214     NoticeInlineAnswerSetup: function() {
215         console.log("NoticeInlineAnswerSetup - begin");
216         $('li.qna-dummy-placeholder input.placeholder')
217             .live('focus', function() {
218                 var notice = $(this).closest('li.notice');
219                 QnA.NoticeInlineAnswerTrigger(notice);
220                 return false;
221             });
222         console.log("NoticeInlineAnswerSetup - exit");
223     },
224
225     AnswerFormSetup: function(form) {
226         console.log("AnswerFormSetup");
227         form.find('textarea').focus();
228
229         if (!form.data('NoticeFormSetup')) {
230             alert('gargargar');
231         }
232
233         if (!form.data('AnswerFormSetup')) {
234             //SN.U.NoticeLocationAttach(form);
235             QnA.FormAnswerXHR(form);
236             //SN.U.FormNoticeEnhancements(form);
237             //SN.U.NoticeDataAttach(form);
238             form.data('NoticeFormSetup', true);
239         }
240     },
241
242    /**
243      * Setup function -- DOES NOT trigger actions immediately.
244      *
245      * Sets up event handlers for special-cased async submission of the
246      * answer-posting form, including some pre-post validation.
247      *
248      * @fixme geodata
249      * @fixme refactor and unify with FormNoticeXHR in util.js
250      *
251      * @param {jQuery} form: jQuery object whose first element is a form
252      *
253      * @access public
254      */
255     FormAnswerXHR: function(form) {
256         console.log("FormAanwerXHR - begin");
257         //SN.C.I.NoticeDataGeo = {};
258         form.append('<input type="hidden" name="ajax" value="1"/>');
259         console.log("FormAnswerXHR - appended ajax flag to form");
260
261         // Make sure we don't have a mixed HTTP/HTTPS submission...
262         form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
263         console.log("FormAnswerXHR rewrote action so we don't have a mixed HTTP/HTTPS submission");
264
265         /**
266          * Show a response feedback bit under the new-notice dialog.
267          *
268          * @param {String} cls: CSS class name to use ('error' or 'success')
269          * @param {String} text
270          * @access private
271          */
272         var showFeedback = function(cls, text) {
273             form.append(
274                 $('<p class="form_response"></p>')
275                     .addClass(cls)
276                     .text(text)
277             );
278         };
279
280         /**
281          * Hide the previous response feedback, if any.
282          */
283         var removeFeedback = function() {
284             form.find('.form_response').remove();
285         };
286
287         console.log("FormAnswerXHR - doing ajaxForm call");
288
289         form.ajaxForm({
290             dataType: 'xml',
291             timeout: '60000',
292
293             beforeSend: function(formData) {
294                 console.log("FormAnswerXHR - beforeSend");
295                 if (form.find('.notice_data-text:first').val() == '') {
296                     form.addClass(SN.C.S.Warning);
297                     return false;
298                 }
299                 form
300                     .addClass(SN.C.S.Processing)
301                     .find('.submit')
302                         .addClass(SN.C.S.Disabled)
303                         .attr(SN.C.S.Disabled, SN.C.S.Disabled);
304                 return true;
305             },
306             error: function (xhr, textStatus, errorThrown) {
307                 form
308                     .removeClass(SN.C.S.Processing)
309                     .find('.submit')
310                         .removeClass(SN.C.S.Disabled)
311                         .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
312                 removeFeedback();
313                 if (textStatus == 'timeout') {
314                     // @fixme i18n
315                     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.');
316                 }
317                 else {
318                     var response = SN.U.GetResponseXML(xhr);
319                     if ($('.'+SN.C.S.Error, response).length > 0) {
320                         form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
321                     }
322                     else {
323                         if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
324                             form
325                                 .resetForm()
326                                 .find('.attach-status').remove();
327                             SN.U.FormNoticeEnhancements(form);
328                         }
329                         else {
330                             // @fixme i18n
331                             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.');
332                         }
333                     }
334                 }
335             },
336             success: function(data, textStatus) {
337                 console.log("FormAnswerHXR - success");
338                 removeFeedback();
339                 var errorResult = $('#'+SN.C.S.Error, data);
340                 if (errorResult.length > 0) {
341                     showFeedback('error', errorResult.text());
342                 }
343                 else {
344
345                     // New notice post was successful. If on our timeline, show it!
346                     var notice = document._importNode($('li', data)[0], true);
347                     console.log("FormAnswerXHR - loaded the notice, now trying to insert it somewhere");
348
349                     var notices = $('#notices_primary .notices:first');
350
351                     console.log("FormAnswerXHR - looking for the closest notice with a notice-answer li");
352
353                     var answerItem = form.closest('li.notice-answer');
354                     var questionItem = form.closest('li.question');
355                     var dummyAnswer = form.find('ul.qna-dummy').remove();
356
357                     if (answerItem.length > 0) {
358                         console.log("FormAnswerXHR - I found the answer li to append to");
359                         // If this is an inline reply, remove the form...
360                         console.log("FormAnswerXHR - looking for the closest .threaded-replies ul")
361                         var list = form.closest('.threaded-replies');
362                         console.log("FormAnswerXHR - search list for the answer placeholder")
363                        
364
365                         var id = $(notice).attr('id');
366                         console.log("FormAnswerXHR - the new notice id is: " + id);
367
368                         if ($("#"+id).length == 0) {
369                             console.log("FormAnswerXHR - the notice is not there already so realtime hasn't inserted it before us");
370                             console.log("FormAnswerXHR - inserting new notice before placeholder");
371                             $(notice).insertBefore(answerItem);
372                             answerItem.remove();
373
374                             SN.U.NoticeInlineReplyPlaceholder(questionItem);
375                            
376                         } else {
377                             // Realtime came through before us...
378                         }
379                         
380                     } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
381                         console.log('FormAnswerXHR - there is at least one notice on the timeline and the new notice should be added to the list');
382                         // Not a reply. If on our timeline, show it at the
383                         if ($('#'+notice.id).length === 0) {
384                             console.log("FormAnswerXHR - The notice is not yet on the timeline.")
385                             var notice_irt_value = form.find('#inreplyto').val();
386                             console.log("FormAnswerXHR - getting value from #inreplyto inside the form: " + notice_irt_value);
387                             var notice_irt = '#notices_primary #notice-'+notice_irt_value;
388                             console.log("notice_irt selector = " + notice_irt_value);
389                             if($('body')[0].id == 'conversation') {
390                                 console.log("FormAnswerXHR - we're on a conversation page");
391                                 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
392                                     $(notice_irt).append('<ul class="notices"></ul>');
393                                 }
394                                 console.log("FormAnswerXHR - appending notice after notice_irt selector");
395                                 $($(notice_irt+' .notices')[0]).append(notice);
396                             }
397                             else {
398                                 console.log("FormAnswerXHR prepending notice to top of the notice list");
399                                 notices.prepend(notice);
400                             }
401                             $('#'+notice.id)
402                                 .css({display:'none'})
403                                 .fadeIn(2500);
404                         }
405
406                         // realtime injected the notice first
407
408                     } else {
409                         // Not on a timeline that this belongs on?
410                         // Just show a success message.
411                         // @fixme inline
412                         showFeedback('success', $('title', data).text());
413                     }
414
415                     //form.resetForm();
416                     //SN.U.FormNoticeEnhancements(form);
417                 }
418             },
419             complete: function(xhr, textStatus) {
420                 form
421                     .removeClass(SN.C.S.Processing)
422                     .find('.submit')
423                         .removeAttr(SN.C.S.Disabled)
424                         .removeClass(SN.C.S.Disabled);
425             }
426         });
427     }
428
429 };
430
431 $(document).ready(function() {
432     QnA.init();
433 });