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