]> git.wh0rd.org Git - tt-rss.git/blob - js/functions.js
init params debugging: support objects etc
[tt-rss.git] / js / functions.js
1 var loading_progress = 0;
2 var sanity_check_done = false;
3 var init_params = {};
4 var _label_base_index = -1024;
5 var notify_hide_timerid = false;
6
7 Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
8         function (callOriginal, options) {
9
10                 if (getInitParam("csrf_token") != undefined) {
11                         Object.extend(options, options || { });
12
13                         if (Object.isString(options.parameters))
14                                 options.parameters = options.parameters.toQueryParams();
15                         else if (Object.isHash(options.parameters))
16                                 options.parameters = options.parameters.toObject();
17
18                         options.parameters["csrf_token"] = getInitParam("csrf_token");
19                 }
20
21                 return callOriginal(options);
22         }
23 );
24
25 /* add method to remove element from array */
26
27 Array.prototype.remove = function(s) {
28         for (var i=0; i < this.length; i++) {
29                 if (s == this[i]) this.splice(i, 1);
30         }
31 };
32
33 /* create console.log if it doesn't exist */
34
35 if (!window.console) console = {};
36 console.log = console.log || function(msg) { };
37 console.warn = console.warn || function(msg) { };
38 console.error = console.error || function(msg) { };
39
40 function exception_error(location, e, ext_info) {
41         var msg = format_exception_error(location, e);
42
43         if (!ext_info) ext_info = false;
44
45         try {
46
47                 if (ext_info) {
48                         if (ext_info.responseText) {
49                                 ext_info = ext_info.responseText;
50                         } else {
51                                 ext_info = JSON.stringify(ext_info);
52                         }
53                 }
54
55                 try {
56                         new Ajax.Request("backend.php", {
57                                 parameters: {op: "rpc", method: "log", logmsg: msg},
58                                 onComplete: function (transport) {
59                                         console.log(transport.responseText);
60                                 } });
61
62                 } catch (eii) {
63                         console.log("Exception while trying to log the error.");
64                         console.log(eii);
65                 }
66
67                 msg += "<p>"+ __("The error will be reported to the configured log destination.") +
68                         "</p>";
69
70                 var content = "<div class=\"fatalError\">" +
71                         "<pre>" + msg + "</pre>";
72
73                 content += "<form name=\"exceptionForm\" id=\"exceptionForm\" target=\"_blank\" "+
74                   "action=\"http://tt-rss.org/report.php\" method=\"POST\">";
75
76                 content += "<textarea style=\"display : none\" name=\"message\">" + msg + "</textarea>";
77                 content += "<textarea style=\"display : none\" name=\"params\">N/A</textarea>";
78
79                 if (ext_info) {
80                         content += "<div><b>Additional information:</b></div>" +
81                         "<textarea name=\"xinfo\" readonly=\"1\">" + ext_info + "</textarea>";
82                 }
83
84                 content += "<div><b>Stack trace:</b></div>" +
85                         "<textarea name=\"stack\" readonly=\"1\">" + e.stack + "</textarea>";
86
87                 content += "</form>";
88
89                 content += "</div>";
90
91                 content += "<div class='dlgButtons'>";
92
93                 content += "<button dojoType=\"dijit.form.Button\""+
94                                 "onclick=\"dijit.byId('exceptionDlg').report()\">" +
95                                 __('Report to tt-rss.org') + "</button> ";
96                 content += "<button dojoType=\"dijit.form.Button\" "+
97                                 "onclick=\"dijit.byId('exceptionDlg').hide()\">" +
98                                 __('Close') + "</button>";
99                 content += "</div>";
100
101                 if (dijit.byId("exceptionDlg"))
102                         dijit.byId("exceptionDlg").destroyRecursive();
103
104                 var dialog = new dijit.Dialog({
105                         id: "exceptionDlg",
106                         title: "Unhandled exception",
107                         style: "width: 600px",
108                         report: function() {
109                                 if (confirm(__("Are you sure to report this exception to tt-rss.org? The report will include information about your web browser and tt-rss configuration. Your IP will be saved in the database."))) {
110
111                                         document.forms['exceptionForm'].params.value = $H({
112                                                 browserName: navigator.appName,
113                                                 browserVersion: navigator.appVersion,
114                                                 browserPlatform: navigator.platform,
115                                                 browserCookies: navigator.cookieEnabled,
116                                                 ttrssVersion: __ttrss_version,
117                                                 initParams: JSON.stringify(init_params),
118                                         }).toQueryString();
119
120                                         document.forms['exceptionForm'].submit();
121
122                                 }
123                         },
124                         content: content});
125
126                 dialog.show();
127
128         } catch (ei) {
129                 console.log("Exception while trying to report an exception. Oh boy.");
130                 console.log(ei);
131                 console.log("Original exception:");
132                 console.log(e);
133
134                 msg += "\n\nAdditional exception caught while trying to show the error dialog.\n\n" +  format_exception_error('exception_error', ei);
135
136                 try {
137                         new Ajax.Request("backend.php", {
138                                 parameters: {op: "rpc", method: "log", logmsg: msg},
139                                 onComplete: function (transport) {
140                                         console.log(transport.responseText);
141                                 } });
142
143                 } catch (eii) {
144                         console.log("Third exception while trying to log the error! Seriously?");
145                         console.log(eii);
146                 }
147
148                 msg += "\n\nThe error will be reported to the configured log destination.";
149
150                 alert(msg);
151         }
152
153 }
154
155 function format_exception_error(location, e) {
156         var msg;
157
158         if (e.fileName) {
159                 var base_fname = e.fileName.substring(e.fileName.lastIndexOf("/") + 1);
160
161                 msg = "Exception: " + e.name + ", " + e.message +
162                         "\nFunction: " + location + "()" +
163                         "\nLocation: " + base_fname + ":" + e.lineNumber;
164
165         } else if (e.description) {
166                 msg = "Exception: " + e.description + "\nFunction: " + location + "()";
167         } else {
168                 msg = "Exception: " + e + "\nFunction: " + location + "()";
169         }
170
171         console.error("EXCEPTION: " + msg);
172
173         return msg;
174 }
175
176 function param_escape(arg) {
177         if (typeof encodeURIComponent != 'undefined')
178                 return encodeURIComponent(arg);
179         else
180                 return escape(arg);
181 }
182
183 function param_unescape(arg) {
184         if (typeof decodeURIComponent != 'undefined')
185                 return decodeURIComponent(arg);
186         else
187                 return unescape(arg);
188 }
189
190
191 function hide_notify() {
192         Element.hide('notify');
193 }
194
195 function notify_real(msg, no_hide, n_type) {
196
197         var n = $("notify");
198
199         if (!n) return;
200
201         if (notify_hide_timerid) {
202                 window.clearTimeout(notify_hide_timerid);
203         }
204
205         if (msg == "") {
206                 if (Element.visible(n)) {
207                         notify_hide_timerid = window.setTimeout("hide_notify()", 0);
208                 }
209                 return;
210         } else {
211                 Element.show(n);
212         }
213
214         /* types:
215
216                 1 - generic
217                 2 - progress
218                 3 - error
219                 4 - info
220
221         */
222
223         msg = "<span class=\"msg\"> " + __(msg) + "</span>";
224
225         if (n_type == 1) {
226                 n.className = "notify";
227         } else if (n_type == 2) {
228                 n.className = "notify progress";
229                 msg = "<span><img src='images/indicator_white.gif'></span>" + msg;
230                 no_hide = true;
231         } else if (n_type == 3) {
232                 n.className = "notify error";
233                 msg = "<span><img src='images/alert.png'></span>" + msg;
234         } else if (n_type == 4) {
235                 n.className = "notify info";
236                 msg = "<span><img src='images/information.png'></span>" + msg;
237         }
238
239         msg += " <span><img src=\"images/cross.png\" class=\"close\" title=\"" +
240                 __("Click to close") + "\" onclick=\"notify('')\"></span>";
241
242 //      msg = "<img src='images/live_com_loading.gif'> " + msg;
243
244         n.innerHTML = msg;
245
246         if (!no_hide) {
247                 notify_hide_timerid = window.setTimeout("hide_notify()", 5*1000);
248         }
249 }
250
251 function notify(msg, no_hide) {
252         notify_real(msg, no_hide, 1);
253 }
254
255 function notify_progress(msg, no_hide) {
256         notify_real(msg, no_hide, 2);
257 }
258
259 function notify_error(msg, no_hide) {
260         notify_real(msg, no_hide, 3);
261
262 }
263
264 function notify_info(msg, no_hide) {
265         notify_real(msg, no_hide, 4);
266 }
267
268 function setCookie(name, value, lifetime, path, domain, secure) {
269
270         var d = false;
271
272         if (lifetime) {
273                 d = new Date();
274                 d.setTime(d.getTime() + (lifetime * 1000));
275         }
276
277         console.log("setCookie: " + name + " => " + value + ": " + d);
278
279         int_setCookie(name, value, d, path, domain, secure);
280
281 }
282
283 function int_setCookie(name, value, expires, path, domain, secure) {
284         document.cookie= name + "=" + escape(value) +
285                 ((expires) ? "; expires=" + expires.toGMTString() : "") +
286                 ((path) ? "; path=" + path : "") +
287                 ((domain) ? "; domain=" + domain : "") +
288                 ((secure) ? "; secure" : "");
289 }
290
291 function delCookie(name, path, domain) {
292         if (getCookie(name)) {
293                 document.cookie = name + "=" +
294                 ((path) ? ";path=" + path : "") +
295                 ((domain) ? ";domain=" + domain : "" ) +
296                 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
297         }
298 }
299
300
301 function getCookie(name) {
302
303         var dc = document.cookie;
304         var prefix = name + "=";
305         var begin = dc.indexOf("; " + prefix);
306         if (begin == -1) {
307             begin = dc.indexOf(prefix);
308             if (begin != 0) return null;
309         }
310         else {
311             begin += 2;
312         }
313         var end = document.cookie.indexOf(";", begin);
314         if (end == -1) {
315             end = dc.length;
316         }
317         return unescape(dc.substring(begin + prefix.length, end));
318 }
319
320 function gotoPreferences() {
321         document.location.href = "prefs.php";
322 }
323
324 function gotoLogout() {
325         document.location.href = "backend.php?op=logout";
326 }
327
328 function gotoMain() {
329         document.location.href = "index.php";
330 }
331
332 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
333   * * @author Sundar Dorai-Raj
334   * * Email: sdoraira@vt.edu
335   * * This program is free software; you can redistribute it and/or
336   * * modify it under the terms of the GNU General Public License
337   * * as published by the Free Software Foundation; either version 2
338   * * of the License, or (at your option) any later version,
339   * * provided that any use properly credits the author.
340   * * This program is distributed in the hope that it will be useful,
341   * * but WITHOUT ANY WARRANTY; without even the implied warranty of
342   * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
343   * * GNU General Public License for more details at http://www.gnu.org * * */
344
345   var numbers=".0123456789";
346   function isNumeric(x) {
347     // is x a String or a character?
348     if(x.length>1) {
349       // remove negative sign
350       x=Math.abs(x)+"";
351       for(var j=0;j<x.length;j++) {
352         // call isNumeric recursively for each character
353         number=isNumeric(x.substring(j,j+1));
354         if(!number) return number;
355       }
356       return number;
357     }
358     else {
359       // if x is number return true
360       if(numbers.indexOf(x)>=0) return true;
361       return false;
362     }
363   }
364
365
366 function toggleSelectRowById(sender, id) {
367         var row = $(id);
368         return toggleSelectRow(sender, row);
369 }
370
371 function toggleSelectListRow(sender) {
372         var row = sender.parentNode;
373         return toggleSelectRow(sender, row);
374 }
375
376 /* this is for dijit Checkbox */
377 function toggleSelectListRow2(sender) {
378         var row = sender.domNode.parentNode;
379         return toggleSelectRow(sender, row);
380 }
381
382 /* this is for dijit Checkbox */
383 function toggleSelectRow2(sender, row, is_cdm) {
384
385         if (!row)
386                 if (!is_cdm)
387                         row = sender.domNode.parentNode.parentNode;
388                 else
389                         row = sender.domNode.parentNode.parentNode.parentNode; // oh ffs
390
391         if (sender.checked && !row.hasClassName('Selected'))
392                 row.addClassName('Selected');
393         else
394                 row.removeClassName('Selected');
395
396         if (typeof updateSelectedPrompt != undefined)
397                 updateSelectedPrompt();
398 }
399
400
401 function toggleSelectRow(sender, row) {
402
403         if (!row) row = sender.parentNode.parentNode;
404
405         if (sender.checked && !row.hasClassName('Selected'))
406                 row.addClassName('Selected');
407         else
408                 row.removeClassName('Selected');
409
410         if (typeof updateSelectedPrompt != undefined)
411                 updateSelectedPrompt();
412 }
413
414 function checkboxToggleElement(elem, id) {
415         if (elem.checked) {
416                 Effect.Appear(id, {duration : 0.5});
417         } else {
418                 Effect.Fade(id, {duration : 0.5});
419         }
420 }
421
422 function dropboxSelect(e, v) {
423         for (var i = 0; i < e.length; i++) {
424                 if (e[i].value == v) {
425                         e.selectedIndex = i;
426                         break;
427                 }
428         }
429 }
430
431 function getURLParam(param){
432         return String(window.location.href).parseQuery()[param];
433 }
434
435 function closeInfoBox(cleanup) {
436         try {
437                 dialog = dijit.byId("infoBox");
438
439                 if (dialog)     dialog.hide();
440
441         } catch (e) {
442                 //exception_error("closeInfoBox", e);
443         }
444         return false;
445 }
446
447
448 function displayDlg(title, id, param, callback) {
449
450         notify_progress("Loading, please wait...", true);
451
452         var query = "?op=dlg&method=" +
453                 param_escape(id) + "&param=" + param_escape(param);
454
455         new Ajax.Request("backend.php", {
456                 parameters: query,
457                 onComplete: function (transport) {
458                         infobox_callback2(transport, title);
459                         if (callback) callback(transport);
460                 } });
461
462         return false;
463 }
464
465 function infobox_callback2(transport, title) {
466         try {
467                 var dialog = false;
468
469                 if (dijit.byId("infoBox")) {
470                         dialog = dijit.byId("infoBox");
471                 }
472
473                 //console.log("infobox_callback2");
474                 notify('');
475
476                 var content = transport.responseText;
477
478                 if (!dialog) {
479                         dialog = new dijit.Dialog({
480                                 title: title,
481                                 id: 'infoBox',
482                                 style: "width: 600px",
483                                 onCancel: function() {
484                                         return true;
485                                 },
486                                 onExecute: function() {
487                                         return true;
488                                 },
489                                 onClose: function() {
490                                         return true;
491                                         },
492                                 content: content});
493                 } else {
494                         dialog.attr('title', title);
495                         dialog.attr('content', content);
496                 }
497
498                 dialog.show();
499
500                 notify("");
501         } catch (e) {
502                 exception_error("infobox_callback2", e);
503         }
504 }
505
506 function filterCR(e, f)
507 {
508      var key;
509
510      if(window.event)
511           key = window.event.keyCode;     //IE
512      else
513           key = e.which;     //firefox
514
515         if (key == 13) {
516                 if (typeof f != 'undefined') {
517                         f();
518                         return false;
519                 } else {
520                         return false;
521                 }
522         } else {
523                 return true;
524         }
525 }
526
527 function getInitParam(key) {
528         return init_params[key];
529 }
530
531 function setInitParam(key, value) {
532         init_params[key] = value;
533 }
534
535 function fatalError(code, msg, ext_info) {
536         try {
537
538                 if (code == 6) {
539                         window.location.href = "index.php";
540                 } else if (code == 5) {
541                         window.location.href = "public.php?op=dbupdate";
542                 } else {
543
544                         if (msg == "") msg = "Unknown error";
545
546                         if (ext_info) {
547                                 if (ext_info.responseText) {
548                                         ext_info = ext_info.responseText;
549                                 }
550                         }
551
552                         if (ERRORS && ERRORS[code] && !msg) {
553                                 msg = ERRORS[code];
554                         }
555
556                         var content = "<div><b>Error code:</b> " + code + "</div>" +
557                                 "<p>" + msg + "</p>";
558
559                         if (ext_info) {
560                                 content = content + "<div><b>Additional information:</b></div>" +
561                                         "<textarea style='width: 100%' readonly=\"1\">" +
562                                         ext_info + "</textarea>";
563                         }
564
565                         var dialog = new dijit.Dialog({
566                                 title: "Fatal error",
567                                 style: "width: 600px",
568                                 content: content});
569
570                         dialog.show();
571
572                 }
573
574                 return false;
575
576         } catch (e) {
577                 exception_error("fatalError", e);
578         }
579 }
580
581 function filterDlgCheckAction(sender) {
582
583         try {
584
585                 var action = sender.value;
586
587                 var action_param = $("filterDlg_paramBox");
588
589                 if (!action_param) {
590                         console.log("filterDlgCheckAction: can't find action param box!");
591                         return;
592                 }
593
594                 // if selected action supports parameters, enable params field
595                 if (action == 4 || action == 6 || action == 7) {
596                         new Effect.Appear(action_param, {duration : 0.5});
597                         if (action != 7) {
598                                 Element.show(dijit.byId("filterDlg_actionParam").domNode);
599                                 Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode);
600                         } else {
601                                 Element.show(dijit.byId("filterDlg_actionParamLabel").domNode);
602                                 Element.hide(dijit.byId("filterDlg_actionParam").domNode);
603                         }
604                 } else {
605                         Element.hide(action_param);
606                 }
607
608         } catch (e) {
609                 exception_error("filterDlgCheckAction", e);
610         }
611
612 }
613
614
615 function explainError(code) {
616         return displayDlg(__("Error explained"), "explainError", code);
617 }
618
619 function loading_set_progress(p) {
620         try {
621                 loading_progress += p;
622
623                 if (dijit.byId("loading_bar"))
624                         dijit.byId("loading_bar").update({progress: loading_progress});
625
626                 if (loading_progress >= 90)
627                         remove_splash();
628
629         } catch (e) {
630                 exception_error("loading_set_progress", e);
631         }
632 }
633
634 function remove_splash() {
635
636         if (Element.visible("overlay")) {
637                 console.log("about to remove splash, OMG!");
638                 Element.hide("overlay");
639                 console.log("removed splash!");
640         }
641 }
642
643 function transport_error_check(transport) {
644         try {
645                 if (transport.responseXML) {
646                         var error = transport.responseXML.getElementsByTagName("error")[0];
647
648                         if (error) {
649                                 var code = error.getAttribute("error-code");
650                                 var msg = error.getAttribute("error-msg");
651                                 if (code != 0) {
652                                         fatalError(code, msg);
653                                         return false;
654                                 }
655                         }
656                 }
657         } catch (e) {
658                 exception_error("check_for_error_xml", e);
659         }
660         return true;
661 }
662
663 function strip_tags(s) {
664         return s.replace(/<\/?[^>]+(>|$)/g, "");
665 }
666
667 function truncate_string(s, length) {
668         if (!length) length = 30;
669         var tmp = s.substring(0, length);
670         if (s.length > length) tmp += "&hellip;";
671         return tmp;
672 }
673
674 function hotkey_prefix_timeout() {
675         try {
676
677                 var date = new Date();
678                 var ts = Math.round(date.getTime() / 1000);
679
680                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
681                         console.log("hotkey_prefix seems to be stuck, aborting");
682                         hotkey_prefix_pressed = false;
683                         hotkey_prefix = false;
684                         Element.hide('cmdline');
685                 }
686
687                 setTimeout("hotkey_prefix_timeout()", 1000);
688
689         } catch  (e) {
690                 exception_error("hotkey_prefix_timeout", e);
691         }
692 }
693
694 function uploadIconHandler(rc) {
695         try {
696                 switch (rc) {
697                         case 0:
698                                 notify_info("Upload complete.");
699                                 if (inPreferences()) {
700                                         updateFeedList();
701                                 } else {
702                                         setTimeout('updateFeedList(false, false)', 50);
703                                 }
704                                 break;
705                         case 1:
706                                 notify_error("Upload failed: icon is too big.");
707                                 break;
708                         case 2:
709                                 notify_error("Upload failed.");
710                                 break;
711                 }
712
713         } catch (e) {
714                 exception_error("uploadIconHandler", e);
715         }
716 }
717
718 function removeFeedIcon(id) {
719
720         try {
721
722                 if (confirm(__("Remove stored feed icon?"))) {
723                         var query = "backend.php?op=pref-feeds&method=removeicon&feed_id=" + param_escape(id);
724
725                         console.log(query);
726
727                         notify_progress("Removing feed icon...", true);
728
729                         new Ajax.Request("backend.php", {
730                                 parameters: query,
731                                 onComplete: function(transport) {
732                                         notify_info("Feed icon removed.");
733                                         if (inPreferences()) {
734                                                 updateFeedList();
735                                         } else {
736                                                 setTimeout('updateFeedList(false, false)', 50);
737                                         }
738                                 } });
739                 }
740
741                 return false;
742         } catch (e) {
743                 exception_error("removeFeedIcon", e);
744         }
745 }
746
747 function uploadFeedIcon() {
748
749         try {
750
751                 var file = $("icon_file");
752
753                 if (file.value.length == 0) {
754                         alert(__("Please select an image file to upload."));
755                 } else {
756                         if (confirm(__("Upload new icon for this feed?"))) {
757                                 notify_progress("Uploading, please wait...", true);
758                                 return true;
759                         }
760                 }
761
762                 return false;
763
764         } catch (e) {
765                 exception_error("uploadFeedIcon", e);
766         }
767 }
768
769 function addLabel(select, callback) {
770
771         try {
772
773                 var caption = prompt(__("Please enter label caption:"), "");
774
775                 if (caption != undefined) {
776
777                         if (caption == "") {
778                                 alert(__("Can't create label: missing caption."));
779                                 return false;
780                         }
781
782                         var query = "?op=pref-labels&method=add&caption=" +
783                                 param_escape(caption);
784
785                         if (select)
786                                 query += "&output=select";
787
788                         notify_progress("Loading, please wait...", true);
789
790                         if (inPreferences() && !select) active_tab = "labelConfig";
791
792                         new Ajax.Request("backend.php", {
793                                 parameters: query,
794                                 onComplete: function(transport) {
795                                         if (callback) {
796                                                 callback(transport);
797                                         } else if (inPreferences()) {
798                                                 updateLabelList();
799                                         } else {
800                                                 updateFeedList();
801                                         }
802                         } });
803
804                 }
805
806         } catch (e) {
807                 exception_error("addLabel", e);
808         }
809 }
810
811 function quickAddFeed() {
812         try {
813                 var query = "backend.php?op=feeds&method=quickAddFeed";
814
815                 // overlapping widgets
816                 if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive();
817                 if (dijit.byId("feedAddDlg"))   dijit.byId("feedAddDlg").destroyRecursive();
818
819                 var dialog = new dijit.Dialog({
820                         id: "feedAddDlg",
821                         title: __("Subscribe to Feed"),
822                         style: "width: 600px",
823                         execute: function() {
824                                 if (this.validate()) {
825                                         console.log(dojo.objectToQuery(this.attr('value')));
826
827                                         var feed_url = this.attr('value').feed;
828
829                                         Element.show("feed_add_spinner");
830
831                                         new Ajax.Request("backend.php", {
832                                                 parameters: dojo.objectToQuery(this.attr('value')),
833                                                 onComplete: function(transport) {
834                                                         try {
835
836                                                                 try {
837                                                                         var reply = JSON.parse(transport.responseText);
838                                                                 } catch (e) {
839                                                                         Element.hide("feed_add_spinner");
840                                                                         alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console."));
841                                                                         console.log('quickAddFeed, backend returned:' + transport.responseText);
842                                                                         return;
843                                                                 }
844
845                                                                 var rc = reply['result'];
846
847                                                                 notify('');
848                                                                 Element.hide("feed_add_spinner");
849
850                                                                 console.log(rc);
851
852                                                                 switch (parseInt(rc['code'])) {
853                                                                 case 1:
854                                                                         dialog.hide();
855                                                                         notify_info(__("Subscribed to %s").replace("%s", feed_url));
856
857                                                                         updateFeedList();
858                                                                         break;
859                                                                 case 2:
860                                                                         alert(__("Specified URL seems to be invalid."));
861                                                                         break;
862                                                                 case 3:
863                                                                         alert(__("Specified URL doesn't seem to contain any feeds."));
864                                                                         break;
865                                                                 case 4:
866                                                                         feeds = rc['feeds'];
867
868                                                                         Element.show("fadd_multiple_notify");
869
870                                                                         var select = dijit.byId("feedDlg_feedContainerSelect");
871
872                                                                         while (select.getOptions().length > 0)
873                                                                                 select.removeOption(0);
874
875                                                                         select.addOption({value: '', label: __("Expand to select feed")});
876
877                                                                         var count = 0;
878                                                                         for (var feedUrl in feeds) {
879                                                                                 select.addOption({value: feedUrl, label: feeds[feedUrl]});
880                                                                                 count++;
881                                                                         }
882
883                                                                         Effect.Appear('feedDlg_feedsContainer', {duration : 0.5});
884
885                                                                         break;
886                                                                 case 5:
887                                                                         alert(__("Couldn't download the specified URL: %s").
888                                                                                         replace("%s", rc['message']));
889                                                                         break;
890                                                                 case 6:
891                                                                         alert(__("XML validation failed: %s").
892                                                                                         replace("%s", rc['message']));
893                                                                         break;
894                                                                         break;
895                                                                 case 0:
896                                                                         alert(__("You are already subscribed to this feed."));
897                                                                         break;
898                                                                 }
899
900                                                         } catch (e) {
901                                                                 exception_error("subscribeToFeed", e, transport);
902                                                         }
903
904                                                 } });
905
906                                         }
907                         },
908                         href: query});
909
910                 dialog.show();
911         } catch (e) {
912                 exception_error("quickAddFeed", e);
913         }
914 }
915
916 function createNewRuleElement(parentNode, replaceNode) {
917         try {
918                 var form = document.forms["filter_new_rule_form"];
919
920                 form.reg_exp.value = form.reg_exp.value.replace(/(<([^>]+)>)/ig,"");
921
922                 var query = "backend.php?op=pref-filters&method=printrulename&rule="+
923                         param_escape(dojo.formToJson(form));
924
925                 console.log(query);
926
927                 new Ajax.Request("backend.php", {
928                         parameters: query,
929                         onComplete: function (transport) {
930                                 try {
931                                         var li = dojo.create("li");
932
933                                         var cb = dojo.create("input", { type: "checkbox" }, li);
934
935                                         new dijit.form.CheckBox({
936                                                 onChange: function() {
937                                                         toggleSelectListRow2(this) },
938                                         }, cb);
939
940                                         dojo.create("input", { type: "hidden",
941                                                 name: "rule[]",
942                                                 value: dojo.formToJson(form) }, li);
943
944                                         dojo.create("span", {
945                                                 onclick: function() {
946                                                         dijit.byId('filterEditDlg').editRule(this);
947                                                 },
948                                                 innerHTML: transport.responseText }, li);
949
950                                         if (replaceNode) {
951                                                 parentNode.replaceChild(li, replaceNode);
952                                         } else {
953                                                 parentNode.appendChild(li);
954                                         }
955                                 } catch (e) {
956                                         exception_error("createNewRuleElement", e);
957                                 }
958                 } });
959         } catch (e) {
960                 exception_error("createNewRuleElement", e);
961         }
962 }
963
964 function createNewActionElement(parentNode, replaceNode) {
965         try {
966                 var form = document.forms["filter_new_action_form"];
967
968                 if (form.action_id.value == 7) {
969                         form.action_param.value = form.action_param_label.value;
970                 }
971
972                 var query = "backend.php?op=pref-filters&method=printactionname&action="+
973                         param_escape(dojo.formToJson(form));
974
975                 console.log(query);
976
977                 new Ajax.Request("backend.php", {
978                         parameters: query,
979                         onComplete: function (transport) {
980                                 try {
981                                         var li = dojo.create("li");
982
983                                         var cb = dojo.create("input", { type: "checkbox" }, li);
984
985                                         new dijit.form.CheckBox({
986                                                 onChange: function() {
987                                                         toggleSelectListRow2(this) },
988                                         }, cb);
989
990                                         dojo.create("input", { type: "hidden",
991                                                 name: "action[]",
992                                                 value: dojo.formToJson(form) }, li);
993
994                                         dojo.create("span", {
995                                                 onclick: function() {
996                                                         dijit.byId('filterEditDlg').editAction(this);
997                                                 },
998                                                 innerHTML: transport.responseText }, li);
999
1000                                         if (replaceNode) {
1001                                                 parentNode.replaceChild(li, replaceNode);
1002                                         } else {
1003                                                 parentNode.appendChild(li);
1004                                         }
1005
1006                                 } catch (e) {
1007                                         exception_error("createNewActionElement", e);
1008                                 }
1009                         } });
1010         } catch (e) {
1011                 exception_error("createNewActionElement", e);
1012         }
1013 }
1014
1015
1016 function addFilterRule(replaceNode, ruleStr) {
1017         try {
1018                 if (dijit.byId("filterNewRuleDlg"))
1019                         dijit.byId("filterNewRuleDlg").destroyRecursive();
1020
1021                 var query = "backend.php?op=pref-filters&method=newrule&rule=" +
1022                         param_escape(ruleStr);
1023
1024                 var rule_dlg = new dijit.Dialog({
1025                         id: "filterNewRuleDlg",
1026                         title: ruleStr ? __("Edit rule") : __("Add rule"),
1027                         style: "width: 600px",
1028                         execute: function() {
1029                                 if (this.validate()) {
1030                                         createNewRuleElement($("filterDlg_Matches"), replaceNode);
1031                                         this.hide();
1032                                 }
1033                         },
1034                         href: query});
1035
1036                 rule_dlg.show();
1037         } catch (e) {
1038                 exception_error("addFilterRule", e);
1039         }
1040 }
1041
1042 function addFilterAction(replaceNode, actionStr) {
1043         try {
1044                 if (dijit.byId("filterNewActionDlg"))
1045                         dijit.byId("filterNewActionDlg").destroyRecursive();
1046
1047                 var query = "backend.php?op=pref-filters&method=newaction&action=" +
1048                         param_escape(actionStr);
1049
1050                 var rule_dlg = new dijit.Dialog({
1051                         id: "filterNewActionDlg",
1052                         title: actionStr ? __("Edit action") : __("Add action"),
1053                         style: "width: 600px",
1054                         execute: function() {
1055                                 if (this.validate()) {
1056                                         createNewActionElement($("filterDlg_Actions"), replaceNode);
1057                                         this.hide();
1058                                 }
1059                         },
1060                         href: query});
1061
1062                 rule_dlg.show();
1063         } catch (e) {
1064                 exception_error("addFilterAction", e);
1065         }
1066 }
1067
1068 function quickAddFilter() {
1069         try {
1070                 var query = "";
1071                 if (!inPreferences()) {
1072                         query = "backend.php?op=pref-filters&method=newfilter&feed=" +
1073                                 param_escape(getActiveFeedId()) + "&is_cat=" +
1074                                 param_escape(activeFeedIsCat());
1075                 } else {
1076                         query = "backend.php?op=pref-filters&method=newfilter";
1077                 }
1078
1079                 console.log(query);
1080
1081                 if (dijit.byId("feedEditDlg"))
1082                         dijit.byId("feedEditDlg").destroyRecursive();
1083
1084                 if (dijit.byId("filterEditDlg"))
1085                         dijit.byId("filterEditDlg").destroyRecursive();
1086
1087                 dialog = new dijit.Dialog({
1088                         id: "filterEditDlg",
1089                         title: __("Create Filter"),
1090                         style: "width: 600px",
1091                         test: function() {
1092                                 var query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test";
1093
1094                                 if (dijit.byId("filterTestDlg"))
1095                                         dijit.byId("filterTestDlg").destroyRecursive();
1096
1097                                 var test_dlg = new dijit.Dialog({
1098                                         id: "filterTestDlg",
1099                                         title: "Test Filter",
1100                                         style: "width: 600px",
1101                                         href: query});
1102
1103                                 test_dlg.show();
1104                         },
1105                         selectRules: function(select) {
1106                                 $$("#filterDlg_Matches input[type=checkbox]").each(function(e) {
1107                                         e.checked = select;
1108                                         if (select)
1109                                                 e.parentNode.addClassName("Selected");
1110                                         else
1111                                                 e.parentNode.removeClassName("Selected");
1112                                 });
1113                         },
1114                         selectActions: function(select) {
1115                                 $$("#filterDlg_Actions input[type=checkbox]").each(function(e) {
1116                                         e.checked = select;
1117
1118                                         if (select)
1119                                                 e.parentNode.addClassName("Selected");
1120                                         else
1121                                                 e.parentNode.removeClassName("Selected");
1122
1123                                 });
1124                         },
1125                         editRule: function(e) {
1126                                 var li = e.parentNode;
1127                                 var rule = li.getElementsByTagName("INPUT")[1].value;
1128                                 addFilterRule(li, rule);
1129                         },
1130                         editAction: function(e) {
1131                                 var li = e.parentNode;
1132                                 var action = li.getElementsByTagName("INPUT")[1].value;
1133                                 addFilterAction(li, action);
1134                         },
1135                         addAction: function() { addFilterAction(); },
1136                         addRule: function() { addFilterRule(); },
1137                         deleteAction: function() {
1138                                 $$("#filterDlg_Actions li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1139                         },
1140                         deleteRule: function() {
1141                                 $$("#filterDlg_Matches li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1142                         },
1143                         execute: function() {
1144                                 if (this.validate()) {
1145
1146                                         var query = dojo.formToQuery("filter_new_form");
1147
1148                                         console.log(query);
1149
1150                                         new Ajax.Request("backend.php", {
1151                                                 parameters: query,
1152                                                 onComplete: function (transport) {
1153                                                         if (inPreferences()) {
1154                                                                 updateFilterList();
1155                                                         }
1156
1157                                                         dialog.hide();
1158                                         } });
1159                                 }
1160                         },
1161                         href: query});
1162
1163                 if (!inPreferences()) {
1164                         var selectedText = getSelectionText();
1165
1166                         var lh = dojo.connect(dialog, "onLoad", function(){
1167                                 dojo.disconnect(lh);
1168
1169                                 if (selectedText != "") {
1170
1171                                         var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1172                                                 getActiveFeedId();
1173
1174                                         var rule = { reg_exp: selectedText, feed_id: feed_id, filter_type: 1 };
1175
1176                                         addFilterRule(null, dojo.toJson(rule));
1177
1178                                 } else {
1179
1180                                         var query = "op=rpc&method=getlinktitlebyid&id=" + getActiveArticleId();
1181
1182                                         new Ajax.Request("backend.php", {
1183                                         parameters: query,
1184                                         onComplete: function(transport) {
1185                                                 var reply = JSON.parse(transport.responseText);
1186
1187                                                 var title = false;
1188
1189                                                 if (reply && reply) title = reply.title;
1190
1191                                                 if (title || getActiveFeedId() || activeFeedIsCat()) {
1192
1193                                                         console.log(title + " " + getActiveFeedId());
1194
1195                                                         var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1196                                                                 getActiveFeedId();
1197
1198                                                         var rule = { reg_exp: title, feed_id: feed_id, filter_type: 1 };
1199
1200                                                         addFilterRule(null, dojo.toJson(rule));
1201                                                 }
1202
1203                                         } });
1204
1205                                 }
1206
1207                         });
1208                 }
1209
1210                 dialog.show();
1211
1212         } catch (e) {
1213                 exception_error("quickAddFilter", e);
1214         }
1215 }
1216
1217 function resetPubSub(feed_id, title) {
1218
1219         var msg = __("Reset subscription? Tiny Tiny RSS will try to subscribe to the notification hub again on next feed update.").replace("%s", title);
1220
1221         if (title == undefined || confirm(msg)) {
1222                 notify_progress("Loading, please wait...");
1223
1224                 var query = "?op=pref-feeds&quiet=1&method=resetPubSub&ids=" + feed_id;
1225
1226                 new Ajax.Request("backend.php", {
1227                         parameters: query,
1228                         onComplete: function(transport) {
1229                                 dijit.byId("pubsubReset_Btn").attr('disabled', true);
1230                                 notify_info("Subscription reset.");
1231                         } });
1232         }
1233
1234         return false;
1235 }
1236
1237
1238 function unsubscribeFeed(feed_id, title) {
1239
1240         var msg = __("Unsubscribe from %s?").replace("%s", title);
1241
1242         if (title == undefined || confirm(msg)) {
1243                 notify_progress("Removing feed...");
1244
1245                 var query = "?op=pref-feeds&quiet=1&method=remove&ids=" + feed_id;
1246
1247                 new Ajax.Request("backend.php", {
1248                         parameters: query,
1249                         onComplete: function(transport) {
1250
1251                                         if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1252
1253                                         if (inPreferences()) {
1254                                                 updateFeedList();
1255                                         } else {
1256                                                 if (feed_id == getActiveFeedId())
1257                                                         setTimeout("viewfeed(-5)", 100);
1258
1259                                                 if (feed_id < 0) updateFeedList();
1260                                         }
1261
1262                                 } });
1263         }
1264
1265         return false;
1266 }
1267
1268
1269 function backend_sanity_check_callback(transport) {
1270
1271         try {
1272
1273                 if (sanity_check_done) {
1274                         fatalError(11, "Sanity check request received twice. This can indicate "+
1275                       "presence of Firebug or some other disrupting extension. "+
1276                                 "Please disable it and try again.");
1277                         return;
1278                 }
1279
1280                 var reply = JSON.parse(transport.responseText);
1281
1282                 if (!reply) {
1283                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1284                         return;
1285                 }
1286
1287                 var error_code = reply['error']['code'];
1288
1289                 if (error_code && error_code != 0) {
1290                         return fatalError(error_code, reply['error']['message']);
1291                 }
1292
1293                 console.log("sanity check ok");
1294
1295                 var params = reply['init-params'];
1296
1297                 if (params) {
1298                         console.log('reading init-params...');
1299
1300                         for (k in params) {
1301                                 console.log("IP: " + k + " => " + JSON.stringify(params[k]));
1302                                 if (k == "label_base_index") _label_base_index = parseInt(params[k]);
1303                         }
1304
1305                         init_params = params;
1306
1307                         // PluginHost might not be available on non-index pages
1308                         window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params);
1309                 }
1310
1311                 sanity_check_done = true;
1312
1313                 init_second_stage();
1314
1315         } catch (e) {
1316                 exception_error("backend_sanity_check_callback", e, transport);
1317         }
1318 }
1319
1320 /*function has_local_storage() {
1321         try {
1322                 return 'sessionStorage' in window && window['sessionStorage'] != null;
1323         } catch (e) {
1324                 return false;
1325         }
1326 } */
1327
1328 function catSelectOnChange(elem) {
1329         try {
1330 /*              var value = elem[elem.selectedIndex].value;
1331                 var def = elem.getAttribute('default');
1332
1333                 if (value == "ADD_CAT") {
1334
1335                         if (def)
1336                                 dropboxSelect(elem, def);
1337                         else
1338                                 elem.selectedIndex = 0;
1339
1340                         quickAddCat(elem);
1341                 } */
1342
1343         } catch (e) {
1344                 exception_error("catSelectOnChange", e);
1345         }
1346 }
1347
1348 function quickAddCat(elem) {
1349         try {
1350                 var cat = prompt(__("Please enter category title:"));
1351
1352                 if (cat) {
1353
1354                         var query = "?op=rpc&method=quickAddCat&cat=" + param_escape(cat);
1355
1356                         notify_progress("Loading, please wait...", true);
1357
1358                         new Ajax.Request("backend.php", {
1359                                 parameters: query,
1360                                 onComplete: function (transport) {
1361                                         var response = transport.responseXML;
1362                                         var select = response.getElementsByTagName("select")[0];
1363                                         var options = select.getElementsByTagName("option");
1364
1365                                         dropbox_replace_options(elem, options);
1366
1367                                         notify('');
1368
1369                         } });
1370
1371                 }
1372
1373         } catch (e) {
1374                 exception_error("quickAddCat", e);
1375         }
1376 }
1377
1378 function genUrlChangeKey(feed, is_cat) {
1379
1380         try {
1381                 var ok = confirm(__("Generate new syndication address for this feed?"));
1382
1383                 if (ok) {
1384
1385                         notify_progress("Trying to change address...", true);
1386
1387                         var query = "?op=pref-feeds&method=regenFeedKey&id=" + param_escape(feed) +
1388                                 "&is_cat=" + param_escape(is_cat);
1389
1390                         new Ajax.Request("backend.php", {
1391                                 parameters: query,
1392                                 onComplete: function(transport) {
1393                                                 var reply = JSON.parse(transport.responseText);
1394                                                 var new_link = reply.link;
1395
1396                                                 var e = $('gen_feed_url');
1397
1398                                                 if (new_link) {
1399
1400                                                         e.innerHTML = e.innerHTML.replace(/\&amp;key=.*$/,
1401                                                                 "&amp;key=" + new_link);
1402
1403                                                         e.href = e.href.replace(/\&key=.*$/,
1404                                                                 "&key=" + new_link);
1405
1406                                                         new Effect.Highlight(e);
1407
1408                                                         notify('');
1409
1410                                                 } else {
1411                                                         notify_error("Could not change feed URL.");
1412                                                 }
1413                                 } });
1414                 }
1415         } catch (e) {
1416                 exception_error("genUrlChangeKey", e);
1417         }
1418         return false;
1419 }
1420
1421 function labelSelectOnChange(elem) {
1422         try {
1423 /*              var value = elem[elem.selectedIndex].value;
1424                 var def = elem.getAttribute('default');
1425
1426                 if (value == "ADD_LABEL") {
1427
1428                         if (def)
1429                                 dropboxSelect(elem, def);
1430                         else
1431                                 elem.selectedIndex = 0;
1432
1433                         addLabel(elem, function(transport) {
1434
1435                                         try {
1436
1437                                                 var response = transport.responseXML;
1438                                                 var select = response.getElementsByTagName("select")[0];
1439                                                 var options = select.getElementsByTagName("option");
1440
1441                                                 dropbox_replace_options(elem, options);
1442
1443                                                 notify('');
1444                                         } catch (e) {
1445                                                 exception_error("addLabel", e);
1446                                         }
1447                         });
1448                 } */
1449
1450         } catch (e) {
1451                 exception_error("labelSelectOnChange", e);
1452         }
1453 }
1454
1455 function dropbox_replace_options(elem, options) {
1456
1457         try {
1458                 while (elem.hasChildNodes())
1459                         elem.removeChild(elem.firstChild);
1460
1461                 var sel_idx = -1;
1462
1463                 for (var i = 0; i < options.length; i++) {
1464                         var text = options[i].firstChild.nodeValue;
1465                         var value = options[i].getAttribute("value");
1466
1467                         if (value == undefined) value = text;
1468
1469                         var issel = options[i].getAttribute("selected") == "1";
1470
1471                         var option = new Option(text, value, issel);
1472
1473                         if (options[i].getAttribute("disabled"))
1474                                 option.setAttribute("disabled", true);
1475
1476                         elem.insert(option);
1477
1478                         if (issel) sel_idx = i;
1479                 }
1480
1481                 // Chrome doesn't seem to just select stuff when you pass new Option(x, y, true)
1482                 if (sel_idx >= 0) elem.selectedIndex = sel_idx;
1483
1484         } catch (e) {
1485                 exception_error("dropbox_replace_options", e);
1486         }
1487 }
1488
1489 // mode = all, none, invert
1490 function selectTableRows(id, mode) {
1491         try {
1492                 var rows = $(id).rows;
1493
1494                 for (var i = 0; i < rows.length; i++) {
1495                         var row = rows[i];
1496                         var cb = false;
1497                         var dcb = false;
1498
1499                         if (row.id && row.className) {
1500                                 var bare_id = row.id.replace(/^[A-Z]*?-/, "");
1501                                 var inputs = rows[i].getElementsByTagName("input");
1502
1503                                 for (var j = 0; j < inputs.length; j++) {
1504                                         var input = inputs[j];
1505
1506                                         if (input.getAttribute("type") == "checkbox" &&
1507                                                         input.id.match(bare_id)) {
1508
1509                                                 cb = input;
1510                                                 dcb = dijit.getEnclosingWidget(cb);
1511                                                 break;
1512                                         }
1513                                 }
1514
1515                                 if (cb || dcb) {
1516                                         var issel = row.hasClassName("Selected");
1517
1518                                         if (mode == "all" && !issel) {
1519                                                 row.addClassName("Selected");
1520                                                 cb.checked = true;
1521                                                 if (dcb) dcb.set("checked", true);
1522                                         } else if (mode == "none" && issel) {
1523                                                 row.removeClassName("Selected");
1524                                                 cb.checked = false;
1525                                                 if (dcb) dcb.set("checked", false);
1526
1527                                         } else if (mode == "invert") {
1528
1529                                                 if (issel) {
1530                                                         row.removeClassName("Selected");
1531                                                         cb.checked = false;
1532                                                         if (dcb) dcb.set("checked", false);
1533                                                 } else {
1534                                                         row.addClassName("Selected");
1535                                                         cb.checked = true;
1536                                                         if (dcb) dcb.set("checked", true);
1537                                                 }
1538                                         }
1539                                 }
1540                         }
1541                 }
1542
1543         } catch (e) {
1544                 exception_error("selectTableRows", e);
1545
1546         }
1547 }
1548
1549 function getSelectedTableRowIds(id) {
1550         var rows = [];
1551
1552         try {
1553                 var elem_rows = $(id).rows;
1554
1555                 for (var i = 0; i < elem_rows.length; i++) {
1556                         if (elem_rows[i].hasClassName("Selected")) {
1557                                 var bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1558                                 rows.push(bare_id);
1559                         }
1560                 }
1561
1562         } catch (e) {
1563                 exception_error("getSelectedTableRowIds", e);
1564         }
1565
1566         return rows;
1567 }
1568
1569 function editFeed(feed, event) {
1570         try {
1571                 if (feed <= 0)
1572                         return alert(__("You can't edit this kind of feed."));
1573
1574                 var query = "backend.php?op=pref-feeds&method=editfeed&id=" +
1575                         param_escape(feed);
1576
1577                 console.log(query);
1578
1579                 if (dijit.byId("filterEditDlg"))
1580                         dijit.byId("filterEditDlg").destroyRecursive();
1581
1582                 if (dijit.byId("feedEditDlg"))
1583                         dijit.byId("feedEditDlg").destroyRecursive();
1584
1585                 dialog = new dijit.Dialog({
1586                         id: "feedEditDlg",
1587                         title: __("Edit Feed"),
1588                         style: "width: 600px",
1589                         execute: function() {
1590                                 if (this.validate()) {
1591 //                                      console.log(dojo.objectToQuery(this.attr('value')));
1592
1593                                         notify_progress("Saving data...", true);
1594
1595                                         new Ajax.Request("backend.php", {
1596                                                 parameters: dojo.objectToQuery(dialog.attr('value')),
1597                                                 onComplete: function(transport) {
1598                                                         dialog.hide();
1599                                                         notify('');
1600                                                         updateFeedList();
1601                                         }});
1602                                 }
1603                         },
1604                         href: query});
1605
1606                 dialog.show();
1607
1608         } catch (e) {
1609                 exception_error("editFeed", e);
1610         }
1611 }
1612
1613 function feedBrowser() {
1614         try {
1615                 var query = "backend.php?op=feeds&method=feedBrowser";
1616
1617                 if (dijit.byId("feedAddDlg"))
1618                         dijit.byId("feedAddDlg").hide();
1619
1620                 if (dijit.byId("feedBrowserDlg"))
1621                         dijit.byId("feedBrowserDlg").destroyRecursive();
1622
1623                 var dialog = new dijit.Dialog({
1624                         id: "feedBrowserDlg",
1625                         title: __("More Feeds"),
1626                         style: "width: 600px",
1627                         getSelectedFeedIds: function() {
1628                                 var list = $$("#browseFeedList li[id*=FBROW]");
1629                                 var selected = new Array();
1630
1631                                 list.each(function(child) {
1632                                         var id = child.id.replace("FBROW-", "");
1633
1634                                         if (child.hasClassName('Selected')) {
1635                                                 selected.push(id);
1636                                         }
1637                                 });
1638
1639                                 return selected;
1640                         },
1641                         getSelectedFeeds: function() {
1642                                 var list = $$("#browseFeedList li.Selected");
1643                                 var selected = new Array();
1644
1645                                 list.each(function(child) {
1646                                         var title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML;
1647                                         var url = child.getElementsBySelector("a.fb_feedUrl")[0].href;
1648
1649                                         selected.push([title,url]);
1650
1651                                 });
1652
1653                                 return selected;
1654                         },
1655
1656                         subscribe: function() {
1657                                 var mode = this.attr('value').mode;
1658                                 var selected = [];
1659
1660                                 if (mode == "1")
1661                                         selected = this.getSelectedFeeds();
1662                                 else
1663                                         selected = this.getSelectedFeedIds();
1664
1665                                 if (selected.length > 0) {
1666                                         dijit.byId("feedBrowserDlg").hide();
1667
1668                                         notify_progress("Loading, please wait...", true);
1669
1670                                         // we use dojo.toJson instead of JSON.stringify because
1671                                         // it somehow escapes everything TWICE, at least in Chrome 9
1672
1673                                         var query = "?op=rpc&method=massSubscribe&payload="+
1674                                                 param_escape(dojo.toJson(selected)) + "&mode=" + param_escape(mode);
1675
1676                                         console.log(query);
1677
1678                                         new Ajax.Request("backend.php", {
1679                                                 parameters: query,
1680                                                 onComplete: function(transport) {
1681                                                         notify('');
1682                                                         updateFeedList();
1683                                                 } });
1684
1685                                 } else {
1686                                         alert(__("No feeds are selected."));
1687                                 }
1688
1689                         },
1690                         update: function() {
1691                                 var query = dojo.objectToQuery(dialog.attr('value'));
1692
1693                                 Element.show('feed_browser_spinner');
1694
1695                                 new Ajax.Request("backend.php", {
1696                                         parameters: query,
1697                                         onComplete: function(transport) {
1698                                                 notify('');
1699
1700                                                 Element.hide('feed_browser_spinner');
1701
1702                                                 var c = $("browseFeedList");
1703
1704                                                 var reply = JSON.parse(transport.responseText);
1705
1706                                                 var r = reply['content'];
1707                                                 var mode = reply['mode'];
1708
1709                                                 if (c && r) {
1710                                                         c.innerHTML = r;
1711                                                 }
1712
1713                                                 dojo.parser.parse("browseFeedList");
1714
1715                                                 if (mode == 2) {
1716                                                         Element.show(dijit.byId('feed_archive_remove').domNode);
1717                                                 } else {
1718                                                         Element.hide(dijit.byId('feed_archive_remove').domNode);
1719                                                 }
1720
1721                                         } });
1722                         },
1723                         removeFromArchive: function() {
1724                                 var selected = this.getSelectedFeedIds();
1725
1726                                 if (selected.length > 0) {
1727
1728                                         var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1729
1730                                         if (confirm(pr)) {
1731                                                 Element.show('feed_browser_spinner');
1732
1733                                                 var query = "?op=rpc&method=remarchive&ids=" +
1734                                                         param_escape(selected.toString());;
1735
1736                                                 new Ajax.Request("backend.php", {
1737                                                         parameters: query,
1738                                                         onComplete: function(transport) {
1739                                                                 dialog.update();
1740                                                         } });
1741                                         }
1742                                 }
1743                         },
1744                         execute: function() {
1745                                 if (this.validate()) {
1746                                         this.subscribe();
1747                                 }
1748                         },
1749                         href: query});
1750
1751                 dialog.show();
1752
1753         } catch (e) {
1754                 exception_error("editFeed", e);
1755         }
1756 }
1757
1758 function showFeedsWithErrors() {
1759         try {
1760                 var query = "backend.php?op=pref-feeds&method=feedsWithErrors";
1761
1762                 if (dijit.byId("errorFeedsDlg"))
1763                         dijit.byId("errorFeedsDlg").destroyRecursive();
1764
1765                 dialog = new dijit.Dialog({
1766                         id: "errorFeedsDlg",
1767                         title: __("Feeds with update errors"),
1768                         style: "width: 600px",
1769                         getSelectedFeeds: function() {
1770                                 return getSelectedTableRowIds("prefErrorFeedList");
1771                         },
1772                         removeSelected: function() {
1773                                 var sel_rows = this.getSelectedFeeds();
1774
1775                                 console.log(sel_rows);
1776
1777                                 if (sel_rows.length > 0) {
1778                                         var ok = confirm(__("Remove selected feeds?"));
1779
1780                                         if (ok) {
1781                                                 notify_progress("Removing selected feeds...", true);
1782
1783                                                 var query = "?op=pref-feeds&method=remove&ids="+
1784                                                         param_escape(sel_rows.toString());
1785
1786                                                 new Ajax.Request("backend.php", {
1787                                                         parameters: query,
1788                                                         onComplete: function(transport) {
1789                                                                 notify('');
1790                                                                 dialog.hide();
1791                                                                 updateFeedList();
1792                                                         } });
1793                                         }
1794
1795                                 } else {
1796                                         alert(__("No feeds are selected."));
1797                                 }
1798                         },
1799                         execute: function() {
1800                                 if (this.validate()) {
1801                                 }
1802                         },
1803                         href: query});
1804
1805                 dialog.show();
1806
1807         } catch (e) {
1808                 exception_error("showFeedsWithErrors", e);
1809         }
1810
1811 }
1812
1813 /* new support functions for SelectByTag */
1814
1815 function get_all_tags(selObj){
1816         try {
1817                 if( !selObj ) return "";
1818
1819                 var result = "";
1820                 var len = selObj.options.length;
1821
1822                 for (var i=0; i < len; i++){
1823                         if (selObj.options[i].selected) {
1824                                 result += selObj[i].value + "%2C";   // is really a comma
1825                         }
1826                 }
1827
1828                 if (result.length > 0){
1829                         result = result.substr(0, result.length-3);  // remove trailing %2C
1830                 }
1831
1832                 return(result);
1833
1834         } catch (e) {
1835                 exception_error("get_all_tags", e);
1836         }
1837 }
1838
1839 function get_radio_checked(radioObj) {
1840         try {
1841                 if (!radioObj) return "";
1842
1843                 var len = radioObj.length;
1844
1845                 if (len == undefined){
1846                         if(radioObj.checked){
1847                                 return(radioObj.value);
1848                         } else {
1849                                 return("");
1850                         }
1851                 }
1852
1853                 for( var i=0; i < len; i++ ){
1854                         if( radioObj[i].checked ){
1855                                 return( radioObj[i].value);
1856                         }
1857                 }
1858
1859         } catch (e) {
1860                 exception_error("get_radio_checked", e);
1861         }
1862         return("");
1863 }
1864
1865 function get_timestamp() {
1866         var date = new Date();
1867         return Math.round(date.getTime() / 1000);
1868 }
1869
1870 function helpDialog(topic) {
1871         try {
1872                 var query = "backend.php?op=backend&method=help&topic=" + param_escape(topic);
1873
1874                 if (dijit.byId("helpDlg"))
1875                         dijit.byId("helpDlg").destroyRecursive();
1876
1877                 dialog = new dijit.Dialog({
1878                         id: "helpDlg",
1879                         title: __("Help"),
1880                         style: "width: 600px",
1881                         href: query,
1882                 });
1883
1884                 dialog.show();
1885
1886         } catch (e) {
1887                 exception_error("helpDialog", e);
1888         }
1889 }
1890
1891 function htmlspecialchars_decode (string, quote_style) {
1892   // http://kevin.vanzonneveld.net
1893   // +   original by: Mirek Slugen
1894   // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1895   // +   bugfixed by: Mateusz "loonquawl" Zalega
1896   // +      input by: ReverseSyntax
1897   // +      input by: Slawomir Kaniecki
1898   // +      input by: Scott Cariss
1899   // +      input by: Francois
1900   // +   bugfixed by: Onno Marsman
1901   // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1902   // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
1903   // +      input by: Ratheous
1904   // +      input by: Mailfaker (http://www.weedem.fr/)
1905   // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
1906   // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
1907   // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
1908   // *     returns 1: '<p>this -> &quot;</p>'
1909   // *     example 2: htmlspecialchars_decode("&amp;quot;");
1910   // *     returns 2: '&quot;'
1911   var optTemp = 0,
1912     i = 0,
1913     noquotes = false;
1914   if (typeof quote_style === 'undefined') {
1915     quote_style = 2;
1916   }
1917   string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
1918   var OPTS = {
1919     'ENT_NOQUOTES': 0,
1920     'ENT_HTML_QUOTE_SINGLE': 1,
1921     'ENT_HTML_QUOTE_DOUBLE': 2,
1922     'ENT_COMPAT': 2,
1923     'ENT_QUOTES': 3,
1924     'ENT_IGNORE': 4
1925   };
1926   if (quote_style === 0) {
1927     noquotes = true;
1928   }
1929   if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
1930     quote_style = [].concat(quote_style);
1931     for (i = 0; i < quote_style.length; i++) {
1932       // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
1933       if (OPTS[quote_style[i]] === 0) {
1934         noquotes = true;
1935       } else if (OPTS[quote_style[i]]) {
1936         optTemp = optTemp | OPTS[quote_style[i]];
1937       }
1938     }
1939     quote_style = optTemp;
1940   }
1941   if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
1942     string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
1943     // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
1944   }
1945   if (!noquotes) {
1946     string = string.replace(/&quot;/g, '"');
1947   }
1948   // Put this in last place to avoid escape being double-decoded
1949   string = string.replace(/&amp;/g, '&');
1950
1951   return string;
1952 }
1953
1954
1955 function label_to_feed_id(label) {
1956         return _label_base_index - 1 - Math.abs(label);
1957 }
1958
1959 function feed_to_label_id(feed) {
1960         return _label_base_index - 1 + Math.abs(feed);
1961 }
1962
1963 // http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac
1964
1965 function getSelectionText() {
1966         var text = "";
1967
1968         if (typeof window.getSelection != "undefined") {
1969                 var sel = window.getSelection();
1970                 if (sel.rangeCount) {
1971                         var container = document.createElement("div");
1972                         for (var i = 0, len = sel.rangeCount; i < len; ++i) {
1973                                 container.appendChild(sel.getRangeAt(i).cloneContents());
1974                         }
1975                         text = container.innerHTML;
1976                 }
1977         } else if (typeof document.selection != "undefined") {
1978                 if (document.selection.type == "Text") {
1979                         text = document.selection.createRange().textText;
1980                 }
1981         }
1982
1983         return text.stripTags();
1984 }