]> git.wh0rd.org Git - tt-rss.git/blob - js/functions.js
add ttrss version and init params to reports
[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                         }
51                 }
52
53                 try {
54                         new Ajax.Request("backend.php", {
55                                 parameters: {op: "rpc", method: "log", logmsg: msg},
56                                 onComplete: function (transport) {
57                                         console.log(transport.responseText);
58                                 } });
59
60                 } catch (eii) {
61                         console.log("Exception while trying to log the error.");
62                         console.log(eii);
63                 }
64
65                 msg += "<p>"+ __("The error will be reported to the configured log destination.") +
66                         "</p>";
67
68                 var content = "<div class=\"fatalError\">" +
69                         "<pre>" + msg + "</pre>";
70
71                 content += "<form name=\"exceptionForm\" id=\"exceptionForm\" target=\"_blank\" "+
72                   "action=\"http://tt-rss.org/report.php\" method=\"POST\">";
73
74                 content += "<textarea style=\"display : none\" name=\"message\">" + msg + "</textarea>";
75                 content += "<textarea style=\"display : none\" name=\"params\">N/A</textarea>";
76
77                 if (ext_info) {
78                         content += "<div><b>Additional information:</b></div>" +
79                         "<textarea name=\"xinfo\" readonly=\"1\">" + ext_info + "</textarea>";
80                 }
81
82                 content += "<div><b>Stack trace:</b></div>" +
83                         "<textarea name=\"stack\" readonly=\"1\">" + e.stack + "</textarea>";
84
85                 content += "</form>";
86
87                 content += "</div>";
88
89                 content += "<div class='dlgButtons'>";
90
91                 content += "<button dojoType=\"dijit.form.Button\""+
92                                 "onclick=\"dijit.byId('exceptionDlg').report()\">" +
93                                 __('Report to tt-rss.org') + "</button> ";
94                 content += "<button dojoType=\"dijit.form.Button\" "+
95                                 "onclick=\"dijit.byId('exceptionDlg').hide()\">" +
96                                 __('Close') + "</button>";
97                 content += "</div>";
98
99                 if (dijit.byId("exceptionDlg"))
100                         dijit.byId("exceptionDlg").destroyRecursive();
101
102                 var dialog = new dijit.Dialog({
103                         id: "exceptionDlg",
104                         title: "Unhandled exception",
105                         style: "width: 600px",
106                         report: function() {
107                                 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."))) {
108
109                                         document.forms['exceptionForm'].params.value = $H({
110                                                 browserName: navigator.appName,
111                                                 browserVersion: navigator.appVersion,
112                                                 browserPlatform: navigator.platform,
113                                                 browserCookies: navigator.cookieEnabled,
114                                                 ttrssVersion: __ttrss_version,
115                                                 initParams: JSON.stringify(init_params),
116                                         }).toQueryString();
117
118                                         document.forms['exceptionForm'].submit();
119
120                                 }
121                         },
122                         content: content});
123
124                 dialog.show();
125
126         } catch (ei) {
127                 console.log("Exception while trying to report an exception. Oh boy.");
128                 console.log(ei);
129                 console.log("Original exception:");
130                 console.log(e);
131
132                 msg += "\n\nAdditional exception caught while trying to show the error dialog.\n\n" +  format_exception_error('exception_error', ei);
133
134                 try {
135                         new Ajax.Request("backend.php", {
136                                 parameters: {op: "rpc", method: "log", logmsg: msg},
137                                 onComplete: function (transport) {
138                                         console.log(transport.responseText);
139                                 } });
140
141                 } catch (eii) {
142                         console.log("Third exception while trying to log the error! Seriously?");
143                         console.log(eii);
144                 }
145
146                 msg += "\n\nThe error will be reported to the configured log destination.";
147
148                 alert(msg);
149         }
150
151 }
152
153 function format_exception_error(location, e) {
154         var msg;
155
156         if (e.fileName) {
157                 var base_fname = e.fileName.substring(e.fileName.lastIndexOf("/") + 1);
158
159                 msg = "Exception: " + e.name + ", " + e.message +
160                         "\nFunction: " + location + "()" +
161                         "\nLocation: " + base_fname + ":" + e.lineNumber;
162
163         } else if (e.description) {
164                 msg = "Exception: " + e.description + "\nFunction: " + location + "()";
165         } else {
166                 msg = "Exception: " + e + "\nFunction: " + location + "()";
167         }
168
169         console.error("EXCEPTION: " + msg);
170
171         return msg;
172 }
173
174 function param_escape(arg) {
175         if (typeof encodeURIComponent != 'undefined')
176                 return encodeURIComponent(arg);
177         else
178                 return escape(arg);
179 }
180
181 function param_unescape(arg) {
182         if (typeof decodeURIComponent != 'undefined')
183                 return decodeURIComponent(arg);
184         else
185                 return unescape(arg);
186 }
187
188
189 function hide_notify() {
190         Element.hide('notify');
191 }
192
193 function notify_real(msg, no_hide, n_type) {
194
195         var n = $("notify");
196
197         if (!n) return;
198
199         if (notify_hide_timerid) {
200                 window.clearTimeout(notify_hide_timerid);
201         }
202
203         if (msg == "") {
204                 if (Element.visible(n)) {
205                         notify_hide_timerid = window.setTimeout("hide_notify()", 0);
206                 }
207                 return;
208         } else {
209                 Element.show(n);
210         }
211
212         /* types:
213
214                 1 - generic
215                 2 - progress
216                 3 - error
217                 4 - info
218
219         */
220
221         msg = "<span class=\"msg\"> " + __(msg) + "</span>";
222
223         if (n_type == 1) {
224                 n.className = "notify";
225         } else if (n_type == 2) {
226                 n.className = "notify progress";
227                 msg = "<span><img src='images/indicator_white.gif'></span>" + msg;
228                 no_hide = true;
229         } else if (n_type == 3) {
230                 n.className = "notify error";
231                 msg = "<span><img src='images/alert.png'></span>" + msg;
232         } else if (n_type == 4) {
233                 n.className = "notify info";
234                 msg = "<span><img src='images/information.png'></span>" + msg;
235         }
236
237         msg += " <span><img src=\"images/cross.png\" class=\"close\" title=\"" +
238                 __("Click to close") + "\" onclick=\"notify('')\"></span>";
239
240 //      msg = "<img src='images/live_com_loading.gif'> " + msg;
241
242         n.innerHTML = msg;
243
244         if (!no_hide) {
245                 notify_hide_timerid = window.setTimeout("hide_notify()", 5*1000);
246         }
247 }
248
249 function notify(msg, no_hide) {
250         notify_real(msg, no_hide, 1);
251 }
252
253 function notify_progress(msg, no_hide) {
254         notify_real(msg, no_hide, 2);
255 }
256
257 function notify_error(msg, no_hide) {
258         notify_real(msg, no_hide, 3);
259
260 }
261
262 function notify_info(msg, no_hide) {
263         notify_real(msg, no_hide, 4);
264 }
265
266 function setCookie(name, value, lifetime, path, domain, secure) {
267
268         var d = false;
269
270         if (lifetime) {
271                 d = new Date();
272                 d.setTime(d.getTime() + (lifetime * 1000));
273         }
274
275         console.log("setCookie: " + name + " => " + value + ": " + d);
276
277         int_setCookie(name, value, d, path, domain, secure);
278
279 }
280
281 function int_setCookie(name, value, expires, path, domain, secure) {
282         document.cookie= name + "=" + escape(value) +
283                 ((expires) ? "; expires=" + expires.toGMTString() : "") +
284                 ((path) ? "; path=" + path : "") +
285                 ((domain) ? "; domain=" + domain : "") +
286                 ((secure) ? "; secure" : "");
287 }
288
289 function delCookie(name, path, domain) {
290         if (getCookie(name)) {
291                 document.cookie = name + "=" +
292                 ((path) ? ";path=" + path : "") +
293                 ((domain) ? ";domain=" + domain : "" ) +
294                 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
295         }
296 }
297
298
299 function getCookie(name) {
300
301         var dc = document.cookie;
302         var prefix = name + "=";
303         var begin = dc.indexOf("; " + prefix);
304         if (begin == -1) {
305             begin = dc.indexOf(prefix);
306             if (begin != 0) return null;
307         }
308         else {
309             begin += 2;
310         }
311         var end = document.cookie.indexOf(";", begin);
312         if (end == -1) {
313             end = dc.length;
314         }
315         return unescape(dc.substring(begin + prefix.length, end));
316 }
317
318 function gotoPreferences() {
319         document.location.href = "prefs.php";
320 }
321
322 function gotoLogout() {
323         document.location.href = "backend.php?op=logout";
324 }
325
326 function gotoMain() {
327         document.location.href = "index.php";
328 }
329
330 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
331   * * @author Sundar Dorai-Raj
332   * * Email: sdoraira@vt.edu
333   * * This program is free software; you can redistribute it and/or
334   * * modify it under the terms of the GNU General Public License
335   * * as published by the Free Software Foundation; either version 2
336   * * of the License, or (at your option) any later version,
337   * * provided that any use properly credits the author.
338   * * This program is distributed in the hope that it will be useful,
339   * * but WITHOUT ANY WARRANTY; without even the implied warranty of
340   * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
341   * * GNU General Public License for more details at http://www.gnu.org * * */
342
343   var numbers=".0123456789";
344   function isNumeric(x) {
345     // is x a String or a character?
346     if(x.length>1) {
347       // remove negative sign
348       x=Math.abs(x)+"";
349       for(var j=0;j<x.length;j++) {
350         // call isNumeric recursively for each character
351         number=isNumeric(x.substring(j,j+1));
352         if(!number) return number;
353       }
354       return number;
355     }
356     else {
357       // if x is number return true
358       if(numbers.indexOf(x)>=0) return true;
359       return false;
360     }
361   }
362
363
364 function toggleSelectRowById(sender, id) {
365         var row = $(id);
366         return toggleSelectRow(sender, row);
367 }
368
369 function toggleSelectListRow(sender) {
370         var row = sender.parentNode;
371         return toggleSelectRow(sender, row);
372 }
373
374 /* this is for dijit Checkbox */
375 function toggleSelectListRow2(sender) {
376         var row = sender.domNode.parentNode;
377         return toggleSelectRow(sender, row);
378 }
379
380 /* this is for dijit Checkbox */
381 function toggleSelectRow2(sender, row, is_cdm) {
382
383         if (!row)
384                 if (!is_cdm)
385                         row = sender.domNode.parentNode.parentNode;
386                 else
387                         row = sender.domNode.parentNode.parentNode.parentNode; // oh ffs
388
389         if (sender.checked && !row.hasClassName('Selected'))
390                 row.addClassName('Selected');
391         else
392                 row.removeClassName('Selected');
393
394         if (typeof updateSelectedPrompt != undefined)
395                 updateSelectedPrompt();
396 }
397
398
399 function toggleSelectRow(sender, row) {
400
401         if (!row) row = sender.parentNode.parentNode;
402
403         if (sender.checked && !row.hasClassName('Selected'))
404                 row.addClassName('Selected');
405         else
406                 row.removeClassName('Selected');
407
408         if (typeof updateSelectedPrompt != undefined)
409                 updateSelectedPrompt();
410 }
411
412 function checkboxToggleElement(elem, id) {
413         if (elem.checked) {
414                 Effect.Appear(id, {duration : 0.5});
415         } else {
416                 Effect.Fade(id, {duration : 0.5});
417         }
418 }
419
420 function dropboxSelect(e, v) {
421         for (var i = 0; i < e.length; i++) {
422                 if (e[i].value == v) {
423                         e.selectedIndex = i;
424                         break;
425                 }
426         }
427 }
428
429 function getURLParam(param){
430         return String(window.location.href).parseQuery()[param];
431 }
432
433 function closeInfoBox(cleanup) {
434         try {
435                 dialog = dijit.byId("infoBox");
436
437                 if (dialog)     dialog.hide();
438
439         } catch (e) {
440                 //exception_error("closeInfoBox", e);
441         }
442         return false;
443 }
444
445
446 function displayDlg(title, id, param, callback) {
447
448         notify_progress("Loading, please wait...", true);
449
450         var query = "?op=dlg&method=" +
451                 param_escape(id) + "&param=" + param_escape(param);
452
453         new Ajax.Request("backend.php", {
454                 parameters: query,
455                 onComplete: function (transport) {
456                         infobox_callback2(transport, title);
457                         if (callback) callback(transport);
458                 } });
459
460         return false;
461 }
462
463 function infobox_callback2(transport, title) {
464         try {
465                 var dialog = false;
466
467                 if (dijit.byId("infoBox")) {
468                         dialog = dijit.byId("infoBox");
469                 }
470
471                 //console.log("infobox_callback2");
472                 notify('');
473
474                 var content = transport.responseText;
475
476                 if (!dialog) {
477                         dialog = new dijit.Dialog({
478                                 title: title,
479                                 id: 'infoBox',
480                                 style: "width: 600px",
481                                 onCancel: function() {
482                                         return true;
483                                 },
484                                 onExecute: function() {
485                                         return true;
486                                 },
487                                 onClose: function() {
488                                         return true;
489                                         },
490                                 content: content});
491                 } else {
492                         dialog.attr('title', title);
493                         dialog.attr('content', content);
494                 }
495
496                 dialog.show();
497
498                 notify("");
499         } catch (e) {
500                 exception_error("infobox_callback2", e);
501         }
502 }
503
504 function filterCR(e, f)
505 {
506      var key;
507
508      if(window.event)
509           key = window.event.keyCode;     //IE
510      else
511           key = e.which;     //firefox
512
513         if (key == 13) {
514                 if (typeof f != 'undefined') {
515                         f();
516                         return false;
517                 } else {
518                         return false;
519                 }
520         } else {
521                 return true;
522         }
523 }
524
525 function getInitParam(key) {
526         return init_params[key];
527 }
528
529 function setInitParam(key, value) {
530         init_params[key] = value;
531 }
532
533 function fatalError(code, msg, ext_info) {
534         try {
535
536                 if (code == 6) {
537                         window.location.href = "index.php";
538                 } else if (code == 5) {
539                         window.location.href = "public.php?op=dbupdate";
540                 } else {
541
542                         if (msg == "") msg = "Unknown error";
543
544                         if (ext_info) {
545                                 if (ext_info.responseText) {
546                                         ext_info = ext_info.responseText;
547                                 }
548                         }
549
550                         if (ERRORS && ERRORS[code] && !msg) {
551                                 msg = ERRORS[code];
552                         }
553
554                         var content = "<div><b>Error code:</b> " + code + "</div>" +
555                                 "<p>" + msg + "</p>";
556
557                         if (ext_info) {
558                                 content = content + "<div><b>Additional information:</b></div>" +
559                                         "<textarea style='width: 100%' readonly=\"1\">" +
560                                         ext_info + "</textarea>";
561                         }
562
563                         var dialog = new dijit.Dialog({
564                                 title: "Fatal error",
565                                 style: "width: 600px",
566                                 content: content});
567
568                         dialog.show();
569
570                 }
571
572                 return false;
573
574         } catch (e) {
575                 exception_error("fatalError", e);
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
613 function explainError(code) {
614         return displayDlg(__("Error explained"), "explainError", code);
615 }
616
617 function loading_set_progress(p) {
618         try {
619                 loading_progress += p;
620
621                 if (dijit.byId("loading_bar"))
622                         dijit.byId("loading_bar").update({progress: loading_progress});
623
624                 if (loading_progress >= 90)
625                         remove_splash();
626
627         } catch (e) {
628                 exception_error("loading_set_progress", e);
629         }
630 }
631
632 function remove_splash() {
633
634         if (Element.visible("overlay")) {
635                 console.log("about to remove splash, OMG!");
636                 Element.hide("overlay");
637                 console.log("removed splash!");
638         }
639 }
640
641 function transport_error_check(transport) {
642         try {
643                 if (transport.responseXML) {
644                         var error = transport.responseXML.getElementsByTagName("error")[0];
645
646                         if (error) {
647                                 var code = error.getAttribute("error-code");
648                                 var msg = error.getAttribute("error-msg");
649                                 if (code != 0) {
650                                         fatalError(code, msg);
651                                         return false;
652                                 }
653                         }
654                 }
655         } catch (e) {
656                 exception_error("check_for_error_xml", e);
657         }
658         return true;
659 }
660
661 function strip_tags(s) {
662         return s.replace(/<\/?[^>]+(>|$)/g, "");
663 }
664
665 function truncate_string(s, length) {
666         if (!length) length = 30;
667         var tmp = s.substring(0, length);
668         if (s.length > length) tmp += "&hellip;";
669         return tmp;
670 }
671
672 function hotkey_prefix_timeout() {
673         try {
674
675                 var date = new Date();
676                 var ts = Math.round(date.getTime() / 1000);
677
678                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
679                         console.log("hotkey_prefix seems to be stuck, aborting");
680                         hotkey_prefix_pressed = false;
681                         hotkey_prefix = false;
682                         Element.hide('cmdline');
683                 }
684
685                 setTimeout("hotkey_prefix_timeout()", 1000);
686
687         } catch  (e) {
688                 exception_error("hotkey_prefix_timeout", e);
689         }
690 }
691
692 function uploadIconHandler(rc) {
693         try {
694                 switch (rc) {
695                         case 0:
696                                 notify_info("Upload complete.");
697                                 if (inPreferences()) {
698                                         updateFeedList();
699                                 } else {
700                                         setTimeout('updateFeedList(false, false)', 50);
701                                 }
702                                 break;
703                         case 1:
704                                 notify_error("Upload failed: icon is too big.");
705                                 break;
706                         case 2:
707                                 notify_error("Upload failed.");
708                                 break;
709                 }
710
711         } catch (e) {
712                 exception_error("uploadIconHandler", e);
713         }
714 }
715
716 function removeFeedIcon(id) {
717
718         try {
719
720                 if (confirm(__("Remove stored feed icon?"))) {
721                         var query = "backend.php?op=pref-feeds&method=removeicon&feed_id=" + param_escape(id);
722
723                         console.log(query);
724
725                         notify_progress("Removing feed icon...", true);
726
727                         new Ajax.Request("backend.php", {
728                                 parameters: query,
729                                 onComplete: function(transport) {
730                                         notify_info("Feed icon removed.");
731                                         if (inPreferences()) {
732                                                 updateFeedList();
733                                         } else {
734                                                 setTimeout('updateFeedList(false, false)', 50);
735                                         }
736                                 } });
737                 }
738
739                 return false;
740         } catch (e) {
741                 exception_error("removeFeedIcon", e);
742         }
743 }
744
745 function uploadFeedIcon() {
746
747         try {
748
749                 var file = $("icon_file");
750
751                 if (file.value.length == 0) {
752                         alert(__("Please select an image file to upload."));
753                 } else {
754                         if (confirm(__("Upload new icon for this feed?"))) {
755                                 notify_progress("Uploading, please wait...", true);
756                                 return true;
757                         }
758                 }
759
760                 return false;
761
762         } catch (e) {
763                 exception_error("uploadFeedIcon", e);
764         }
765 }
766
767 function addLabel(select, callback) {
768
769         try {
770
771                 var caption = prompt(__("Please enter label caption:"), "");
772
773                 if (caption != undefined) {
774
775                         if (caption == "") {
776                                 alert(__("Can't create label: missing caption."));
777                                 return false;
778                         }
779
780                         var query = "?op=pref-labels&method=add&caption=" +
781                                 param_escape(caption);
782
783                         if (select)
784                                 query += "&output=select";
785
786                         notify_progress("Loading, please wait...", true);
787
788                         if (inPreferences() && !select) active_tab = "labelConfig";
789
790                         new Ajax.Request("backend.php", {
791                                 parameters: query,
792                                 onComplete: function(transport) {
793                                         if (callback) {
794                                                 callback(transport);
795                                         } else if (inPreferences()) {
796                                                 updateLabelList();
797                                         } else {
798                                                 updateFeedList();
799                                         }
800                         } });
801
802                 }
803
804         } catch (e) {
805                 exception_error("addLabel", e);
806         }
807 }
808
809 function quickAddFeed() {
810         try {
811                 var query = "backend.php?op=feeds&method=quickAddFeed";
812
813                 // overlapping widgets
814                 if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive();
815                 if (dijit.byId("feedAddDlg"))   dijit.byId("feedAddDlg").destroyRecursive();
816
817                 var dialog = new dijit.Dialog({
818                         id: "feedAddDlg",
819                         title: __("Subscribe to Feed"),
820                         style: "width: 600px",
821                         execute: function() {
822                                 if (this.validate()) {
823                                         console.log(dojo.objectToQuery(this.attr('value')));
824
825                                         var feed_url = this.attr('value').feed;
826
827                                         Element.show("feed_add_spinner");
828
829                                         new Ajax.Request("backend.php", {
830                                                 parameters: dojo.objectToQuery(this.attr('value')),
831                                                 onComplete: function(transport) {
832                                                         try {
833
834                                                                 try {
835                                                                         var reply = JSON.parse(transport.responseText);
836                                                                 } catch (e) {
837                                                                         Element.hide("feed_add_spinner");
838                                                                         alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console."));
839                                                                         console.log('quickAddFeed, backend returned:' + transport.responseText);
840                                                                         return;
841                                                                 }
842
843                                                                 var rc = reply['result'];
844
845                                                                 notify('');
846                                                                 Element.hide("feed_add_spinner");
847
848                                                                 console.log(rc);
849
850                                                                 switch (parseInt(rc['code'])) {
851                                                                 case 1:
852                                                                         dialog.hide();
853                                                                         notify_info(__("Subscribed to %s").replace("%s", feed_url));
854
855                                                                         updateFeedList();
856                                                                         break;
857                                                                 case 2:
858                                                                         alert(__("Specified URL seems to be invalid."));
859                                                                         break;
860                                                                 case 3:
861                                                                         alert(__("Specified URL doesn't seem to contain any feeds."));
862                                                                         break;
863                                                                 case 4:
864                                                                         feeds = rc['feeds'];
865
866                                                                         Element.show("fadd_multiple_notify");
867
868                                                                         var select = dijit.byId("feedDlg_feedContainerSelect");
869
870                                                                         while (select.getOptions().length > 0)
871                                                                                 select.removeOption(0);
872
873                                                                         select.addOption({value: '', label: __("Expand to select feed")});
874
875                                                                         var count = 0;
876                                                                         for (var feedUrl in feeds) {
877                                                                                 select.addOption({value: feedUrl, label: feeds[feedUrl]});
878                                                                                 count++;
879                                                                         }
880
881                                                                         Effect.Appear('feedDlg_feedsContainer', {duration : 0.5});
882
883                                                                         break;
884                                                                 case 5:
885                                                                         alert(__("Couldn't download the specified URL: %s").
886                                                                                         replace("%s", rc['message']));
887                                                                         break;
888                                                                 case 6:
889                                                                         alert(__("XML validation failed: %s").
890                                                                                         replace("%s", rc['message']));
891                                                                         break;
892                                                                         break;
893                                                                 case 0:
894                                                                         alert(__("You are already subscribed to this feed."));
895                                                                         break;
896                                                                 }
897
898                                                         } catch (e) {
899                                                                 exception_error("subscribeToFeed", e, transport);
900                                                         }
901
902                                                 } });
903
904                                         }
905                         },
906                         href: query});
907
908                 dialog.show();
909         } catch (e) {
910                 exception_error("quickAddFeed", e);
911         }
912 }
913
914 function createNewRuleElement(parentNode, replaceNode) {
915         try {
916                 var form = document.forms["filter_new_rule_form"];
917
918                 form.reg_exp.value = form.reg_exp.value.replace(/(<([^>]+)>)/ig,"");
919
920                 var query = "backend.php?op=pref-filters&method=printrulename&rule="+
921                         param_escape(dojo.formToJson(form));
922
923                 console.log(query);
924
925                 new Ajax.Request("backend.php", {
926                         parameters: query,
927                         onComplete: function (transport) {
928                                 try {
929                                         var li = dojo.create("li");
930
931                                         var cb = dojo.create("input", { type: "checkbox" }, li);
932
933                                         new dijit.form.CheckBox({
934                                                 onChange: function() {
935                                                         toggleSelectListRow2(this) },
936                                         }, cb);
937
938                                         dojo.create("input", { type: "hidden",
939                                                 name: "rule[]",
940                                                 value: dojo.formToJson(form) }, li);
941
942                                         dojo.create("span", {
943                                                 onclick: function() {
944                                                         dijit.byId('filterEditDlg').editRule(this);
945                                                 },
946                                                 innerHTML: transport.responseText }, li);
947
948                                         if (replaceNode) {
949                                                 parentNode.replaceChild(li, replaceNode);
950                                         } else {
951                                                 parentNode.appendChild(li);
952                                         }
953                                 } catch (e) {
954                                         exception_error("createNewRuleElement", e);
955                                 }
956                 } });
957         } catch (e) {
958                 exception_error("createNewRuleElement", e);
959         }
960 }
961
962 function createNewActionElement(parentNode, replaceNode) {
963         try {
964                 var form = document.forms["filter_new_action_form"];
965
966                 if (form.action_id.value == 7) {
967                         form.action_param.value = form.action_param_label.value;
968                 }
969
970                 var query = "backend.php?op=pref-filters&method=printactionname&action="+
971                         param_escape(dojo.formToJson(form));
972
973                 console.log(query);
974
975                 new Ajax.Request("backend.php", {
976                         parameters: query,
977                         onComplete: function (transport) {
978                                 try {
979                                         var li = dojo.create("li");
980
981                                         var cb = dojo.create("input", { type: "checkbox" }, li);
982
983                                         new dijit.form.CheckBox({
984                                                 onChange: function() {
985                                                         toggleSelectListRow2(this) },
986                                         }, cb);
987
988                                         dojo.create("input", { type: "hidden",
989                                                 name: "action[]",
990                                                 value: dojo.formToJson(form) }, li);
991
992                                         dojo.create("span", {
993                                                 onclick: function() {
994                                                         dijit.byId('filterEditDlg').editAction(this);
995                                                 },
996                                                 innerHTML: transport.responseText }, li);
997
998                                         if (replaceNode) {
999                                                 parentNode.replaceChild(li, replaceNode);
1000                                         } else {
1001                                                 parentNode.appendChild(li);
1002                                         }
1003
1004                                 } catch (e) {
1005                                         exception_error("createNewActionElement", e);
1006                                 }
1007                         } });
1008         } catch (e) {
1009                 exception_error("createNewActionElement", e);
1010         }
1011 }
1012
1013
1014 function addFilterRule(replaceNode, ruleStr) {
1015         try {
1016                 if (dijit.byId("filterNewRuleDlg"))
1017                         dijit.byId("filterNewRuleDlg").destroyRecursive();
1018
1019                 var query = "backend.php?op=pref-filters&method=newrule&rule=" +
1020                         param_escape(ruleStr);
1021
1022                 var rule_dlg = new dijit.Dialog({
1023                         id: "filterNewRuleDlg",
1024                         title: ruleStr ? __("Edit rule") : __("Add rule"),
1025                         style: "width: 600px",
1026                         execute: function() {
1027                                 if (this.validate()) {
1028                                         createNewRuleElement($("filterDlg_Matches"), replaceNode);
1029                                         this.hide();
1030                                 }
1031                         },
1032                         href: query});
1033
1034                 rule_dlg.show();
1035         } catch (e) {
1036                 exception_error("addFilterRule", e);
1037         }
1038 }
1039
1040 function addFilterAction(replaceNode, actionStr) {
1041         try {
1042                 if (dijit.byId("filterNewActionDlg"))
1043                         dijit.byId("filterNewActionDlg").destroyRecursive();
1044
1045                 var query = "backend.php?op=pref-filters&method=newaction&action=" +
1046                         param_escape(actionStr);
1047
1048                 var rule_dlg = new dijit.Dialog({
1049                         id: "filterNewActionDlg",
1050                         title: actionStr ? __("Edit action") : __("Add action"),
1051                         style: "width: 600px",
1052                         execute: function() {
1053                                 if (this.validate()) {
1054                                         createNewActionElement($("filterDlg_Actions"), replaceNode);
1055                                         this.hide();
1056                                 }
1057                         },
1058                         href: query});
1059
1060                 rule_dlg.show();
1061         } catch (e) {
1062                 exception_error("addFilterAction", e);
1063         }
1064 }
1065
1066 function quickAddFilter() {
1067         try {
1068                 var query = "";
1069                 if (!inPreferences()) {
1070                         query = "backend.php?op=pref-filters&method=newfilter&feed=" +
1071                                 param_escape(getActiveFeedId()) + "&is_cat=" +
1072                                 param_escape(activeFeedIsCat());
1073                 } else {
1074                         query = "backend.php?op=pref-filters&method=newfilter";
1075                 }
1076
1077                 console.log(query);
1078
1079                 if (dijit.byId("feedEditDlg"))
1080                         dijit.byId("feedEditDlg").destroyRecursive();
1081
1082                 if (dijit.byId("filterEditDlg"))
1083                         dijit.byId("filterEditDlg").destroyRecursive();
1084
1085                 dialog = new dijit.Dialog({
1086                         id: "filterEditDlg",
1087                         title: __("Create Filter"),
1088                         style: "width: 600px",
1089                         test: function() {
1090                                 var query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test";
1091
1092                                 if (dijit.byId("filterTestDlg"))
1093                                         dijit.byId("filterTestDlg").destroyRecursive();
1094
1095                                 var test_dlg = new dijit.Dialog({
1096                                         id: "filterTestDlg",
1097                                         title: "Test Filter",
1098                                         style: "width: 600px",
1099                                         href: query});
1100
1101                                 test_dlg.show();
1102                         },
1103                         selectRules: function(select) {
1104                                 $$("#filterDlg_Matches input[type=checkbox]").each(function(e) {
1105                                         e.checked = select;
1106                                         if (select)
1107                                                 e.parentNode.addClassName("Selected");
1108                                         else
1109                                                 e.parentNode.removeClassName("Selected");
1110                                 });
1111                         },
1112                         selectActions: function(select) {
1113                                 $$("#filterDlg_Actions input[type=checkbox]").each(function(e) {
1114                                         e.checked = select;
1115
1116                                         if (select)
1117                                                 e.parentNode.addClassName("Selected");
1118                                         else
1119                                                 e.parentNode.removeClassName("Selected");
1120
1121                                 });
1122                         },
1123                         editRule: function(e) {
1124                                 var li = e.parentNode;
1125                                 var rule = li.getElementsByTagName("INPUT")[1].value;
1126                                 addFilterRule(li, rule);
1127                         },
1128                         editAction: function(e) {
1129                                 var li = e.parentNode;
1130                                 var action = li.getElementsByTagName("INPUT")[1].value;
1131                                 addFilterAction(li, action);
1132                         },
1133                         addAction: function() { addFilterAction(); },
1134                         addRule: function() { addFilterRule(); },
1135                         deleteAction: function() {
1136                                 $$("#filterDlg_Actions li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1137                         },
1138                         deleteRule: function() {
1139                                 $$("#filterDlg_Matches li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1140                         },
1141                         execute: function() {
1142                                 if (this.validate()) {
1143
1144                                         var query = dojo.formToQuery("filter_new_form");
1145
1146                                         console.log(query);
1147
1148                                         new Ajax.Request("backend.php", {
1149                                                 parameters: query,
1150                                                 onComplete: function (transport) {
1151                                                         if (inPreferences()) {
1152                                                                 updateFilterList();
1153                                                         }
1154
1155                                                         dialog.hide();
1156                                         } });
1157                                 }
1158                         },
1159                         href: query});
1160
1161                 if (!inPreferences()) {
1162                         var selectedText = getSelectionText();
1163
1164                         var lh = dojo.connect(dialog, "onLoad", function(){
1165                                 dojo.disconnect(lh);
1166
1167                                 if (selectedText != "") {
1168
1169                                         var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1170                                                 getActiveFeedId();
1171
1172                                         var rule = { reg_exp: selectedText, feed_id: feed_id, filter_type: 1 };
1173
1174                                         addFilterRule(null, dojo.toJson(rule));
1175
1176                                 } else {
1177
1178                                         var query = "op=rpc&method=getlinktitlebyid&id=" + getActiveArticleId();
1179
1180                                         new Ajax.Request("backend.php", {
1181                                         parameters: query,
1182                                         onComplete: function(transport) {
1183                                                 var reply = JSON.parse(transport.responseText);
1184
1185                                                 var title = false;
1186
1187                                                 if (reply && reply) title = reply.title;
1188
1189                                                 if (title || getActiveFeedId() || activeFeedIsCat()) {
1190
1191                                                         console.log(title + " " + getActiveFeedId());
1192
1193                                                         var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1194                                                                 getActiveFeedId();
1195
1196                                                         var rule = { reg_exp: title, feed_id: feed_id, filter_type: 1 };
1197
1198                                                         addFilterRule(null, dojo.toJson(rule));
1199                                                 }
1200
1201                                         } });
1202
1203                                 }
1204
1205                         });
1206                 }
1207
1208                 dialog.show();
1209
1210         } catch (e) {
1211                 exception_error("quickAddFilter", e);
1212         }
1213 }
1214
1215 function resetPubSub(feed_id, title) {
1216
1217         var msg = __("Reset subscription? Tiny Tiny RSS will try to subscribe to the notification hub again on next feed update.").replace("%s", title);
1218
1219         if (title == undefined || confirm(msg)) {
1220                 notify_progress("Loading, please wait...");
1221
1222                 var query = "?op=pref-feeds&quiet=1&method=resetPubSub&ids=" + feed_id;
1223
1224                 new Ajax.Request("backend.php", {
1225                         parameters: query,
1226                         onComplete: function(transport) {
1227                                 dijit.byId("pubsubReset_Btn").attr('disabled', true);
1228                                 notify_info("Subscription reset.");
1229                         } });
1230         }
1231
1232         return false;
1233 }
1234
1235
1236 function unsubscribeFeed(feed_id, title) {
1237
1238         var msg = __("Unsubscribe from %s?").replace("%s", title);
1239
1240         if (title == undefined || confirm(msg)) {
1241                 notify_progress("Removing feed...");
1242
1243                 var query = "?op=pref-feeds&quiet=1&method=remove&ids=" + feed_id;
1244
1245                 new Ajax.Request("backend.php", {
1246                         parameters: query,
1247                         onComplete: function(transport) {
1248
1249                                         if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1250
1251                                         if (inPreferences()) {
1252                                                 updateFeedList();
1253                                         } else {
1254                                                 if (feed_id == getActiveFeedId())
1255                                                         setTimeout("viewfeed(-5)", 100);
1256
1257                                                 if (feed_id < 0) updateFeedList();
1258                                         }
1259
1260                                 } });
1261         }
1262
1263         return false;
1264 }
1265
1266
1267 function backend_sanity_check_callback(transport) {
1268
1269         try {
1270
1271                 if (sanity_check_done) {
1272                         fatalError(11, "Sanity check request received twice. This can indicate "+
1273                       "presence of Firebug or some other disrupting extension. "+
1274                                 "Please disable it and try again.");
1275                         return;
1276                 }
1277
1278                 var reply = JSON.parse(transport.responseText);
1279
1280                 if (!reply) {
1281                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1282                         return;
1283                 }
1284
1285                 var error_code = reply['error']['code'];
1286
1287                 if (error_code && error_code != 0) {
1288                         return fatalError(error_code, reply['error']['message']);
1289                 }
1290
1291                 console.log("sanity check ok");
1292
1293                 var params = reply['init-params'];
1294
1295                 if (params) {
1296                         console.log('reading init-params...');
1297
1298                         for (k in params) {
1299                                 var v = params[k];
1300                                 console.log("IP: " + k + " => " + v);
1301
1302                                 if (k == "label_base_index") _label_base_index = parseInt(v);
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 }