]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
9c79f837ffe1dd3d323865d551f7ec5b36b37083
[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             $('#'+form_id+' #'+SN.C.S.NoticeDataText).unbind('keyup');
61             $('#'+form_id+' #'+SN.C.S.NoticeDataText).unbind('keydown');
62             if (maxLength > 0) {
63                 $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keyup', function(e) {
64                     SN.U.Counter(form);
65                 });
66                 // run once in case there's something in there
67                 SN.U.Counter(form);
68             }
69
70             $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keydown', function(e) {
71                 SN.U.SubmitOnReturn(e, form);
72             });
73
74             if($('body')[0].id != 'conversation') {
75                 $('#'+form_id+' textarea').focus();
76             }
77         },
78
79         SubmitOnReturn: function(event, el) {
80             if (event.keyCode == 13 || event.keyCode == 10) {
81                 el.submit();
82                 event.preventDefault();
83                 event.stopPropagation();
84                 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
85                 $('body').focus();
86                 return false;
87             }
88             return true;
89         },
90
91         Counter: function(form) {
92             SN.C.I.FormNoticeCurrent = form;
93             form_id = form.attr('id');
94             if (typeof(maxLength) == "undefined") {
95                  maxLength = SN.C.I.MaxLength;
96             }
97
98             if (maxLength <= 0) {
99                 return;
100             }
101
102             var remaining = maxLength - $('#'+form_id+' #'+SN.C.S.NoticeDataText).val().length;
103             var counter = $('#'+form_id+' #'+SN.C.S.NoticeTextCount);
104
105             if (remaining.toString() != counter.text()) {
106                 if (!SN.C.I.CounterBlackout || remaining === 0) {
107                     if (counter.text() != String(remaining)) {
108                         counter.text(remaining);
109                     }
110                     if (remaining < 0) {
111                         form.addClass(SN.C.S.Warning);
112                     } else {
113                         form.removeClass(SN.C.S.Warning);
114                     }
115                     // Skip updates for the next 500ms.
116                     // On slower hardware, updating on every keypress is unpleasant.
117                     if (!SN.C.I.CounterBlackout) {
118                         SN.C.I.CounterBlackout = true;
119                         SN.C.I.FormNoticeCurrent = form;
120                         window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
121                     }
122                 }
123             }
124         },
125
126         ClearCounterBlackout: function(form) {
127             // Allow keyup events to poke the counter again
128             SN.C.I.CounterBlackout = false;
129             // Check if the string changed since we last looked
130             SN.U.Counter(form);
131         },
132
133         FormXHR: function(f) {
134             f.bind('submit', function(e) {
135                 form_id = $(this)[0].id;
136                 $.ajax({
137                     type: 'POST',
138                     dataType: 'xml',
139                     url: $(this)[0].action,
140                     data: $(this).serialize() + '&ajax=1',
141                     beforeSend: function(xhr) {
142                         $('#'+form_id).addClass(SN.C.S.Processing);
143                         $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
144                         $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
145                     },
146                     error: function (xhr, textStatus, errorThrown) {
147                         alert(errorThrown || textStatus);
148                     },
149                     success: function(data, textStatus) {
150                         if (typeof($('form', data)[0]) != 'undefined') {
151                             form_new = document._importNode($('form', data)[0], true);
152                             $('#'+form_id).replaceWith(form_new);
153                             $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
154                         }
155                         else {
156                             $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
157                         }
158                     }
159                 });
160                 return false;
161             });
162         },
163
164         FormNoticeXHR: function(form) {
165             form_id = form.attr('id');
166             form.append('<input type="hidden" name="ajax" value="1"/>');
167             form.ajaxForm({
168                 dataType: 'xml',
169                 timeout: '60000',
170                 beforeSend: function(xhr) {
171                     if ($('#'+form_id+' #'+SN.C.S.NoticeDataText)[0].value.length === 0) {
172                         form.addClass(SN.C.S.Warning);
173                         return false;
174                     }
175                     form.addClass(SN.C.S.Processing);
176                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
177                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
178                     return true;
179                 },
180                 error: function (xhr, textStatus, errorThrown) {
181                     form.removeClass(SN.C.S.Processing);
182                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
183                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
184                     if (textStatus == 'timeout') {
185                         alert ('Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists');
186                     }
187                     else {
188                         if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
189                             form.append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
190                         }
191                         else {
192                             if(jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) < 0) {
193                                 alert('Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
194                             }
195                             else {
196                                 $('#'+form_id+' #'+SN.C.S.NoticeDataText).val('');
197                                 SN.U.FormNoticeEnhancements($('#'+form_id));
198                             }
199                         }
200                     }
201                 },
202                 success: function(data, textStatus) {
203                     var result;
204                     if ($('#'+SN.C.S.Error, data).length > 0) {
205                         result = document._importNode($('p', data)[0], true);
206                         alert(result.textContent || result.innerHTML);
207                     }
208                     else {
209                         if($('body')[0].id == 'bookmarklet') {
210                             self.close();
211                         }
212
213                         if ($('#'+SN.C.S.CommandResult, data).length > 0) {
214                             result = document._importNode($('p', data)[0], true);
215                             alert(result.textContent || result.innerHTML);
216                         }
217                         else {
218                              notice = document._importNode($('li', data)[0], true);
219                              if ($('#'+notice.id).length === 0) {
220                                 var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
221                                 var notice_irt = '#notices_primary #notice-'+notice_irt_value;
222                                 if($('body')[0].id == 'conversation') {
223                                     if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
224                                         $(notice_irt).append('<ul class="notices"></ul>');
225                                     }
226                                     $($(notice_irt+' .notices')[0]).append(notice);
227                                 }
228                                 else {
229                                     $("#notices_primary .notices").prepend(notice);
230                                 }
231                                 $('#'+notice.id).css({display:'none'});
232                                 $('#'+notice.id).fadeIn(2500);
233                                 SN.U.NoticeAttachments();
234                                 SN.U.NoticeReply();
235                                 SN.U.NoticeFavor();
236                              }
237                         }
238                         $('#'+form_id+' #'+SN.C.S.NoticeDataText).val('');
239                         $('#'+form_id+' #'+SN.C.S.NoticeDataAttach).val('');
240                         $('#'+form_id+' #'+SN.C.S.NoticeInReplyTo).val('');
241                         $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
242                         SN.U.FormNoticeEnhancements($('#'+form_id));
243                     }
244                 },
245                 complete: function(xhr, textStatus) {
246                     form.removeClass(SN.C.S.Processing);
247                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
248                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
249                 }
250             });
251         },
252
253         NoticeReply: function() {
254             if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
255                 $('#content .notice').each(function() {
256                     var notice = $(this)[0];
257                     $($('.notice_reply', notice)[0]).click(function() {
258                         var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
259                         SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
260                         return false;
261                     });
262                 });
263             }
264         },
265
266         NoticeReplySet: function(nick,id) {
267             if (nick.match(SN.C.I.PatternUsername)) {
268                 var text = $('#'+SN.C.S.NoticeDataText);
269                 if (text.length) {
270                     replyto = '@' + nick + ' ';
271                     text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
272                     $('#'+SN.C.S.FormNotice+' input#'+SN.C.S.NoticeInReplyTo).val(id);
273                     if (text[0].setSelectionRange) {
274                         var len = text.val().length;
275                         text[0].setSelectionRange(len,len);
276                         text[0].focus();
277                     }
278                     return false;
279                 }
280             }
281             return true;
282         },
283
284         NoticeFavor: function() {
285             $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
286             $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
287         },
288
289         NoticeAttachments: function() {
290             $.fn.jOverlay.options = {
291                 method : 'GET',
292                 data : '',
293                 url : '',
294                 color : '#000',
295                 opacity : '0.6',
296                 zIndex : 99,
297                 center : false,
298                 imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
299                 bgClickToClose : true,
300                 success : function() {
301                     $('#jOverlayContent').append('<button class="close">&#215;</button>');
302                     $('#jOverlayContent button').click($.closeOverlay);
303                 },
304                 timeout : 0,
305                 autoHide : true,
306                 css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
307             };
308
309             $('#content .notice a.attachment').click(function() {
310                 $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
311                 return false;
312             });
313
314             var t;
315             $("body:not(#shownotice) #content .notice a.thumbnail").hover(
316                 function() {
317                     var anchor = $(this);
318                     $("a.thumbnail").children('img').hide();
319                     anchor.closest(".entry-title").addClass('ov');
320
321                     if (anchor.children('img').length === 0) {
322                         t = setTimeout(function() {
323                             $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
324                                 anchor.append(data);
325                             });
326                         }, 500);
327                     }
328                     else {
329                         anchor.children('img').show();
330                     }
331                 },
332                 function() {
333                     clearTimeout(t);
334                     $("a.thumbnail").children('img').hide();
335                     $(this).closest(".entry-title").removeClass('ov');
336                 }
337             );
338         },
339
340         NoticeDataAttach: function() {
341             NDA = $('#'+SN.C.S.NoticeDataAttach);
342             NDA.change(function() {
343                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
344                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
345                 if (NDAS.length > 0) {
346                     NDAS.replaceWith(S);
347                 }
348                 else {
349                     $('#'+SN.C.S.FormNotice).append(S);
350                 }
351                 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
352                     $('#'+SN.C.S.NoticeDataAttachSelected).remove();
353                     NDA.val('');
354                 });
355             });
356         },
357
358         NoticeLocationAttach: function() {
359             if(navigator.geolocation) navigator.geolocation.watchPosition(function(position) {
360                 $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
361                 $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
362             });
363         },
364
365         NewDirectMessage: function() {
366             NDM = $('.entity_send-a-message a');
367             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
368             NDM.click(function() {
369                 var NDMF = $('.entity_send-a-message form');
370                 if (NDMF.length === 0) {
371                     $.get(NDM.attr('href'), null, function(data) {
372                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
373                         NDMF = $('.entity_send-a-message .form_notice');
374                         SN.U.FormNoticeXHR(NDMF);
375                         SN.U.FormNoticeEnhancements(NDMF);
376                         NDMF.append('<button class="close">&#215;</button>');
377                         $('.entity_send-a-message button').click(function(){
378                             NDMF.hide();
379                             return false;
380                         });
381                     });
382                 }
383                 else {
384                     NDMF.show();
385                     $('.entity_send-a-message textarea').focus();
386                 }
387                 return false;
388             });
389         }
390     },
391
392     Init: {
393         NoticeForm: function() {
394             if ($('body.user_in').length > 0) {
395                 $('.'+SN.C.S.FormNotice).each(function() {
396                     SN.U.FormNoticeXHR($(this));
397                     SN.U.FormNoticeEnhancements($(this));
398                 });
399
400                 SN.U.NoticeDataAttach();
401                 SN.U.NoticeLocationAttach();
402             }
403         },
404
405         Notices: function() {
406             if ($('body.user_in').length > 0) {
407                 SN.U.NoticeFavor();
408
409                 SN.U.NoticeReply();
410             }
411
412             SN.U.NoticeAttachments();
413         },
414
415         EntityActions: function() {
416             if ($('body.user_in').length > 0) {
417                 $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
418                 $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
419                 $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
420                 $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
421                 $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });
422
423                 SN.U.NewDirectMessage();
424             }
425         }
426     }
427 };
428
429 $(document).ready(function(){
430     if ($('.'+SN.C.S.FormNotice).length > 0) {
431         SN.Init.NoticeForm();
432     }
433     if ($('#content .notices').length > 0) {
434         SN.Init.Notices();
435     }
436     if ($('#content .entity_actions').length > 0) {
437         SN.Init.EntityActions();
438     }
439 });
440