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