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