]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
Merge branch 'master' into 0.9.x
[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  * @category  UI interaction
19  * @package   StatusNet
20  * @author    Sarven Capadisli <csarven@status.net>
21  * @author    Evan Prodromou <evan@status.net>
22  * @copyright 2009 StatusNet, Inc.
23  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
24  * @link      http://status.net/
25  */
26
27 var SN = { // StatusNet
28     C: { // Config
29         I: { // Init
30             CounterBlackout: false,
31             MaxLength: 140,
32             PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
33             HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
34         },
35
36         S: { // Selector
37             Disabled: 'disabled',
38             Warning: 'warning',
39             Error: 'error',
40             Success: 'success',
41             Processing: 'processing',
42             CommandResult: 'command_result',
43             FormNotice: 'form_notice',
44             NoticeDataText: 'notice_data-text',
45             NoticeTextCount: 'notice_text-count',
46             NoticeInReplyTo: 'notice_in-reply-to',
47             NoticeDataAttach: 'notice_data-attach',
48             NoticeDataAttachSelected: 'notice_data-attach_selected',
49             NoticeActionSubmit: 'notice_action-submit',
50             NoticeLat: 'notice_data-lat',
51             NoticeLon: 'notice_data-lon',
52             NoticeLocationId: 'notice_data-location_id',
53             NoticeLocationNs: 'notice_data-location_ns'
54         }
55     },
56
57     U: { // Utils
58         FormNoticeEnhancements: function(form) {
59             form_id = form.attr('id');
60
61             if (jQuery.data(form[0], 'ElementData') === undefined) {
62                 MaxLength = $('#'+form_id+' #'+SN.C.S.NoticeTextCount).text();
63                 if (typeof(MaxLength) == 'undefined') {
64                      MaxLength = SN.C.I.MaxLength;
65                 }
66                 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
67
68                 SN.U.Counter(form);
69
70                 NDT = $('#'+form_id+' #'+SN.C.S.NoticeDataText);
71
72                 NDT.bind('keyup', function(e) {
73                     SN.U.Counter(form);
74                 });
75
76                 NDT.bind('keydown', function(e) {
77                     SN.U.SubmitOnReturn(e, form);
78                 });
79             }
80             else {
81                 $('#'+form_id+' #'+SN.C.S.NoticeTextCount).text(jQuery.data(form[0], 'ElementData').MaxLength);
82             }
83
84             if ($('body')[0].id != 'conversation') {
85                 $('#'+form_id+' textarea').focus();
86             }
87         },
88
89         SubmitOnReturn: function(event, el) {
90             if (event.keyCode == 13 || event.keyCode == 10) {
91                 el.submit();
92                 event.preventDefault();
93                 event.stopPropagation();
94                 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
95                 $('body').focus();
96                 return false;
97             }
98             return true;
99         },
100
101         Counter: function(form) {
102             SN.C.I.FormNoticeCurrent = form;
103             form_id = form.attr('id');
104
105             var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
106
107             if (MaxLength <= 0) {
108                 return;
109             }
110
111             var remaining = MaxLength - $('#'+form_id+' #'+SN.C.S.NoticeDataText).val().length;
112             var counter = $('#'+form_id+' #'+SN.C.S.NoticeTextCount);
113
114             if (remaining.toString() != counter.text()) {
115                 if (!SN.C.I.CounterBlackout || remaining === 0) {
116                     if (counter.text() != String(remaining)) {
117                         counter.text(remaining);
118                     }
119                     if (remaining < 0) {
120                         form.addClass(SN.C.S.Warning);
121                     } else {
122                         form.removeClass(SN.C.S.Warning);
123                     }
124                     // Skip updates for the next 500ms.
125                     // On slower hardware, updating on every keypress is unpleasant.
126                     if (!SN.C.I.CounterBlackout) {
127                         SN.C.I.CounterBlackout = true;
128                         SN.C.I.FormNoticeCurrent = form;
129                         window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
130                     }
131                 }
132             }
133         },
134
135         ClearCounterBlackout: function(form) {
136             // Allow keyup events to poke the counter again
137             SN.C.I.CounterBlackout = false;
138             // Check if the string changed since we last looked
139             SN.U.Counter(form);
140         },
141
142         FormXHR: function(f) {
143             if (jQuery.data(f[0], "ElementData") === undefined) {
144                 jQuery.data(f[0], "ElementData", {Bind:'submit'});
145                 f.bind('submit', function(e) {
146                     form_id = $(this)[0].id;
147                     $.ajax({
148                         type: 'POST',
149                         dataType: 'xml',
150                         url: $(this)[0].action,
151                         data: $(this).serialize() + '&ajax=1',
152                         beforeSend: function(xhr) {
153                             $('#'+form_id).addClass(SN.C.S.Processing);
154                             $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
155                             $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
156                         },
157                         error: function (xhr, textStatus, errorThrown) {
158                             alert(errorThrown || textStatus);
159                         },
160                         success: function(data, textStatus) {
161                             if (typeof($('form', data)[0]) != 'undefined') {
162                                 form_new = document._importNode($('form', data)[0], true);
163                                 $('#'+form_id).replaceWith(form_new);
164                                 $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
165                             }
166                             else {
167                                 $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
168                             }
169                         }
170                     });
171                     return false;
172                 });
173             }
174         },
175
176         FormNoticeXHR: function(form) {
177             form_id = form.attr('id');
178             form.append('<input type="hidden" name="ajax" value="1"/>');
179             form.ajaxForm({
180                 dataType: 'xml',
181                 timeout: '60000',
182                 beforeSend: function(xhr) {
183                     if ($('#'+form_id+' #'+SN.C.S.NoticeDataText)[0].value.length === 0) {
184                         form.addClass(SN.C.S.Warning);
185                         return false;
186                     }
187                     form.addClass(SN.C.S.Processing);
188                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
189                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
190                     return true;
191                 },
192                 error: function (xhr, textStatus, errorThrown) {
193                     form.removeClass(SN.C.S.Processing);
194                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
195                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
196                     $('#'+form_id+' .form_response').remove();
197                     if (textStatus == 'timeout') {
198                         form.append('<p class="form_response error">Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.</p>');
199                     }
200                     else {
201                         if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
202                             form.append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
203                         }
204                         else {
205                             if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
206                                 $('#'+form_id).resetForm();
207                                 $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
208                                 SN.U.FormNoticeEnhancements($('#'+form_id));
209                             }
210                             else {
211                                 form.append('<p class="form_response error">(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.</p>');
212                             }
213                         }
214                     }
215                 },
216                 success: function(data, textStatus) {
217                     $('#'+form_id+' .form_response').remove();
218                     var result;
219                     if ($('#'+SN.C.S.Error, data).length > 0) {
220                         result = document._importNode($('p', data)[0], true);
221                         result = result.textContent || result.innerHTML;
222                         form.append('<p class="form_response error">'+result+'</p>');
223                     }
224                     else {
225                         if($('body')[0].id == 'bookmarklet') {
226                             self.close();
227                         }
228
229                         if ($('#'+SN.C.S.CommandResult, data).length > 0) {
230                             result = document._importNode($('p', data)[0], true);
231                             result = result.textContent || result.innerHTML;
232                             form.append('<p class="form_response success">'+result+'</p>');
233                         }
234                         else {
235                             var notices = $('#notices_primary .notices');
236                             if (notices.length > 0) {
237                                 var notice = document._importNode($('li', data)[0], true);
238                                 if ($('#'+notice.id).length === 0) {
239                                     var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
240                                     var notice_irt = '#notices_primary #notice-'+notice_irt_value;
241                                     if($('body')[0].id == 'conversation') {
242                                         if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
243                                             $(notice_irt).append('<ul class="notices"></ul>');
244                                         }
245                                         $($(notice_irt+' .notices')[0]).append(notice);
246                                     }
247                                     else {
248                                         notices.prepend(notice);
249                                     }
250                                     $('#'+notice.id).css({display:'none'});
251                                     $('#'+notice.id).fadeIn(2500);
252                                     SN.U.NoticeWithAttachment($('#'+notice.id));
253                                     SN.U.NoticeReplyTo($('#'+notice.id));
254                                     SN.U.FormXHR($('#'+notice.id+' .form_favor'));
255                                 }
256                             }
257                             else {
258                                 result = document._importNode($('title', data)[0], true);
259                                 result_title = result.textContent || result.innerHTML;
260                                 form.append('<p class="form_response success">'+result_title+'</p>');
261                             }
262                         }
263                         $('#'+form_id).resetForm();
264                         $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
265                         SN.U.FormNoticeEnhancements($('#'+form_id));
266                     }
267                 },
268                 complete: function(xhr, textStatus) {
269                     form.removeClass(SN.C.S.Processing);
270                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
271                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
272                 }
273             });
274         },
275
276         NoticeReply: function() {
277             if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
278                 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
279             }
280         },
281
282         NoticeReplyTo: function(notice_item) {
283             var notice = notice_item[0];
284             var notice_reply = $('.notice_reply', notice)[0];
285
286             if (jQuery.data(notice_reply, "ElementData") === undefined) {
287                 jQuery.data(notice_reply, "ElementData", {Bind:'submit'});
288                 $(notice_reply).bind('click', function() {
289                     var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
290                     SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
291                     return false;
292                 });
293             }
294         },
295
296         NoticeReplySet: function(nick,id) {
297             if (nick.match(SN.C.I.PatternUsername)) {
298                 var text = $('#'+SN.C.S.NoticeDataText);
299                 if (text.length > 0) {
300                     replyto = '@' + nick + ' ';
301                     text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
302                     $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
303
304                     text[0].focus();
305                     if (text[0].setSelectionRange) {
306                         var len = text.val().length;
307                         text[0].setSelectionRange(len,len);
308                     }
309                 }
310             }
311         },
312
313         NoticeFavor: function() {
314             $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
315             $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
316         },
317
318         NoticeRepeat: function() {
319             $('.form_repeat').each(function() {
320                 SN.U.FormXHR($(this));
321                 SN.U.NoticeRepeatConfirmation($(this));
322             });
323         },
324
325         NoticeRepeatConfirmation: function(form) {
326             function NRC() {
327                 form.closest('.notice-options').addClass('opaque');
328                 form.addClass('dialogbox');
329
330                 form.append('<button class="close">&#215;</button>');
331                 form.find('button.close').click(function(){
332                     $(this).remove();
333
334                     form.closest('.notice-options').removeClass('opaque');
335                     form.removeClass('dialogbox');
336                     form.find('.submit_dialogbox').remove();
337                     form.find('.submit').show();
338
339                     return false;
340                 });
341             };
342
343             form.find('.submit').bind('click', function(e) {
344                 e.preventDefault();
345
346                 var submit = form.find('.submit').clone();
347                 submit.addClass('submit_dialogbox');
348                 submit.removeClass('submit');
349                 form.append(submit);
350
351                 $(this).hide();
352
353                 NRC();
354             });
355         },
356
357         NoticeAttachments: function() {
358             $('.notice a.attachment').each(function() {
359                 SN.U.NoticeWithAttachment($(this).closest('.notice'));
360             });
361         },
362
363         NoticeWithAttachment: function(notice) {
364             if ($('.attachment', notice).length === 0) {
365                 return;
366             }
367
368             var notice_id = notice.attr('id');
369
370             $.fn.jOverlay.options = {
371                 method : 'GET',
372                 data : '',
373                 url : '',
374                 color : '#000',
375                 opacity : '0.6',
376                 zIndex : 9999,
377                 center : false,
378                 imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
379                 bgClickToClose : true,
380                 success : function() {
381                     $('#jOverlayContent').append('<button class="close">&#215;</button>');
382                     $('#jOverlayContent button').click($.closeOverlay);
383                 },
384                 timeout : 0,
385                 autoHide : true,
386                 css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
387             };
388
389             $('#'+notice_id+' a.attachment').click(function() {
390                 $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
391                 return false;
392             });
393
394             var t;
395             $("body:not(#shownotice) #"+notice_id+" a.thumbnail").hover(
396                 function() {
397                     var anchor = $(this);
398                     $("a.thumbnail").children('img').hide();
399                     anchor.closest(".entry-title").addClass('ov');
400
401                     if (anchor.children('img').length === 0) {
402                         t = setTimeout(function() {
403                             $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
404                                 anchor.append(data);
405                             });
406                         }, 500);
407                     }
408                     else {
409                         anchor.children('img').show();
410                     }
411                 },
412                 function() {
413                     clearTimeout(t);
414                     $("a.thumbnail").children('img').hide();
415                     $(this).closest(".entry-title").removeClass('ov');
416                 }
417             );
418         },
419
420         NoticeDataAttach: function() {
421             NDA = $('#'+SN.C.S.NoticeDataAttach);
422             NDA.change(function() {
423                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
424                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
425                 if (NDAS.length > 0) {
426                     NDAS.replaceWith(S);
427                 }
428                 else {
429                     $('#'+SN.C.S.FormNotice).append(S);
430                 }
431                 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
432                     $('#'+SN.C.S.NoticeDataAttachSelected).remove();
433                     NDA.val('');
434                 });
435             });
436         },
437
438         NoticeLocationAttach: function() {
439             if(navigator.geolocation) navigator.geolocation.watchPosition(function(position) {
440                 $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
441                 $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
442             });
443         },
444
445         NewDirectMessage: function() {
446             NDM = $('.entity_send-a-message a');
447             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
448             NDM.bind('click', function() {
449                 var NDMF = $('.entity_send-a-message form');
450                 if (NDMF.length === 0) {
451                     $(this).addClass('processing');
452                     $.get(NDM.attr('href'), null, function(data) {
453                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
454                         NDMF = $('.entity_send-a-message .form_notice');
455                         SN.U.FormNoticeXHR(NDMF);
456                         SN.U.FormNoticeEnhancements(NDMF);
457                         NDMF.append('<button class="close">&#215;</button>');
458                         $('.entity_send-a-message button').click(function(){
459                             NDMF.hide();
460                             return false;
461                         });
462                         NDM.removeClass('processing');
463                     });
464                 }
465                 else {
466                     NDMF.show();
467                     $('.entity_send-a-message textarea').focus();
468                 }
469                 return false;
470             });
471         }
472     },
473
474     Init: {
475         NoticeForm: function() {
476             if ($('body.user_in').length > 0) {
477                 $('.'+SN.C.S.FormNotice).each(function() {
478                     SN.U.FormNoticeXHR($(this));
479                     SN.U.FormNoticeEnhancements($(this));
480                 });
481
482                 SN.U.NoticeDataAttach();
483                 SN.U.NoticeLocationAttach();
484             }
485         },
486
487         Notices: function() {
488             if ($('body.user_in').length > 0) {
489                 SN.U.NoticeFavor();
490                 SN.U.NoticeRepeat();
491                 SN.U.NoticeReply();
492             }
493
494             SN.U.NoticeAttachments();
495         },
496
497         EntityActions: function() {
498             if ($('body.user_in').length > 0) {
499                 $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
500                 $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
501                 $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
502                 $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
503                 $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });
504
505                 SN.U.NewDirectMessage();
506             }
507         }
508     }
509 };
510
511 $(document).ready(function(){
512     if ($('.'+SN.C.S.FormNotice).length > 0) {
513         SN.Init.NoticeForm();
514     }
515     if ($('#content .notices').length > 0) {
516         SN.Init.Notices();
517     }
518     if ($('#content .entity_actions').length > 0) {
519         SN.Init.EntityActions();
520     }
521 });
522