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