]> git.wh0rd.org Git - tt-rss.git/blob - functions.js
1fd421809267b57d0be66ddede63ab1c4cd97640
[tt-rss.git] / functions.js
1 var notify_silent = false;
2 var loading_progress = 0;
3 var sanity_check_done = false;
4
5 /* add method to remove element from array */
6
7 Array.prototype.remove = function(s) {
8         for (var i=0; i < this.length; i++) {
9                 if (s == this[i]) this.splice(i, 1);
10         }
11 }
12
13 /* create console.log if it doesn't exist */
14
15 if (!window.console) console = {};
16 console.log = console.log || function(msg) { };
17 console.warn = console.warn || function(msg) { };
18 console.error = console.error || function(msg) { };
19
20 function exception_error(location, e, ext_info) {
21         var msg = format_exception_error(location, e);
22
23         if (!ext_info) ext_info = false;
24
25         try {
26
27                 if (ext_info) {
28                         if (ext_info.responseText) {
29                                 ext_info = ext_info.responseText;
30                         }
31                 }
32
33                 var content = "<div class=\"fatalError\">" +
34                         "<pre>" + msg + "</pre>";
35
36                 content += "<form name=\"exceptionForm\" id=\"exceptionForm\" target=\"_blank\" "+
37                   "action=\"http://tt-rss.org/report.php\" method=\"POST\">";
38
39                 content += "<textarea style=\"display : none\" name=\"message\">" + msg + "</textarea>";
40                 content += "<textarea style=\"display : none\" name=\"params\">N/A</textarea>";
41
42                 if (ext_info) {
43                         content += "<div><b>Additional information:</b></div>" +
44                         "<textarea name=\"xinfo\" readonly=\"1\">" + ext_info + "</textarea>";
45                 }
46
47                 content += "<div><b>Stack trace:</b></div>" +
48                         "<textarea name=\"stack\" readonly=\"1\">" + e.stack + "</textarea>";
49
50                 content += "</form>";
51
52                 content += "</div>";
53
54                 content += "<div class='dlgButtons'>";
55
56                 content += "<button dojoType=\"dijit.form.Button\""+
57                                 "onclick=\"dijit.byId('exceptionDlg').report()\">" +
58                                 __('Report to tt-rss.org') + "</button> ";
59                 content += "<button dojoType=\"dijit.form.Button\" "+
60                                 "onclick=\"dijit.byId('exceptionDlg').hide()\">" +
61                                 __('Close') + "</button>";
62                 content += "</div>";
63
64                 if (dijit.byId("exceptionDlg"))
65                         dijit.byId("exceptionDlg").destroyRecursive();
66
67                 var dialog = new dijit.Dialog({
68                         id: "exceptionDlg",
69                         title: "Unhandled exception",
70                         style: "width: 600px",
71                         report: function() {
72                                 if (confirm(__("Are you sure to report this exception to tt-rss.org? The report will include your browser information. Your IP would be saved in the database."))) {
73
74                                         document.forms['exceptionForm'].params.value = $H({
75                                                 browserName: navigator.appName,
76                                                 browserVersion: navigator.appVersion,
77                                                 browserPlatform: navigator.platform,
78                                                 browserCookies: navigator.cookieEnabled,
79                                         }).toQueryString();
80
81                                         document.forms['exceptionForm'].submit();
82
83                                 }
84                         },
85                         content: content});
86
87                 dialog.show();
88
89         } catch (e) {
90                 alert(msg);
91         }
92
93 }
94
95 function format_exception_error(location, e) {
96         var msg;
97
98         if (e.fileName) {
99                 var base_fname = e.fileName.substring(e.fileName.lastIndexOf("/") + 1);
100
101                 msg = "Exception: " + e.name + ", " + e.message +
102                         "\nFunction: " + location + "()" +
103                         "\nLocation: " + base_fname + ":" + e.lineNumber;
104
105         } else if (e.description) {
106                 msg = "Exception: " + e.description + "\nFunction: " + location + "()";
107         } else {
108                 msg = "Exception: " + e + "\nFunction: " + location + "()";
109         }
110
111         console.error("EXCEPTION: " + msg);
112
113         return msg;
114 }
115
116 function param_escape(arg) {
117         if (typeof encodeURIComponent != 'undefined')
118                 return encodeURIComponent(arg);
119         else
120                 return escape(arg);
121 }
122
123 function param_unescape(arg) {
124         if (typeof decodeURIComponent != 'undefined')
125                 return decodeURIComponent(arg);
126         else
127                 return unescape(arg);
128 }
129
130 var notify_hide_timerid = false;
131
132 function hide_notify() {
133         var n = $("notify");
134         if (n) {
135                 n.style.display = "none";
136         }
137 }
138
139 function notify_silent_next() {
140         notify_silent = true;
141 }
142
143 function notify_real(msg, no_hide, n_type) {
144
145         if (notify_silent) {
146                 notify_silent = false;
147                 return;
148         }
149
150         var n = $("notify");
151         var nb = $("notify_body");
152
153         if (!n || !nb) return;
154
155         if (notify_hide_timerid) {
156                 window.clearTimeout(notify_hide_timerid);
157         }
158
159         if (msg == "") {
160                 if (n.style.display == "block") {
161                         notify_hide_timerid = window.setTimeout("hide_notify()", 0);
162                 }
163                 return;
164         } else {
165                 n.style.display = "block";
166         }
167
168         /* types:
169
170                 1 - generic
171                 2 - progress
172                 3 - error
173                 4 - info
174
175         */
176
177         if (typeof __ != 'undefined') {
178                 msg = __(msg);
179         }
180
181         if (n_type == 1) {
182                 n.className = "notify";
183         } else if (n_type == 2) {
184                 n.className = "notifyProgress";
185                 msg = "<img src='"+getInitParam("sign_progress")+"'> " + msg;
186         } else if (n_type == 3) {
187                 n.className = "notifyError";
188                 msg = "<img src='"+getInitParam("sign_excl")+"'> " + msg;
189         } else if (n_type == 4) {
190                 n.className = "notifyInfo";
191                 msg = "<img src='"+getInitParam("sign_info")+"'> " + msg;
192         }
193
194 //      msg = "<img src='images/live_com_loading.gif'> " + msg;
195
196         nb.innerHTML = msg;
197
198         if (!no_hide) {
199                 notify_hide_timerid = window.setTimeout("hide_notify()", 3000);
200         }
201 }
202
203 function notify(msg, no_hide) {
204         notify_real(msg, no_hide, 1);
205 }
206
207 function notify_progress(msg, no_hide) {
208         notify_real(msg, no_hide, 2);
209 }
210
211 function notify_error(msg, no_hide) {
212         notify_real(msg, no_hide, 3);
213
214 }
215
216 function notify_info(msg, no_hide) {
217         notify_real(msg, no_hide, 4);
218 }
219
220 function setCookie(name, value, lifetime, path, domain, secure) {
221
222         var d = false;
223
224         if (lifetime) {
225                 d = new Date();
226                 d.setTime(d.getTime() + (lifetime * 1000));
227         }
228
229         console.log("setCookie: " + name + " => " + value + ": " + d);
230
231         int_setCookie(name, value, d, path, domain, secure);
232
233 }
234
235 function int_setCookie(name, value, expires, path, domain, secure) {
236         document.cookie= name + "=" + escape(value) +
237                 ((expires) ? "; expires=" + expires.toGMTString() : "") +
238                 ((path) ? "; path=" + path : "") +
239                 ((domain) ? "; domain=" + domain : "") +
240                 ((secure) ? "; secure" : "");
241 }
242
243 function delCookie(name, path, domain) {
244         if (getCookie(name)) {
245                 document.cookie = name + "=" +
246                 ((path) ? ";path=" + path : "") +
247                 ((domain) ? ";domain=" + domain : "" ) +
248                 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
249         }
250 }
251
252
253 function getCookie(name) {
254
255         var dc = document.cookie;
256         var prefix = name + "=";
257         var begin = dc.indexOf("; " + prefix);
258         if (begin == -1) {
259             begin = dc.indexOf(prefix);
260             if (begin != 0) return null;
261         }
262         else {
263             begin += 2;
264         }
265         var end = document.cookie.indexOf(";", begin);
266         if (end == -1) {
267             end = dc.length;
268         }
269         return unescape(dc.substring(begin + prefix.length, end));
270 }
271
272 function gotoPreferences() {
273         document.location.href = "prefs.php";
274 }
275
276 function gotoMain() {
277         document.location.href = "tt-rss.php";
278 }
279
280 function gotoExportOpml(filename, settings) {
281     tmp = settings ? 1 : 0;
282         document.location.href = "opml.php?op=Export&filename=" + filename + "&settings=" + tmp;
283 }
284
285
286 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
287   * * @author Sundar Dorai-Raj
288   * * Email: sdoraira@vt.edu
289   * * This program is free software; you can redistribute it and/or
290   * * modify it under the terms of the GNU General Public License
291   * * as published by the Free Software Foundation; either version 2
292   * * of the License, or (at your option) any later version,
293   * * provided that any use properly credits the author.
294   * * This program is distributed in the hope that it will be useful,
295   * * but WITHOUT ANY WARRANTY; without even the implied warranty of
296   * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
297   * * GNU General Public License for more details at http://www.gnu.org * * */
298
299   var numbers=".0123456789";
300   function isNumeric(x) {
301     // is x a String or a character?
302     if(x.length>1) {
303       // remove negative sign
304       x=Math.abs(x)+"";
305       for(j=0;j<x.length;j++) {
306         // call isNumeric recursively for each character
307         number=isNumeric(x.substring(j,j+1));
308         if(!number) return number;
309       }
310       return number;
311     }
312     else {
313       // if x is number return true
314       if(numbers.indexOf(x)>=0) return true;
315       return false;
316     }
317   }
318
319
320 function toggleSelectRowById(sender, id) {
321         var row = $(id);
322         return toggleSelectRow(sender, row);
323 }
324
325 function toggleSelectListRow(sender) {
326         var row = sender.parentNode;
327         return toggleSelectRow(sender, row);
328 }
329
330 /* this is for dijit Checkbox */
331 function toggleSelectListRow2(sender) {
332         var row = sender.domNode.parentNode;
333         return toggleSelectRow(sender, row);
334 }
335
336 function tSR(sender, row) {
337         return toggleSelectRow(sender, row);
338 }
339
340 /* this is for dijit Checkbox */
341 function toggleSelectRow2(sender, row) {
342
343         if (!row) row = sender.domNode.parentNode.parentNode;
344
345         if (sender.checked && !row.hasClassName('Selected'))
346                 row.addClassName('Selected');
347         else
348                 row.removeClassName('Selected');
349 }
350
351
352 function toggleSelectRow(sender, row) {
353
354         if (!row) row = sender.parentNode.parentNode;
355
356         if (sender.checked && !row.hasClassName('Selected'))
357                 row.addClassName('Selected');
358         else
359                 row.removeClassName('Selected');
360 }
361
362 function checkboxToggleElement(elem, id) {
363         if (elem.checked) {
364                 Effect.Appear(id, {duration : 0.5});
365         } else {
366                 Effect.Fade(id, {duration : 0.5});
367         }
368 }
369
370 function dropboxSelect(e, v) {
371         for (i = 0; i < e.length; i++) {
372                 if (e[i].value == v) {
373                         e.selectedIndex = i;
374                         break;
375                 }
376         }
377 }
378
379 function getURLParam(param){
380         return String(window.location.href).parseQuery()[param];
381 }
382
383 function leading_zero(p) {
384         var s = String(p);
385         if (s.length == 1) s = "0" + s;
386         return s;
387 }
388
389 function make_timestamp() {
390         var d = new Date();
391
392         return leading_zero(d.getHours()) + ":" + leading_zero(d.getMinutes()) +
393                         ":" + leading_zero(d.getSeconds());
394 }
395
396
397 function closeErrorBox() {
398
399         if (Element.visible("errorBoxShadow")) {
400                 Element.hide("dialog_overlay");
401                 Element.hide("errorBoxShadow");
402         }
403
404         return false;
405 }
406
407 function closeInfoBox(cleanup) {
408         try {
409                 dialog = dijit.byId("infoBox");
410
411                 if (dialog)     dialog.hide();
412
413         } catch (e) {
414                 //exception_error("closeInfoBox", e);
415         }
416         return false;
417 }
418
419
420 function displayDlg(id, param, callback) {
421
422         notify_progress("Loading, please wait...", true);
423
424         var query = "?op=dlg&id=" +
425                 param_escape(id) + "&param=" + param_escape(param);
426
427         new Ajax.Request("backend.php", {
428                 parameters: query,
429                 onComplete: function (transport) {
430                         infobox_callback2(transport);
431                         if (callback) callback(transport);
432                 } });
433
434         return false;
435 }
436
437 function infobox_callback2(transport) {
438         try {
439                 var dialog = false;
440
441                 if (dijit.byId("infoBox")) {
442                         dialog = dijit.byId("infoBox");
443                 }
444
445                 //console.log("infobox_callback2");
446                 notify('');
447
448                 var content;
449                 var dtitle = "Dialog";
450
451                 var dlg = transport.responseXML.getElementsByTagName("dlg")[0];
452
453                 var title = transport.responseXML.getElementsByTagName("title")[0];
454                 if (title)
455                         title = title.firstChild.nodeValue;
456
457                 var content = transport.responseXML.getElementsByTagName("content")[0];
458
459                 content = content.firstChild.nodeValue;
460
461                 if (!dialog) {
462                         dialog = new dijit.Dialog({
463                                 title: title,
464                                 id: 'infoBox',
465                                 style: "width: 600px",
466                                 onCancel: function() {
467                                         return true;
468                                 },
469                                 onExecute: function() {
470                                         return true;
471                                 },
472                                 onClose: function() {
473                                         return true;
474                                         },
475                                 content: content});
476                 } else {
477                         dialog.attr('title', title);
478                         dialog.attr('content', content);
479                 }
480
481                 dialog.show();
482
483                 notify("");
484         } catch (e) {
485                 exception_error("infobox_callback2", e);
486         }
487 }
488
489 function filterCR(e, f)
490 {
491      var key;
492
493      if(window.event)
494           key = window.event.keyCode;     //IE
495      else
496           key = e.which;     //firefox
497
498         if (key == 13) {
499                 if (typeof f != 'undefined') {
500                         f();
501                         return false;
502                 } else {
503                         return false;
504                 }
505         } else {
506                 return true;
507         }
508 }
509
510 function getInitParam(key) {
511         return init_params[key];
512 }
513
514 function setInitParam(key, value) {
515         init_params[key] = value;
516 }
517
518 function fatalError(code, msg, ext_info) {
519         try {
520
521                 if (code == 6) {
522                         window.location.href = "tt-rss.php";
523                 } else if (code == 5) {
524                         window.location.href = "db-updater.php";
525                 } else {
526
527                         if (msg == "") msg = "Unknown error";
528
529                         if (ext_info) {
530                                 if (ext_info.responseText) {
531                                         ext_info = ext_info.responseText;
532                                 }
533                         }
534
535                         if (ERRORS && ERRORS[code] && !msg) {
536                                 msg = ERRORS[code];
537                         }
538
539                         var content = "<div><b>Error code:</b> " + code + "</div>" +
540                                 "<p>" + msg + "</p>";
541
542                         if (ext_info) {
543                                 content = content + "<div><b>Additional information:</b></div>" +
544                                         "<textarea style='width: 100%' readonly=\"1\">" +
545                                         ext_info + "</textarea>";
546                         }
547
548                         var dialog = new dijit.Dialog({
549                                 title: "Fatal error",
550                                 style: "width: 600px",
551                                 content: content});
552
553                         dialog.show();
554
555                 }
556
557                 return false;
558
559         } catch (e) {
560                 exception_error("fatalError", e);
561         }
562 }
563
564 function filterDlgCheckType(sender) {
565
566         try {
567
568                 var ftype = sender.value;
569
570                 // if selected filter type is 5 (Date) enable the modifier dropbox
571                 if (ftype == 5) {
572                         Element.show("filterDlg_dateModBox");
573                         Element.show("filterDlg_dateChkBox");
574                 } else {
575                         Element.hide("filterDlg_dateModBox");
576                         Element.hide("filterDlg_dateChkBox");
577
578                 }
579
580         } catch (e) {
581                 exception_error("filterDlgCheckType", e);
582         }
583
584 }
585
586 function filterDlgCheckAction(sender) {
587
588         try {
589
590                 var action = sender.value;
591
592                 var action_param = $("filterDlg_paramBox");
593
594                 if (!action_param) {
595                         console.log("filterDlgCheckAction: can't find action param box!");
596                         return;
597                 }
598
599                 // if selected action supports parameters, enable params field
600                 if (action == 4 || action == 6 || action == 7) {
601                         new Effect.Appear(action_param, {duration : 0.5});
602                         if (action != 7) {
603                                 Element.show(dijit.byId("filterDlg_actionParam").domNode);
604                                 Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode);
605                         } else {
606                                 Element.show(dijit.byId("filterDlg_actionParamLabel").domNode);
607                                 Element.hide(dijit.byId("filterDlg_actionParam").domNode);
608                         }
609                 } else {
610                         Element.hide(action_param);
611                 }
612
613         } catch (e) {
614                 exception_error("filterDlgCheckAction", e);
615         }
616
617 }
618
619 function filterDlgCheckDate() {
620         try {
621                 var dialog = dijit.byId("filterEditDlg");
622
623                 var reg_exp = dialog.attr('value').reg_exp;
624
625                 var query = "?op=rpc&subop=checkDate&date=" + reg_exp;
626
627                 new Ajax.Request("backend.php", {
628                         parameters: query,
629                         onComplete: function(transport) {
630
631                                 var reply = JSON.parse(transport.responseText);
632
633                                 if (reply['result'] == true) {
634                                         alert(__("Date syntax appears to be correct:") + " " + reply['date']);
635                                         return;
636                                 } else {
637                                         alert(__("Date syntax is incorrect."));
638                                 }
639
640                         } });
641
642
643         } catch (e) {
644                 exception_error("filterDlgCheckDate", e);
645         }
646 }
647
648 function explainError(code) {
649         return displayDlg("explainError", code);
650 }
651
652 function displayHelpInfobox(topic_id) {
653
654         var url = "backend.php?op=help&tid=" + param_escape(topic_id);
655
656         var w = window.open(url, "ttrss_help",
657                 "status=0,toolbar=0,location=0,width=450,height=500,scrollbars=1,menubar=0");
658
659 }
660
661 function loading_set_progress(p) {
662         try {
663                 loading_progress += p;
664
665                 if (dijit.byId("loading_bar"))
666                         dijit.byId("loading_bar").update({progress: loading_progress});
667
668                 if (loading_progress >= 90)
669                         remove_splash();
670
671         } catch (e) {
672                 exception_error("loading_set_progress", e);
673         }
674 }
675
676 function remove_splash() {
677
678         if (Element.visible("overlay")) {
679                 console.log("about to remove splash, OMG!");
680                 Element.hide("overlay");
681                 console.log("removed splash!");
682         }
683 }
684
685 function transport_error_check(transport) {
686         try {
687                 if (transport.responseXML) {
688                         var error = transport.responseXML.getElementsByTagName("error")[0];
689
690                         if (error) {
691                                 var code = error.getAttribute("error-code");
692                                 var msg = error.getAttribute("error-msg");
693                                 if (code != 0) {
694                                         fatalError(code, msg);
695                                         return false;
696                                 }
697                         }
698                 }
699         } catch (e) {
700                 exception_error("check_for_error_xml", e);
701         }
702         return true;
703 }
704
705 function strip_tags(s) {
706         return s.replace(/<\/?[^>]+(>|$)/g, "");
707 }
708
709 function truncate_string(s, length) {
710         if (!length) length = 30;
711         var tmp = s.substring(0, length);
712         if (s.length > length) tmp += "&hellip;";
713         return tmp;
714 }
715
716 function hotkey_prefix_timeout() {
717         try {
718
719                 var date = new Date();
720                 var ts = Math.round(date.getTime() / 1000);
721
722                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
723                         console.log("hotkey_prefix seems to be stuck, aborting");
724                         hotkey_prefix_pressed = false;
725                         hotkey_prefix = false;
726                         Element.hide('cmdline');
727                 }
728
729                 setTimeout("hotkey_prefix_timeout()", 1000);
730
731         } catch  (e) {
732                 exception_error("hotkey_prefix_timeout", e);
733         }
734 }
735
736 function hideAuxDlg() {
737         try {
738                 Element.hide('auxDlg');
739         } catch (e) {
740                 exception_error("hideAuxDlg", e);
741         }
742 }
743
744
745 function uploadIconHandler(rc) {
746         try {
747                 switch (rc) {
748                         case 0:
749                                 notify_info("Upload complete.");
750                                 if (inPreferences()) {
751                                         updateFeedList();
752                                 } else {
753                                         setTimeout('updateFeedList(false, false)', 50);
754                                 }
755                                 break;
756                         case 1:
757                                 notify_error("Upload failed: icon is too big.");
758                                 break;
759                         case 2:
760                                 notify_error("Upload failed.");
761                                 break;
762                 }
763
764         } catch (e) {
765                 exception_error("uploadIconHandler", e);
766         }
767 }
768
769 function removeFeedIcon(id) {
770
771         try {
772
773                 if (confirm(__("Remove stored feed icon?"))) {
774                         var query = "backend.php?op=pref-feeds&subop=removeicon&feed_id=" + param_escape(id);
775
776                         console.log(query);
777
778                         notify_progress("Removing feed icon...", true);
779
780                         new Ajax.Request("backend.php", {
781                                 parameters: query,
782                                 onComplete: function(transport) {
783                                         notify_info("Feed icon removed.");
784                                         if (inPreferences()) {
785                                                 updateFeedList();
786                                         } else {
787                                                 setTimeout('updateFeedList(false, false)', 50);
788                                         }
789                                 } });
790                 }
791
792                 return false;
793         } catch (e) {
794                 exception_error("uploadFeedIcon", e);
795         }
796 }
797
798 function uploadFeedIcon() {
799
800         try {
801
802                 var file = $("icon_file");
803
804                 if (file.value.length == 0) {
805                         alert(__("Please select an image file to upload."));
806                 } else {
807                         if (confirm(__("Upload new icon for this feed?"))) {
808                                 notify_progress("Uploading, please wait...", true);
809                                 return true;
810                         }
811                 }
812
813                 return false;
814
815         } catch (e) {
816                 exception_error("uploadFeedIcon", e);
817         }
818 }
819
820 function addLabel(select, callback) {
821
822         try {
823
824                 var caption = prompt(__("Please enter label caption:"), "");
825
826                 if (caption != undefined) {
827
828                         if (caption == "") {
829                                 alert(__("Can't create label: missing caption."));
830                                 return false;
831                         }
832
833                         var query = "?op=pref-labels&subop=add&caption=" +
834                                 param_escape(caption);
835
836                         if (select)
837                                 query += "&output=select";
838
839                         notify_progress("Loading, please wait...", true);
840
841                         if (inPreferences() && !select) active_tab = "labelConfig";
842
843                         new Ajax.Request("backend.php", {
844                                 parameters: query,
845                                 onComplete: function(transport) {
846                                         if (callback) {
847                                                 callback(transport);
848                                         } else if (inPreferences()) {
849                                                 updateLabelList();
850                                         } else {
851                                                 updateFeedList();
852                                         }
853                         } });
854
855                 }
856
857         } catch (e) {
858                 exception_error("addLabel", e);
859         }
860 }
861
862 function quickAddFeed() {
863         try {
864                 var query = "backend.php?op=dlg&id=quickAddFeed";
865
866                 if (dijit.byId("feedAddDlg"))
867                         dijit.byId("feedAddDlg").destroyRecursive();
868
869                 var dialog = new dijit.Dialog({
870                         id: "feedAddDlg",
871                         title: __("Subscribe to Feed"),
872                         style: "width: 600px",
873                         execute: function() {
874                                 if (this.validate()) {
875                                         console.log(dojo.objectToQuery(this.attr('value')));
876
877                                         var feed_url = this.attr('value').feed;
878
879                                         notify_progress(__("Subscribing to feed..."), true);
880
881                                         new Ajax.Request("backend.php", {
882                                                 parameters: dojo.objectToQuery(this.attr('value')),
883                                                 onComplete: function(transport) {
884                                                         try {
885
886                                                                 var reply = JSON.parse(transport.responseText);
887
888                                                                 var rc = parseInt(reply['result']);
889
890                                                                 notify('');
891
892                                                                 console.log("GOT RC: " + rc);
893
894                                                                 switch (rc) {
895                                                                 case 1:
896                                                                         dialog.hide();
897                                                                         notify_info(__("Subscribed to %s").replace("%s", feed_url));
898
899                                                                         updateFeedList();
900                                                                         break;
901                                                                 case 2:
902                                                                         alert(__("Specified URL seems to be invalid."));
903                                                                         break;
904                                                                 case 3:
905                                                                         alert(__("Specified URL doesn't seem to contain any feeds."));
906                                                                         break;
907                                                                 case 4:
908                                                                         notify_progress("Searching for feed urls...", true);
909
910                                                                         new Ajax.Request("backend.php", {
911                                                                                 parameters: 'op=rpc&subop=extractfeedurls&url=' + param_escape(feed_url),
912                                                                                 onComplete: function(transport, dialog, feed_url) {
913
914                                                                                         notify('');
915
916                                                                                         var reply = JSON.parse(transport.responseText);
917
918                                                                                         var feeds = reply['urls'];
919
920                                                                                         console.log(transport.responseText);
921
922                                                                                         var select = dijit.byId("feedDlg_feedContainerSelect");
923
924                                                                                         while (select.getOptions().length > 0)
925                                                                                                 select.removeOption(0);
926
927                                                                                         var count = 0;
928                                                                                         for (var feedUrl in feeds) {
929                                                                                                 select.addOption({value: feedUrl, label: feeds[feedUrl]});
930                                                                                                 count++;
931                                                                                         }
932
933 //                                                                                      if (count > 5) count = 5;
934 //                                                                                      select.size = count;
935
936                                                                                         Effect.Appear('feedDlg_feedsContainer', {duration : 0.5});
937                                                                                 }
938                                                                         });
939                                                                         break;
940                                                                 case 5:
941                                                                         alert(__("Couldn't download the specified URL."));
942                                                                         break;
943                                                                 case 0:
944                                                                         alert(__("You are already subscribed to this feed."));
945                                                                         break;
946                                                                 }
947
948                                                         } catch (e) {
949                                                                 exception_error("subscribeToFeed", e, transport);
950                                                         }
951
952                                                 } });
953
954                                         }
955                         },
956                         href: query});
957
958                 dialog.show();
959         } catch (e) {
960                 exception_error("quickAddFeed", e);
961         }
962 }
963
964 function quickAddFilter() {
965         try {
966                 var query = "backend.php?op=dlg&id=quickAddFilter";
967
968                 if (dijit.byId("filterEditDlg"))
969                         dijit.byId("filterEditDlg").destroyRecursive();
970
971                 dialog = new dijit.Dialog({
972                         id: "filterEditDlg",
973                         title: __("Create Filter"),
974                         style: "width: 600px",
975                         test: function() {
976                                 if (this.validate()) {
977
978                                         if (dijit.byId("filterTestDlg"))
979                                                 dijit.byId("filterTestDlg").destroyRecursive();
980
981                                         tdialog = new dijit.Dialog({
982                                                 id: "filterTestDlg",
983                                                 title: __("Filter Test Results"),
984                                                 style: "width: 600px",
985                                                 href: "backend.php?savemode=test&" +
986                                                         dojo.objectToQuery(dialog.attr('value')),
987                                                 });
988
989                                         tdialog.show();
990
991                                 }
992                         },
993                         execute: function() {
994                                 if (this.validate()) {
995
996                                         var query = "?op=rpc&subop=verifyRegexp&reg_exp=" +
997                                                 param_escape(dialog.attr('value').reg_exp);
998
999                                         notify_progress("Verifying regular expression...");
1000
1001                                         new Ajax.Request("backend.php", {
1002                                                 parameters: query,
1003                                                 onComplete: function(transport) {
1004                                                         var reply = JSON.parse(transport.responseText);
1005
1006                                                         if (reply) {
1007                                                                 notify('');
1008
1009                                                                 if (!reply['status']) {
1010                                                                         alert("Match regular expression seems to be invalid.");
1011                                                                         return;
1012                                                                 } else {
1013                                                                         notify_progress("Saving data...", true);
1014
1015                                                                         console.log(dojo.objectToQuery(dialog.attr('value')));
1016
1017                                                                         new Ajax.Request("backend.php", {
1018                                                                                 parameters: dojo.objectToQuery(dialog.attr('value')),
1019                                                                                 onComplete: function(transport) {
1020                                                                                         dialog.hide();
1021                                                                                         notify_info(transport.responseText);
1022                                                                                         if (inPreferences()) {
1023                                                                                                 updateFilterList();
1024                                                                                         }
1025                                                                         }})
1026                                                                 }
1027                                                         }
1028                                         }});
1029                                 }
1030                         },
1031                         href: query});
1032
1033                 dialog.show();
1034         } catch (e) {
1035                 exception_error("quickAddFilter", e);
1036         }
1037 }
1038
1039 function resetPubSub(feed_id, title) {
1040
1041         var msg = __("Reset subscription? Tiny Tiny RSS will try to subscribe to the notification hub again on next feed update.").replace("%s", title);
1042
1043         if (title == undefined || confirm(msg)) {
1044                 notify_progress("Loading, please wait...");
1045
1046                 var query = "?op=pref-feeds&quiet=1&subop=resetPubSub&ids=" + feed_id;
1047
1048                 new Ajax.Request("backend.php", {
1049                         parameters: query,
1050                         onComplete: function(transport) {
1051                                 dijit.byId("pubsubReset_Btn").attr('disabled', true);
1052                                 notify_info("Subscription reset.");
1053                         } });
1054         }
1055
1056         return false;
1057 }
1058
1059
1060 function unsubscribeFeed(feed_id, title) {
1061
1062         var msg = __("Unsubscribe from %s?").replace("%s", title);
1063
1064         if (title == undefined || confirm(msg)) {
1065                 notify_progress("Removing feed...");
1066
1067                 var query = "?op=pref-feeds&quiet=1&subop=remove&ids=" + feed_id;
1068
1069                 new Ajax.Request("backend.php", {
1070                         parameters: query,
1071                         onComplete: function(transport) {
1072
1073                                         if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1074
1075                                         if (inPreferences()) {
1076                                                 updateFeedList();
1077                                         } else {
1078                                                 if (feed_id == getActiveFeedId())
1079                                                         setTimeout("viewfeed(-5)", 100);
1080                                         }
1081
1082                                 } });
1083         }
1084
1085         return false;
1086 }
1087
1088
1089 function backend_sanity_check_callback(transport) {
1090
1091         try {
1092
1093                 if (sanity_check_done) {
1094                         fatalError(11, "Sanity check request received twice. This can indicate "+
1095                       "presence of Firebug or some other disrupting extension. "+
1096                                 "Please disable it and try again.");
1097                         return;
1098                 }
1099
1100                 var reply = JSON.parse(transport.responseText);
1101
1102                 if (!reply) {
1103                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1104                         return;
1105                 }
1106
1107                 var error_code = reply['error']['code'];
1108
1109                 if (error_code && error_code != 0) {
1110                         return fatalError(error_code, reply['error']['message']);
1111                 }
1112
1113                 console.log("sanity check ok");
1114
1115                 var params = reply['init-params'];
1116
1117                 if (params) {
1118                         console.log('reading init-params...');
1119
1120                         if (params) {
1121                                 for (k in params) {
1122                                         var v = params[k];
1123                                         console.log("IP: " + k + " => " + v);
1124                                 }
1125                         }
1126
1127                         init_params = params;
1128                 }
1129
1130                 sanity_check_done = true;
1131
1132                 init_second_stage();
1133
1134         } catch (e) {
1135                 exception_error("backend_sanity_check_callback", e, transport);
1136         }
1137 }
1138
1139 /*function has_local_storage() {
1140         try {
1141                 return 'sessionStorage' in window && window['sessionStorage'] != null;
1142         } catch (e) {
1143                 return false;
1144         }
1145 } */
1146
1147 function catSelectOnChange(elem) {
1148         try {
1149 /*              var value = elem[elem.selectedIndex].value;
1150                 var def = elem.getAttribute('default');
1151
1152                 if (value == "ADD_CAT") {
1153
1154                         if (def)
1155                                 dropboxSelect(elem, def);
1156                         else
1157                                 elem.selectedIndex = 0;
1158
1159                         quickAddCat(elem);
1160                 } */
1161
1162         } catch (e) {
1163                 exception_error("catSelectOnChange", e);
1164         }
1165 }
1166
1167 function quickAddCat(elem) {
1168         try {
1169                 var cat = prompt(__("Please enter category title:"));
1170
1171                 if (cat) {
1172
1173                         var query = "?op=rpc&subop=quickAddCat&cat=" + param_escape(cat);
1174
1175                         notify_progress("Loading, please wait...", true);
1176
1177                         new Ajax.Request("backend.php", {
1178                                 parameters: query,
1179                                 onComplete: function (transport) {
1180                                         var response = transport.responseXML;
1181                                         var select = response.getElementsByTagName("select")[0];
1182                                         var options = select.getElementsByTagName("option");
1183
1184                                         dropbox_replace_options(elem, options);
1185
1186                                         notify('');
1187
1188                         } });
1189
1190                 }
1191
1192         } catch (e) {
1193                 exception_error("quickAddCat", e);
1194         }
1195 }
1196
1197 function genUrlChangeKey(feed, is_cat) {
1198
1199         try {
1200                 var ok = confirm(__("Generate new syndication address for this feed?"));
1201
1202                 if (ok) {
1203
1204                         notify_progress("Trying to change address...", true);
1205
1206                         var query = "?op=rpc&subop=regenFeedKey&id=" + param_escape(feed) +
1207                                 "&is_cat=" + param_escape(is_cat);
1208
1209                         new Ajax.Request("backend.php", {
1210                                 parameters: query,
1211                                 onComplete: function(transport) {
1212                                                 var reply = JSON.parse(transport.responseText);
1213                                                 var new_link = reply.link;
1214
1215                                                 var e = $('gen_feed_url');
1216
1217                                                 if (new_link) {
1218
1219                                                         e.innerHTML = e.innerHTML.replace(/\&amp;key=.*$/,
1220                                                                 "&amp;key=" + new_link);
1221
1222                                                         e.href = e.href.replace(/\&key=.*$/,
1223                                                                 "&key=" + new_link);
1224
1225                                                         new Effect.Highlight(e);
1226
1227                                                         notify('');
1228
1229                                                 } else {
1230                                                         notify_error("Could not change feed URL.");
1231                                                 }
1232                                 } });
1233                 }
1234         } catch (e) {
1235                 exception_error("genUrlChangeKey", e);
1236         }
1237         return false;
1238 }
1239
1240 function labelSelectOnChange(elem) {
1241         try {
1242 /*              var value = elem[elem.selectedIndex].value;
1243                 var def = elem.getAttribute('default');
1244
1245                 if (value == "ADD_LABEL") {
1246
1247                         if (def)
1248                                 dropboxSelect(elem, def);
1249                         else
1250                                 elem.selectedIndex = 0;
1251
1252                         addLabel(elem, function(transport) {
1253
1254                                         try {
1255
1256                                                 var response = transport.responseXML;
1257                                                 var select = response.getElementsByTagName("select")[0];
1258                                                 var options = select.getElementsByTagName("option");
1259
1260                                                 dropbox_replace_options(elem, options);
1261
1262                                                 notify('');
1263                                         } catch (e) {
1264                                                 exception_error("addLabel", e);
1265                                         }
1266                         });
1267                 } */
1268
1269         } catch (e) {
1270                 exception_error("labelSelectOnChange", e);
1271         }
1272 }
1273
1274 function dropbox_replace_options(elem, options) {
1275
1276         try {
1277                 while (elem.hasChildNodes())
1278                         elem.removeChild(elem.firstChild);
1279
1280                 var sel_idx = -1;
1281
1282                 for (var i = 0; i < options.length; i++) {
1283                         var text = options[i].firstChild.nodeValue;
1284                         var value = options[i].getAttribute("value");
1285
1286                         if (value == undefined) value = text;
1287
1288                         var issel = options[i].getAttribute("selected") == "1";
1289
1290                         var option = new Option(text, value, issel);
1291
1292                         if (options[i].getAttribute("disabled"))
1293                                 option.setAttribute("disabled", true);
1294
1295                         elem.insert(option);
1296
1297                         if (issel) sel_idx = i;
1298                 }
1299
1300                 // Chrome doesn't seem to just select stuff when you pass new Option(x, y, true)
1301                 if (sel_idx >= 0) elem.selectedIndex = sel_idx;
1302
1303         } catch (e) {
1304                 exception_error("dropbox_replace_options", e);
1305         }
1306 }
1307
1308 // mode = all, none, invert
1309 function selectTableRows(id, mode) {
1310         try {
1311                 var rows = $(id).rows;
1312
1313                 for (var i = 0; i < rows.length; i++) {
1314                         var row = rows[i];
1315                         var cb = false;
1316
1317                         if (row.id && row.className) {
1318                                 var bare_id = row.id.replace(/^[A-Z]*?-/, "");
1319                                 var inputs = rows[i].getElementsByTagName("input");
1320
1321                                 for (var j = 0; j < inputs.length; j++) {
1322                                         var input = inputs[j];
1323
1324                                         if (input.getAttribute("type") == "checkbox" &&
1325                                                         input.id.match(bare_id)) {
1326
1327                                                 cb = input;
1328                                                 break;
1329                                         }
1330                                 }
1331
1332                                 if (cb) {
1333                                         var issel = row.hasClassName("Selected");
1334
1335                                         if (mode == "all" && !issel) {
1336                                                 row.addClassName("Selected");
1337                                                 cb.checked = true;
1338                                         } else if (mode == "none" && issel) {
1339                                                 row.removeClassName("Selected");
1340                                                 cb.checked = false;
1341                                         } else if (mode == "invert") {
1342
1343                                                 if (issel) {
1344                                                         row.removeClassName("Selected");
1345                                                         cb.checked = false;
1346                                                 } else {
1347                                                         row.addClassName("Selected");
1348                                                         cb.checked = true;
1349                                                 }
1350                                         }
1351                                 }
1352                         }
1353                 }
1354
1355         } catch (e) {
1356                 exception_error("selectTableRows", e);
1357
1358         }
1359 }
1360
1361 function getSelectedTableRowIds(id) {
1362         var rows = [];
1363
1364         try {
1365                 var elem_rows = $(id).rows;
1366
1367                 for (i = 0; i < elem_rows.length; i++) {
1368                         if (elem_rows[i].hasClassName("Selected")) {
1369                                 var bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1370                                 rows.push(bare_id);
1371                         }
1372                 }
1373
1374         } catch (e) {
1375                 exception_error("getSelectedTableRowIds", e);
1376         }
1377
1378         return rows;
1379 }
1380
1381 function editFeed(feed, event) {
1382         try {
1383                 if (feed <= 0)
1384                         return alert(__("You can't edit this kind of feed."));
1385
1386                 var query = "backend.php?op=pref-feeds&subop=editfeed&id=" +
1387                         param_escape(feed);
1388
1389                 console.log(query);
1390
1391                 if (dijit.byId("feedEditDlg"))
1392                         dijit.byId("feedEditDlg").destroyRecursive();
1393
1394                 dialog = new dijit.Dialog({
1395                         id: "feedEditDlg",
1396                         title: __("Edit Feed"),
1397                         style: "width: 600px",
1398                         execute: function() {
1399                                 if (this.validate()) {
1400 //                                      console.log(dojo.objectToQuery(this.attr('value')));
1401
1402                                         notify_progress("Saving data...", true);
1403
1404                                         new Ajax.Request("backend.php", {
1405                                                 parameters: dojo.objectToQuery(dialog.attr('value')),
1406                                                 onComplete: function(transport) {
1407                                                         dialog.hide();
1408                                                         notify('');
1409                                                         updateFeedList();
1410                                         }})
1411                                 }
1412                         },
1413                         href: query});
1414
1415                 dialog.show();
1416
1417         } catch (e) {
1418                 exception_error("editFeed", e);
1419         }
1420 }
1421
1422 function feedBrowser() {
1423         try {
1424                 var query = "backend.php?op=dlg&id=feedBrowser";
1425
1426                 if (dijit.byId("feedAddDlg"))
1427                         dijit.byId("feedAddDlg").hide();
1428
1429                 if (dijit.byId("feedBrowserDlg"))
1430                         dijit.byId("feedBrowserDlg").destroyRecursive();
1431
1432                 var dialog = new dijit.Dialog({
1433                         id: "feedBrowserDlg",
1434                         title: __("More Feeds"),
1435                         style: "width: 600px",
1436                         getSelectedFeedIds: function() {
1437                                 var list = $$("#browseFeedList li[id*=FBROW]");
1438                                 var selected = new Array();
1439
1440                                 list.each(function(child) {
1441                                         var id = child.id.replace("FBROW-", "");
1442
1443                                         if (child.hasClassName('Selected')) {
1444                                                 selected.push(id);
1445                                         }
1446                                 });
1447
1448                                 return selected;
1449                         },
1450                         getSelectedFeeds: function() {
1451                                 var list = $$("#browseFeedList li.Selected");
1452                                 var selected = new Array();
1453
1454                                 list.each(function(child) {
1455                                         var title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML;
1456                                         var url = child.getElementsBySelector("a.fb_feedUrl")[0].href;
1457
1458                                         selected.push([title,url]);
1459
1460                                 });
1461
1462                                 return selected;
1463                         },
1464
1465                         subscribe: function() {
1466                                 var mode = this.attr('value').mode;
1467                                 var selected = [];
1468
1469                                 if (mode == "1")
1470                                         selected = this.getSelectedFeeds();
1471                                 else
1472                                         selected = this.getSelectedFeedIds();
1473
1474                                 if (selected.length > 0) {
1475                                         dijit.byId("feedBrowserDlg").hide();
1476
1477                                         notify_progress("Loading, please wait...", true);
1478
1479                                         // we use dojo.toJson instead of JSON.stringify because
1480                                         // it somehow escapes everything TWICE, at least in Chrome 9
1481
1482                                         var query = "?op=rpc&subop=massSubscribe&payload="+
1483                                                 param_escape(dojo.toJson(selected)) + "&mode=" + param_escape(mode);
1484
1485                                         console.log(query);
1486
1487                                         new Ajax.Request("backend.php", {
1488                                                 parameters: query,
1489                                                 onComplete: function(transport) {
1490                                                         notify('');
1491                                                         updateFeedList();
1492                                                 } });
1493
1494                                 } else {
1495                                         alert(__("No feeds are selected."));
1496                                 }
1497
1498                         },
1499                         update: function() {
1500                                 var query = dojo.objectToQuery(dialog.attr('value'));
1501
1502                                 Element.show('feed_browser_spinner');
1503
1504                                 new Ajax.Request("backend.php", {
1505                                         parameters: query,
1506                                         onComplete: function(transport) {
1507                                                 notify('');
1508
1509                                                 Element.hide('feed_browser_spinner');
1510
1511                                                 var c = $("browseFeedList");
1512
1513                                                 var reply = JSON.parse(transport.responseText);
1514
1515                                                 var r = reply['content'];
1516                                                 var mode = reply['mode'];
1517
1518                                                 if (c && r) {
1519                                                         c.innerHTML = r;
1520                                                 }
1521
1522                                                 dojo.parser.parse("browseFeedList");
1523
1524                                                 if (mode == 2) {
1525                                                         Element.show(dijit.byId('feed_archive_remove').domNode);
1526                                                 } else {
1527                                                         Element.hide(dijit.byId('feed_archive_remove').domNode);
1528                                                 }
1529
1530                                         } });
1531                         },
1532                         removeFromArchive: function() {
1533                                 var selected = this.getSelectedFeeds();
1534
1535                                 if (selected.length > 0) {
1536
1537                                         var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1538
1539                                         if (confirm(pr)) {
1540                                                 Element.show('feed_browser_spinner');
1541
1542                                                 var query = "?op=rpc&subop=remarchived&ids=" +
1543                                                         param_escape(selected.toString());;
1544
1545                                                 new Ajax.Request("backend.php", {
1546                                                         parameters: query,
1547                                                         onComplete: function(transport) {
1548                                                                 dialog.update();
1549                                                         } });
1550                                         }
1551                                 }
1552                         },
1553                         execute: function() {
1554                                 if (this.validate()) {
1555                                         this.subscribe();
1556                                 }
1557                         },
1558                         href: query});
1559
1560                 dialog.show();
1561
1562         } catch (e) {
1563                 exception_error("editFeed", e);
1564         }
1565 }
1566
1567 function showFeedsWithErrors() {
1568         try {
1569                 var query = "backend.php?op=dlg&id=feedsWithErrors";
1570
1571                 if (dijit.byId("errorFeedsDlg"))
1572                         dijit.byId("errorFeedsDlg").destroyRecursive();
1573
1574                 dialog = new dijit.Dialog({
1575                         id: "errorFeedsDlg",
1576                         title: __("Feeds with update errors"),
1577                         style: "width: 600px",
1578                         getSelectedFeeds: function() {
1579                                 return getSelectedTableRowIds("prefErrorFeedList");
1580                         },
1581                         removeSelected: function() {
1582                                 var sel_rows = this.getSelectedFeeds();
1583
1584                                 console.log(sel_rows);
1585
1586                                 if (sel_rows.length > 0) {
1587                                         var ok = confirm(__("Remove selected feeds?"));
1588
1589                                         if (ok) {
1590                                                 notify_progress("Removing selected feeds...", true);
1591
1592                                                 var query = "?op=pref-feeds&subop=remove&ids="+
1593                                                         param_escape(sel_rows.toString());
1594
1595                                                 new Ajax.Request("backend.php", {
1596                                                         parameters: query,
1597                                                         onComplete: function(transport) {
1598                                                                 notify('');
1599                                                                 dialog.hide();
1600                                                                 updateFeedList();
1601                                                         } });
1602                                         }
1603
1604                                 } else {
1605                                         alert(__("No feeds are selected."));
1606                                 }
1607                         },
1608                         execute: function() {
1609                                 if (this.validate()) {
1610                                 }
1611                         },
1612                         href: query});
1613
1614                 dialog.show();
1615
1616         } catch (e) {
1617                 exception_error("showFeedsWithErrors", e);
1618         }
1619
1620 }
1621
1622 /* new support functions for SelectByTag */
1623
1624 function get_all_tags(selObj){
1625         try {
1626                 if( !selObj ) return "";
1627
1628                 var result = "";
1629                 var len = selObj.options.length;
1630
1631                 for (var i=0; i < len; i++){
1632                         if (selObj.options[i].selected) {
1633                                 result += selObj[i].value + "%2C";   // is really a comma
1634                         }
1635                 }
1636
1637                 if (result.length > 0){
1638                         result = result.substr(0, result.length-3);  // remove trailing %2C
1639                 }
1640
1641                 return(result);
1642
1643         } catch (e) {
1644                 exception_error("get_all_tags", e);
1645         }
1646 }
1647
1648 function get_radio_checked(radioObj) {
1649         try {
1650                 if (!radioObj) return "";
1651
1652                 var len = radioObj.length;
1653
1654                 if (len == undefined){
1655                         if(radioObj.checked){
1656                                 return(radioObj.value);
1657                         } else {
1658                                 return("");
1659                         }
1660                 }
1661
1662                 for( var i=0; i < len; i++ ){
1663                         if( radioObj[i].checked ){
1664                                 return( radioObj[i].value);
1665                         }
1666                 }
1667
1668         } catch (e) {
1669                 exception_error("get_radio_checked", e);
1670         }
1671         return("");
1672 }