]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
Refactored XHR forms:
[quix0rs-gnu-social.git] / js / util.js
1 /*
2  * StatusNet - a distributed open-source microblogging tool
3  * Copyright (C) 2008, StatusNet, Inc.
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         var counterBlackout = false;
21         
22         // count character on keyup
23         function counter(event){
24          if (maxLength <= 0) {
25               return;
26          }
27                 var currentLength = $("#notice_data-text").val().length;
28                 var remaining = maxLength - currentLength;
29                 var counter = $("#notice_text-count");
30                 
31                 if (remaining.toString() != counter.text()) {
32                     if (!counterBlackout || remaining == 0) {
33                         if (counter.text() != String(remaining)) {
34                             counter.text(remaining);
35                         }
36
37                         if (remaining < 0) {
38                             $("#form_notice").addClass("warning");
39                         } else {
40                             $("#form_notice").removeClass("warning");
41                         }
42                         // Skip updates for the next 500ms.
43                         // On slower hardware, updating on every keypress is unpleasant.
44                         if (!counterBlackout) {
45                             counterBlackout = true;
46                             window.setTimeout(clearCounterBlackout, 500);
47                         }
48                     }
49                 }
50         }
51         
52         function clearCounterBlackout() {
53                 // Allow keyup events to poke the counter again
54                 counterBlackout = false;
55                 // Check if the string changed since we last looked
56                 counter(null);
57         }
58
59         function submitonreturn(event) {
60                 if (event.keyCode == 13 || event.keyCode == 10) {
61                         // iPhone sends \n not \r for 'return'
62                         $("#form_notice").submit();
63                         event.preventDefault();
64                         event.stopPropagation();
65                         $("#notice_data-text").blur();
66                         $("body").focus();
67                         return false;
68                 }
69                 return true;
70         }
71
72      // define maxLength if it wasn't defined already
73
74     if (typeof(maxLength) == "undefined") {
75          maxLength = 140;
76     }
77
78         if ($("#notice_data-text").length) {
79          if (maxLength > 0) {
80               $("#notice_data-text").bind("keyup", counter);
81               // run once in case there's something in there
82               counter();
83          }
84
85                 $("#notice_data-text").bind("keydown", submitonreturn);
86
87         if($('body')[0].id != 'conversation') {
88             $("#notice_data-text").focus();
89         }
90         }
91
92         function addAjaxHidden() {
93                 var ajax = document.createElement('input');
94                 ajax.setAttribute('type', 'hidden');
95                 ajax.setAttribute('name', 'ajax');
96                 ajax.setAttribute('value', 1);
97                 this.appendChild(ajax);
98         }
99
100     $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
101     $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
102     $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
103     $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
104     $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
105     $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
106     $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });
107
108         var PostNotice = { dataType: 'xml',
109                                            beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
110                                                                                                                                                                 $("#form_notice").addClass("warning");
111                                                                                                                                                                 return false;
112                                                                                                                                                    }
113                                                                                                                                                    $("#form_notice").addClass("processing");
114                                                                                                                                                    $("#notice_action-submit").attr("disabled", "disabled");
115                                                                                                                                                    $("#notice_action-submit").addClass("disabled");
116                                                                                                                                                    return true;
117                                                                                                                                                  },
118                                            timeout: '60000',
119                                            error: function (xhr, textStatus, errorThrown) {     $("#form_notice").removeClass("processing");
120                                                                                                                                                 $("#notice_action-submit").removeAttr("disabled");
121                                                                                                                                                 $("#notice_action-submit").removeClass("disabled");
122                                                                                                                                                 if (textStatus == "timeout") {
123                                                                                                                                                         alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
124                                                                                                                                                 }
125                                                                                                                                                 else {
126                                                                                                                                                         if ($(".error", xhr.responseXML).length > 0) {
127                                                                                                                                                                 $('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
128                                                                                                                                                         }
129                                                                                                                                                         else {
130                                                                                                                                                                 var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
131                                                                                                                                                                 if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
132                                                                                                                                                                         alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
133                                                                                                                                                                 }
134                                                                                                                                                                 else {
135                                                                                                                                                                         $("#notice_data-text").val("");
136                                                                                      if (maxLength > 0) {
137                                                                                           counter();
138                                                                                      }
139                                                                                                                                                                 }
140                                                                                                                                                         }
141                                                                                                                                                 }
142                                                                                                                                           },
143                                            success: function(xml) {     if ($("#error", xml).length > 0) {
144                                                                                                         var result = document._importNode($("p", xml).get(0), true);
145                                                                                                         result = result.textContent || result.innerHTML;
146                                                                                                         alert(result);
147                                                                                                 }
148                                                                                                 else {
149                                                                                                     if($('body')[0].id == 'bookmarklet') {
150                                                                                                         self.close();
151                                                                                                     }
152                                                                                                     if ($("#command_result", xml).length > 0) {
153                                                                                                             var result = document._importNode($("p", xml).get(0), true);
154                                                                                                             result = result.textContent || result.innerHTML;
155                                                                                                             alert(result);
156                                                     }
157                                                     else {
158                                                          li = $("li", xml).get(0);
159                                                          if ($("#"+li.id).length == 0) {
160                                                             var notice_irt_value = $('#notice_in-reply-to').val();
161                                                             var notice_irt = '#notices_primary #notice-'+notice_irt_value;
162                                                             if($('body')[0].id == 'conversation') {
163                                                                 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
164                                                                     $(notice_irt).append('<ul class="notices"></ul>');
165                                                                 }
166                                                                 $($(notice_irt+' .notices')[0]).append(document._importNode(li, true));
167                                                             }
168                                                             else {
169                                                                 $("#notices_primary .notices").prepend(document._importNode(li, true));
170                                                             }
171                                                             $('#'+li.id).css({display:'none'});
172                                                             $('#'+li.id).fadeIn(2500);
173                                                             NoticeReply();
174                                                             NoticeAttachments();
175                                                          }
176                                                                                                         }
177                                                                                                         $("#notice_data-text").val("");
178                                                                                                 $("#notice_data-attach").val("");
179                                                                                                 $("#notice_in-reply-to").val("");
180                                                     $('#notice_data-attach_selected').remove();
181                                                      if (maxLength > 0) {
182                                                           counter();
183                                                      }
184                                                                                                 }
185                                                                                                 $("#form_notice").removeClass("processing");
186                                                                                                 $("#notice_action-submit").removeAttr("disabled");
187                                                                                                 $("#notice_action-submit").removeClass("disabled");
188                                                                                          }
189                                            };
190         $("#form_notice").ajaxForm(PostNotice);
191         $("#form_notice").each(addAjaxHidden);
192     NoticeReply();
193     NoticeAttachments();
194     NoticeDataAttach();
195 });
196
197 function NoticeReply() {
198     if ($('#notice_data-text').length > 0 && $('#content .notice_reply').length > 0) {
199         $('#content .notice').each(function() {
200             var notice = $(this)[0];
201             $($('.notice_reply', notice)[0]).click(function() {
202                 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
203                 NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
204                 return false;
205             });
206         });
207     }
208 }
209
210 function NoticeReplySet(nick,id) {
211         rgx_username = /^[0-9a-zA-Z\-_.]*$/;
212         if (nick.match(rgx_username)) {
213                 var text = $("#notice_data-text");
214                 if (text.length) {
215                         replyto = "@" + nick + " ";
216                         text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
217                         $("#form_notice input#notice_in-reply-to").val(id);
218                         if (text.get(0).setSelectionRange) {
219                                 var len = text.val().length;
220                                 text.get(0).setSelectionRange(len,len);
221                                 text.get(0).focus();
222                         }
223                         return false;
224                 }
225         }
226         return true;
227 }
228
229 function NoticeAttachments() {
230     $.fn.jOverlay.options = {
231         method : 'GET',
232         data : '',
233         url : '',
234         color : '#000',
235         opacity : '0.6',
236         zIndex : 99,
237         center : false,
238         imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
239         bgClickToClose : true,
240         success : function() {
241             $('#jOverlayContent').append('<button>&#215;</button>');
242             $('#jOverlayContent button').click($.closeOverlay);
243         },
244         timeout : 0,
245         autoHide : true,
246         css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
247     };
248
249     $('#content .notice a.attachment').click(function() {
250         $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
251         return false;
252     });
253
254     var t;
255     $("body:not(#shownotice) #content .notice a.thumbnail").hover(
256         function() {
257             var anchor = $(this);
258             $("a.thumbnail").children('img').hide();
259             anchor.closest(".entry-title").addClass('ov');
260
261             if (anchor.children('img').length == 0) {
262                 t = setTimeout(function() {
263                     $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
264                         anchor.append(data);
265                     });
266                 }, 500);
267             }
268             else {
269                 anchor.children('img').show();
270             }
271         },
272         function() {
273             clearTimeout(t);
274             $("a.thumbnail").children('img').hide();
275             $(this).closest(".entry-title").removeClass('ov');
276         }
277     );
278 }
279
280 function NoticeDataAttach() {
281     NDA = $('#notice_data-attach');
282     NDA.change(function() {
283         S = '<div id="notice_data-attach_selected" class="success"><code>'+$(this).val()+'</code> <button>&#215;</button></div>';
284         NDAS = $('#notice_data-attach_selected');
285         (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#form_notice').append(S);
286         $('#notice_data-attach_selected button').click(function(){
287             $('#notice_data-attach_selected').remove();
288             NDA.val('');
289         });
290     });
291 }
292
293 var SN = { // StatusNet
294     C: { // Config
295         S: { // Selector
296             Disabled: 'disabled',
297             Warning: 'warning',
298             Error: 'error',
299             Processing: 'processing'
300         }
301     },
302
303     U: { // Utils
304         FormXHR: function(f) {
305             f.bind('submit', function(e) {
306                 form_id = $(this)[0].id;
307                 $.ajax({
308                     type: 'POST',
309                     url: $(this)[0].action,
310                     data: $(this).serialize() + '&ajax=1',
311                     beforeSend: function(xhr) {
312                         $('#'+form_id).addClass(SN.C.S.Processing);
313                         $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
314                         $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
315                     },
316                     error: function (xhr, textStatus, errorThrown) {
317                         alert(errorThrown || textStatus);
318                     },
319                     success: function(data, textStatus) {
320                         if ($('form', data)[0].length > 0) {
321                             form_new = $('form', data)[0];
322                             $('#'+form_id).replaceWith(document._importNode(form_new, true));
323                             $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
324                         }
325                         else {
326                             $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
327                         }
328                     }
329                 });
330                 return false;
331             });
332         }
333     }
334 }