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