]> git.wh0rd.org Git - tt-rss.git/blob - js/functions.js
api: getHeadlines: add configurable excerpt_length (bump api version)
[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 filterCR(e, f)
506 {
507      var key;
508
509      if(window.event)
510           key = window.event.keyCode;     //IE
511      else
512           key = e.which;     //firefox
513
514         if (key == 13) {
515                 if (typeof f != 'undefined') {
516                         f();
517                         return false;
518                 } else {
519                         return false;
520                 }
521         } else {
522                 return true;
523         }
524 }
525
526 function getInitParam(key) {
527         return init_params[key];
528 }
529
530 function setInitParam(key, value) {
531         init_params[key] = value;
532 }
533
534 function fatalError(code, msg, ext_info) {
535         try {
536
537                 if (code == 6) {
538                         window.location.href = "index.php";
539                 } else if (code == 5) {
540                         window.location.href = "public.php?op=dbupdate";
541                 } else {
542
543                         if (msg == "") msg = "Unknown error";
544
545                         if (ext_info) {
546                                 if (ext_info.responseText) {
547                                         ext_info = ext_info.responseText;
548                                 }
549                         }
550
551                         if (ERRORS && ERRORS[code] && !msg) {
552                                 msg = ERRORS[code];
553                         }
554
555                         var content = "<div><b>Error code:</b> " + code + "</div>" +
556                                 "<p>" + msg + "</p>";
557
558                         if (ext_info) {
559                                 content = content + "<div><b>Additional information:</b></div>" +
560                                         "<textarea style='width: 100%' readonly=\"1\">" +
561                                         ext_info + "</textarea>";
562                         }
563
564                         var dialog = new dijit.Dialog({
565                                 title: "Fatal error",
566                                 style: "width: 600px",
567                                 content: content});
568
569                         dialog.show();
570
571                 }
572
573                 return false;
574
575         } catch (e) {
576                 exception_error("fatalError", e);
577         }
578 }
579
580 function filterDlgCheckAction(sender) {
581
582         try {
583
584                 var action = sender.value;
585
586                 var action_param = $("filterDlg_paramBox");
587
588                 if (!action_param) {
589                         console.log("filterDlgCheckAction: can't find action param box!");
590                         return;
591                 }
592
593                 // if selected action supports parameters, enable params field
594                 if (action == 4 || action == 6 || action == 7) {
595                         new Effect.Appear(action_param, {duration : 0.5});
596                         if (action != 7) {
597                                 Element.show(dijit.byId("filterDlg_actionParam").domNode);
598                                 Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode);
599                         } else {
600                                 Element.show(dijit.byId("filterDlg_actionParamLabel").domNode);
601                                 Element.hide(dijit.byId("filterDlg_actionParam").domNode);
602                         }
603                 } else {
604                         Element.hide(action_param);
605                 }
606
607         } catch (e) {
608                 exception_error("filterDlgCheckAction", e);
609         }
610
611 }
612
613
614 function explainError(code) {
615         return displayDlg(__("Error explained"), "explainError", code);
616 }
617
618 function loading_set_progress(p) {
619         try {
620                 loading_progress += p;
621
622                 if (dijit.byId("loading_bar"))
623                         dijit.byId("loading_bar").update({progress: loading_progress});
624
625                 if (loading_progress >= 90)
626                         remove_splash();
627
628         } catch (e) {
629                 exception_error("loading_set_progress", e);
630         }
631 }
632
633 function remove_splash() {
634
635         if (Element.visible("overlay")) {
636                 console.log("about to remove splash, OMG!");
637                 Element.hide("overlay");
638                 console.log("removed splash!");
639         }
640 }
641
642 function transport_error_check(transport) {
643         try {
644                 if (transport.responseXML) {
645                         var error = transport.responseXML.getElementsByTagName("error")[0];
646
647                         if (error) {
648                                 var code = error.getAttribute("error-code");
649                                 var msg = error.getAttribute("error-msg");
650                                 if (code != 0) {
651                                         fatalError(code, msg);
652                                         return false;
653                                 }
654                         }
655                 }
656         } catch (e) {
657                 exception_error("check_for_error_xml", e);
658         }
659         return true;
660 }
661
662 function strip_tags(s) {
663         return s.replace(/<\/?[^>]+(>|$)/g, "");
664 }
665
666 function truncate_string(s, length) {
667         if (!length) length = 30;
668         var tmp = s.substring(0, length);
669         if (s.length > length) tmp += "&hellip;";
670         return tmp;
671 }
672
673 function hotkey_prefix_timeout() {
674         try {
675
676                 var date = new Date();
677                 var ts = Math.round(date.getTime() / 1000);
678
679                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
680                         console.log("hotkey_prefix seems to be stuck, aborting");
681                         hotkey_prefix_pressed = false;
682                         hotkey_prefix = false;
683                         Element.hide('cmdline');
684                 }
685
686                 setTimeout("hotkey_prefix_timeout()", 1000);
687
688         } catch  (e) {
689                 exception_error("hotkey_prefix_timeout", e);
690         }
691 }
692
693 function uploadIconHandler(rc) {
694         try {
695                 switch (rc) {
696                         case 0:
697                                 notify_info("Upload complete.");
698                                 if (inPreferences()) {
699                                         updateFeedList();
700                                 } else {
701                                         setTimeout('updateFeedList(false, false)', 50);
702                                 }
703                                 break;
704                         case 1:
705                                 notify_error("Upload failed: icon is too big.");
706                                 break;
707                         case 2:
708                                 notify_error("Upload failed.");
709                                 break;
710                 }
711
712         } catch (e) {
713                 exception_error("uploadIconHandler", e);
714         }
715 }
716
717 function removeFeedIcon(id) {
718
719         try {
720
721                 if (confirm(__("Remove stored feed icon?"))) {
722                         var query = "backend.php?op=pref-feeds&method=removeicon&feed_id=" + param_escape(id);
723
724                         console.log(query);
725
726                         notify_progress("Removing feed icon...", true);
727
728                         new Ajax.Request("backend.php", {
729                                 parameters: query,
730                                 onComplete: function(transport) {
731                                         notify_info("Feed icon removed.");
732                                         if (inPreferences()) {
733                                                 updateFeedList();
734                                         } else {
735                                                 setTimeout('updateFeedList(false, false)', 50);
736                                         }
737                                 } });
738                 }
739
740                 return false;
741         } catch (e) {
742                 exception_error("removeFeedIcon", e);
743         }
744 }
745
746 function uploadFeedIcon() {
747
748         try {
749
750                 var file = $("icon_file");
751
752                 if (file.value.length == 0) {
753                         alert(__("Please select an image file to upload."));
754                 } else {
755                         if (confirm(__("Upload new icon for this feed?"))) {
756                                 notify_progress("Uploading, please wait...", true);
757                                 return true;
758                         }
759                 }
760
761                 return false;
762
763         } catch (e) {
764                 exception_error("uploadFeedIcon", e);
765         }
766 }
767
768 function addLabel(select, callback) {
769
770         try {
771
772                 var caption = prompt(__("Please enter label caption:"), "");
773
774                 if (caption != undefined) {
775
776                         if (caption == "") {
777                                 alert(__("Can't create label: missing caption."));
778                                 return false;
779                         }
780
781                         var query = "?op=pref-labels&method=add&caption=" +
782                                 param_escape(caption);
783
784                         if (select)
785                                 query += "&output=select";
786
787                         notify_progress("Loading, please wait...", true);
788
789                         if (inPreferences() && !select) active_tab = "labelConfig";
790
791                         new Ajax.Request("backend.php", {
792                                 parameters: query,
793                                 onComplete: function(transport) {
794                                         if (callback) {
795                                                 callback(transport);
796                                         } else if (inPreferences()) {
797                                                 updateLabelList();
798                                         } else {
799                                                 updateFeedList();
800                                         }
801                         } });
802
803                 }
804
805         } catch (e) {
806                 exception_error("addLabel", e);
807         }
808 }
809
810 function quickAddFeed() {
811         try {
812                 var query = "backend.php?op=feeds&method=quickAddFeed";
813
814                 // overlapping widgets
815                 if (dijit.byId("batchSubDlg")) dijit.byId("batchSubDlg").destroyRecursive();
816                 if (dijit.byId("feedAddDlg"))   dijit.byId("feedAddDlg").destroyRecursive();
817
818                 var dialog = new dijit.Dialog({
819                         id: "feedAddDlg",
820                         title: __("Subscribe to Feed"),
821                         style: "width: 600px",
822                         execute: function() {
823                                 if (this.validate()) {
824                                         console.log(dojo.objectToQuery(this.attr('value')));
825
826                                         var feed_url = this.attr('value').feed;
827
828                                         Element.show("feed_add_spinner");
829
830                                         new Ajax.Request("backend.php", {
831                                                 parameters: dojo.objectToQuery(this.attr('value')),
832                                                 onComplete: function(transport) {
833                                                         try {
834
835                                                                 try {
836                                                                         var reply = JSON.parse(transport.responseText);
837                                                                 } catch (e) {
838                                                                         Element.hide("feed_add_spinner");
839                                                                         alert(__("Failed to parse output. This can indicate server timeout and/or network issues. Backend output was logged to browser console."));
840                                                                         console.log('quickAddFeed, backend returned:' + transport.responseText);
841                                                                         return;
842                                                                 }
843
844                                                                 var rc = reply['result'];
845
846                                                                 notify('');
847                                                                 Element.hide("feed_add_spinner");
848
849                                                                 console.log(rc);
850
851                                                                 switch (parseInt(rc['code'])) {
852                                                                 case 1:
853                                                                         dialog.hide();
854                                                                         notify_info(__("Subscribed to %s").replace("%s", feed_url));
855
856                                                                         updateFeedList();
857                                                                         break;
858                                                                 case 2:
859                                                                         alert(__("Specified URL seems to be invalid."));
860                                                                         break;
861                                                                 case 3:
862                                                                         alert(__("Specified URL doesn't seem to contain any feeds."));
863                                                                         break;
864                                                                 case 4:
865                                                                         feeds = rc['feeds'];
866
867                                                                         Element.show("fadd_multiple_notify");
868
869                                                                         var select = dijit.byId("feedDlg_feedContainerSelect");
870
871                                                                         while (select.getOptions().length > 0)
872                                                                                 select.removeOption(0);
873
874                                                                         select.addOption({value: '', label: __("Expand to select feed")});
875
876                                                                         var count = 0;
877                                                                         for (var feedUrl in feeds) {
878                                                                                 select.addOption({value: feedUrl, label: feeds[feedUrl]});
879                                                                                 count++;
880                                                                         }
881
882                                                                         Effect.Appear('feedDlg_feedsContainer', {duration : 0.5});
883
884                                                                         break;
885                                                                 case 5:
886                                                                         alert(__("Couldn't download the specified URL: %s").
887                                                                                         replace("%s", rc['message']));
888                                                                         break;
889                                                                 case 6:
890                                                                         alert(__("XML validation failed: %s").
891                                                                                         replace("%s", rc['message']));
892                                                                         break;
893                                                                         break;
894                                                                 case 0:
895                                                                         alert(__("You are already subscribed to this feed."));
896                                                                         break;
897                                                                 }
898
899                                                         } catch (e) {
900                                                                 exception_error("subscribeToFeed", e, transport);
901                                                         }
902
903                                                 } });
904
905                                         }
906                         },
907                         href: query});
908
909                 dialog.show();
910         } catch (e) {
911                 exception_error("quickAddFeed", e);
912         }
913 }
914
915 function createNewRuleElement(parentNode, replaceNode) {
916         try {
917                 var form = document.forms["filter_new_rule_form"];
918
919                 form.reg_exp.value = form.reg_exp.value.replace(/(<([^>]+)>)/ig,"");
920
921                 var query = "backend.php?op=pref-filters&method=printrulename&rule="+
922                         param_escape(dojo.formToJson(form));
923
924                 console.log(query);
925
926                 new Ajax.Request("backend.php", {
927                         parameters: query,
928                         onComplete: function (transport) {
929                                 try {
930                                         var li = dojo.create("li");
931
932                                         var cb = dojo.create("input", { type: "checkbox" }, li);
933
934                                         new dijit.form.CheckBox({
935                                                 onChange: function() {
936                                                         toggleSelectListRow2(this) },
937                                         }, cb);
938
939                                         dojo.create("input", { type: "hidden",
940                                                 name: "rule[]",
941                                                 value: dojo.formToJson(form) }, li);
942
943                                         dojo.create("span", {
944                                                 onclick: function() {
945                                                         dijit.byId('filterEditDlg').editRule(this);
946                                                 },
947                                                 innerHTML: transport.responseText }, li);
948
949                                         if (replaceNode) {
950                                                 parentNode.replaceChild(li, replaceNode);
951                                         } else {
952                                                 parentNode.appendChild(li);
953                                         }
954                                 } catch (e) {
955                                         exception_error("createNewRuleElement", e);
956                                 }
957                 } });
958         } catch (e) {
959                 exception_error("createNewRuleElement", e);
960         }
961 }
962
963 function createNewActionElement(parentNode, replaceNode) {
964         try {
965                 var form = document.forms["filter_new_action_form"];
966
967                 if (form.action_id.value == 7) {
968                         form.action_param.value = form.action_param_label.value;
969                 }
970
971                 var query = "backend.php?op=pref-filters&method=printactionname&action="+
972                         param_escape(dojo.formToJson(form));
973
974                 console.log(query);
975
976                 new Ajax.Request("backend.php", {
977                         parameters: query,
978                         onComplete: function (transport) {
979                                 try {
980                                         var li = dojo.create("li");
981
982                                         var cb = dojo.create("input", { type: "checkbox" }, li);
983
984                                         new dijit.form.CheckBox({
985                                                 onChange: function() {
986                                                         toggleSelectListRow2(this) },
987                                         }, cb);
988
989                                         dojo.create("input", { type: "hidden",
990                                                 name: "action[]",
991                                                 value: dojo.formToJson(form) }, li);
992
993                                         dojo.create("span", {
994                                                 onclick: function() {
995                                                         dijit.byId('filterEditDlg').editAction(this);
996                                                 },
997                                                 innerHTML: transport.responseText }, li);
998
999                                         if (replaceNode) {
1000                                                 parentNode.replaceChild(li, replaceNode);
1001                                         } else {
1002                                                 parentNode.appendChild(li);
1003                                         }
1004
1005                                 } catch (e) {
1006                                         exception_error("createNewActionElement", e);
1007                                 }
1008                         } });
1009         } catch (e) {
1010                 exception_error("createNewActionElement", e);
1011         }
1012 }
1013
1014
1015 function addFilterRule(replaceNode, ruleStr) {
1016         try {
1017                 if (dijit.byId("filterNewRuleDlg"))
1018                         dijit.byId("filterNewRuleDlg").destroyRecursive();
1019
1020                 var query = "backend.php?op=pref-filters&method=newrule&rule=" +
1021                         param_escape(ruleStr);
1022
1023                 var rule_dlg = new dijit.Dialog({
1024                         id: "filterNewRuleDlg",
1025                         title: ruleStr ? __("Edit rule") : __("Add rule"),
1026                         style: "width: 600px",
1027                         execute: function() {
1028                                 if (this.validate()) {
1029                                         createNewRuleElement($("filterDlg_Matches"), replaceNode);
1030                                         this.hide();
1031                                 }
1032                         },
1033                         href: query});
1034
1035                 rule_dlg.show();
1036         } catch (e) {
1037                 exception_error("addFilterRule", e);
1038         }
1039 }
1040
1041 function addFilterAction(replaceNode, actionStr) {
1042         try {
1043                 if (dijit.byId("filterNewActionDlg"))
1044                         dijit.byId("filterNewActionDlg").destroyRecursive();
1045
1046                 var query = "backend.php?op=pref-filters&method=newaction&action=" +
1047                         param_escape(actionStr);
1048
1049                 var rule_dlg = new dijit.Dialog({
1050                         id: "filterNewActionDlg",
1051                         title: actionStr ? __("Edit action") : __("Add action"),
1052                         style: "width: 600px",
1053                         execute: function() {
1054                                 if (this.validate()) {
1055                                         createNewActionElement($("filterDlg_Actions"), replaceNode);
1056                                         this.hide();
1057                                 }
1058                         },
1059                         href: query});
1060
1061                 rule_dlg.show();
1062         } catch (e) {
1063                 exception_error("addFilterAction", e);
1064         }
1065 }
1066
1067 function quickAddFilter() {
1068         try {
1069                 var query = "";
1070                 if (!inPreferences()) {
1071                         query = "backend.php?op=pref-filters&method=newfilter&feed=" +
1072                                 param_escape(getActiveFeedId()) + "&is_cat=" +
1073                                 param_escape(activeFeedIsCat());
1074                 } else {
1075                         query = "backend.php?op=pref-filters&method=newfilter";
1076                 }
1077
1078                 console.log(query);
1079
1080                 if (dijit.byId("feedEditDlg"))
1081                         dijit.byId("feedEditDlg").destroyRecursive();
1082
1083                 if (dijit.byId("filterEditDlg"))
1084                         dijit.byId("filterEditDlg").destroyRecursive();
1085
1086                 dialog = new dijit.Dialog({
1087                         id: "filterEditDlg",
1088                         title: __("Create Filter"),
1089                         style: "width: 600px",
1090                         test: function() {
1091                                 var query = "backend.php?" + dojo.formToQuery("filter_new_form") + "&savemode=test";
1092
1093                                 if (dijit.byId("filterTestDlg"))
1094                                         dijit.byId("filterTestDlg").destroyRecursive();
1095
1096                                 var test_dlg = new dijit.Dialog({
1097                                         id: "filterTestDlg",
1098                                         title: "Test Filter",
1099                                         style: "width: 600px",
1100                                         href: query});
1101
1102                                 test_dlg.show();
1103                         },
1104                         selectRules: function(select) {
1105                                 $$("#filterDlg_Matches input[type=checkbox]").each(function(e) {
1106                                         e.checked = select;
1107                                         if (select)
1108                                                 e.parentNode.addClassName("Selected");
1109                                         else
1110                                                 e.parentNode.removeClassName("Selected");
1111                                 });
1112                         },
1113                         selectActions: function(select) {
1114                                 $$("#filterDlg_Actions input[type=checkbox]").each(function(e) {
1115                                         e.checked = select;
1116
1117                                         if (select)
1118                                                 e.parentNode.addClassName("Selected");
1119                                         else
1120                                                 e.parentNode.removeClassName("Selected");
1121
1122                                 });
1123                         },
1124                         editRule: function(e) {
1125                                 var li = e.parentNode;
1126                                 var rule = li.getElementsByTagName("INPUT")[1].value;
1127                                 addFilterRule(li, rule);
1128                         },
1129                         editAction: function(e) {
1130                                 var li = e.parentNode;
1131                                 var action = li.getElementsByTagName("INPUT")[1].value;
1132                                 addFilterAction(li, action);
1133                         },
1134                         addAction: function() { addFilterAction(); },
1135                         addRule: function() { addFilterRule(); },
1136                         deleteAction: function() {
1137                                 $$("#filterDlg_Actions li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1138                         },
1139                         deleteRule: function() {
1140                                 $$("#filterDlg_Matches li.[class*=Selected]").each(function(e) { e.parentNode.removeChild(e) });
1141                         },
1142                         execute: function() {
1143                                 if (this.validate()) {
1144
1145                                         var query = dojo.formToQuery("filter_new_form");
1146
1147                                         console.log(query);
1148
1149                                         new Ajax.Request("backend.php", {
1150                                                 parameters: query,
1151                                                 onComplete: function (transport) {
1152                                                         if (inPreferences()) {
1153                                                                 updateFilterList();
1154                                                         }
1155
1156                                                         dialog.hide();
1157                                         } });
1158                                 }
1159                         },
1160                         href: query});
1161
1162                 if (!inPreferences()) {
1163                         var selectedText = getSelectionText();
1164
1165                         var lh = dojo.connect(dialog, "onLoad", function(){
1166                                 dojo.disconnect(lh);
1167
1168                                 if (selectedText != "") {
1169
1170                                         var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1171                                                 getActiveFeedId();
1172
1173                                         var rule = { reg_exp: selectedText, feed_id: feed_id, filter_type: 1 };
1174
1175                                         addFilterRule(null, dojo.toJson(rule));
1176
1177                                 } else {
1178
1179                                         var query = "op=rpc&method=getlinktitlebyid&id=" + getActiveArticleId();
1180
1181                                         new Ajax.Request("backend.php", {
1182                                         parameters: query,
1183                                         onComplete: function(transport) {
1184                                                 var reply = JSON.parse(transport.responseText);
1185
1186                                                 var title = false;
1187
1188                                                 if (reply && reply) title = reply.title;
1189
1190                                                 if (title || getActiveFeedId() || activeFeedIsCat()) {
1191
1192                                                         console.log(title + " " + getActiveFeedId());
1193
1194                                                         var feed_id = activeFeedIsCat() ? 'CAT:' + parseInt(getActiveFeedId()) :
1195                                                                 getActiveFeedId();
1196
1197                                                         var rule = { reg_exp: title, feed_id: feed_id, filter_type: 1 };
1198
1199                                                         addFilterRule(null, dojo.toJson(rule));
1200                                                 }
1201
1202                                         } });
1203
1204                                 }
1205
1206                         });
1207                 }
1208
1209                 dialog.show();
1210
1211         } catch (e) {
1212                 exception_error("quickAddFilter", e);
1213         }
1214 }
1215
1216 function resetPubSub(feed_id, title) {
1217
1218         var msg = __("Reset subscription? Tiny Tiny RSS will try to subscribe to the notification hub again on next feed update.").replace("%s", title);
1219
1220         if (title == undefined || confirm(msg)) {
1221                 notify_progress("Loading, please wait...");
1222
1223                 var query = "?op=pref-feeds&quiet=1&method=resetPubSub&ids=" + feed_id;
1224
1225                 new Ajax.Request("backend.php", {
1226                         parameters: query,
1227                         onComplete: function(transport) {
1228                                 dijit.byId("pubsubReset_Btn").attr('disabled', true);
1229                                 notify_info("Subscription reset.");
1230                         } });
1231         }
1232
1233         return false;
1234 }
1235
1236
1237 function unsubscribeFeed(feed_id, title) {
1238
1239         var msg = __("Unsubscribe from %s?").replace("%s", title);
1240
1241         if (title == undefined || confirm(msg)) {
1242                 notify_progress("Removing feed...");
1243
1244                 var query = "?op=pref-feeds&quiet=1&method=remove&ids=" + feed_id;
1245
1246                 new Ajax.Request("backend.php", {
1247                         parameters: query,
1248                         onComplete: function(transport) {
1249
1250                                         if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1251
1252                                         if (inPreferences()) {
1253                                                 updateFeedList();
1254                                         } else {
1255                                                 if (feed_id == getActiveFeedId())
1256                                                         setTimeout("viewfeed(-5)", 100);
1257
1258                                                 if (feed_id < 0) updateFeedList();
1259                                         }
1260
1261                                 } });
1262         }
1263
1264         return false;
1265 }
1266
1267
1268 function backend_sanity_check_callback(transport) {
1269
1270         try {
1271
1272                 if (sanity_check_done) {
1273                         fatalError(11, "Sanity check request received twice. This can indicate "+
1274                       "presence of Firebug or some other disrupting extension. "+
1275                                 "Please disable it and try again.");
1276                         return;
1277                 }
1278
1279                 var reply = JSON.parse(transport.responseText);
1280
1281                 if (!reply) {
1282                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1283                         return;
1284                 }
1285
1286                 var error_code = reply['error']['code'];
1287
1288                 if (error_code && error_code != 0) {
1289                         return fatalError(error_code, reply['error']['message']);
1290                 }
1291
1292                 console.log("sanity check ok");
1293
1294                 var params = reply['init-params'];
1295
1296                 if (params) {
1297                         console.log('reading init-params...');
1298
1299                         for (k in params) {
1300                                 console.log("IP: " + k + " => " + JSON.stringify(params[k]));
1301                                 if (k == "label_base_index") _label_base_index = parseInt(params[k]);
1302                         }
1303
1304                         init_params = params;
1305
1306                         // PluginHost might not be available on non-index pages
1307                         window.PluginHost && PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, init_params);
1308                 }
1309
1310                 sanity_check_done = true;
1311
1312                 init_second_stage();
1313
1314         } catch (e) {
1315                 exception_error("backend_sanity_check_callback", e, transport);
1316         }
1317 }
1318
1319 /*function has_local_storage() {
1320         try {
1321                 return 'sessionStorage' in window && window['sessionStorage'] != null;
1322         } catch (e) {
1323                 return false;
1324         }
1325 } */
1326
1327 function catSelectOnChange(elem) {
1328         try {
1329 /*              var value = elem[elem.selectedIndex].value;
1330                 var def = elem.getAttribute('default');
1331
1332                 if (value == "ADD_CAT") {
1333
1334                         if (def)
1335                                 dropboxSelect(elem, def);
1336                         else
1337                                 elem.selectedIndex = 0;
1338
1339                         quickAddCat(elem);
1340                 } */
1341
1342         } catch (e) {
1343                 exception_error("catSelectOnChange", e);
1344         }
1345 }
1346
1347 function quickAddCat(elem) {
1348         try {
1349                 var cat = prompt(__("Please enter category title:"));
1350
1351                 if (cat) {
1352
1353                         var query = "?op=rpc&method=quickAddCat&cat=" + param_escape(cat);
1354
1355                         notify_progress("Loading, please wait...", true);
1356
1357                         new Ajax.Request("backend.php", {
1358                                 parameters: query,
1359                                 onComplete: function (transport) {
1360                                         var response = transport.responseXML;
1361                                         var select = response.getElementsByTagName("select")[0];
1362                                         var options = select.getElementsByTagName("option");
1363
1364                                         dropbox_replace_options(elem, options);
1365
1366                                         notify('');
1367
1368                         } });
1369
1370                 }
1371
1372         } catch (e) {
1373                 exception_error("quickAddCat", e);
1374         }
1375 }
1376
1377 function genUrlChangeKey(feed, is_cat) {
1378
1379         try {
1380                 var ok = confirm(__("Generate new syndication address for this feed?"));
1381
1382                 if (ok) {
1383
1384                         notify_progress("Trying to change address...", true);
1385
1386                         var query = "?op=pref-feeds&method=regenFeedKey&id=" + param_escape(feed) +
1387                                 "&is_cat=" + param_escape(is_cat);
1388
1389                         new Ajax.Request("backend.php", {
1390                                 parameters: query,
1391                                 onComplete: function(transport) {
1392                                                 var reply = JSON.parse(transport.responseText);
1393                                                 var new_link = reply.link;
1394
1395                                                 var e = $('gen_feed_url');
1396
1397                                                 if (new_link) {
1398
1399                                                         e.innerHTML = e.innerHTML.replace(/\&amp;key=.*$/,
1400                                                                 "&amp;key=" + new_link);
1401
1402                                                         e.href = e.href.replace(/\&key=.*$/,
1403                                                                 "&key=" + new_link);
1404
1405                                                         new Effect.Highlight(e);
1406
1407                                                         notify('');
1408
1409                                                 } else {
1410                                                         notify_error("Could not change feed URL.");
1411                                                 }
1412                                 } });
1413                 }
1414         } catch (e) {
1415                 exception_error("genUrlChangeKey", e);
1416         }
1417         return false;
1418 }
1419
1420 function labelSelectOnChange(elem) {
1421         try {
1422 /*              var value = elem[elem.selectedIndex].value;
1423                 var def = elem.getAttribute('default');
1424
1425                 if (value == "ADD_LABEL") {
1426
1427                         if (def)
1428                                 dropboxSelect(elem, def);
1429                         else
1430                                 elem.selectedIndex = 0;
1431
1432                         addLabel(elem, function(transport) {
1433
1434                                         try {
1435
1436                                                 var response = transport.responseXML;
1437                                                 var select = response.getElementsByTagName("select")[0];
1438                                                 var options = select.getElementsByTagName("option");
1439
1440                                                 dropbox_replace_options(elem, options);
1441
1442                                                 notify('');
1443                                         } catch (e) {
1444                                                 exception_error("addLabel", e);
1445                                         }
1446                         });
1447                 } */
1448
1449         } catch (e) {
1450                 exception_error("labelSelectOnChange", e);
1451         }
1452 }
1453
1454 function dropbox_replace_options(elem, options) {
1455
1456         try {
1457                 while (elem.hasChildNodes())
1458                         elem.removeChild(elem.firstChild);
1459
1460                 var sel_idx = -1;
1461
1462                 for (var i = 0; i < options.length; i++) {
1463                         var text = options[i].firstChild.nodeValue;
1464                         var value = options[i].getAttribute("value");
1465
1466                         if (value == undefined) value = text;
1467
1468                         var issel = options[i].getAttribute("selected") == "1";
1469
1470                         var option = new Option(text, value, issel);
1471
1472                         if (options[i].getAttribute("disabled"))
1473                                 option.setAttribute("disabled", true);
1474
1475                         elem.insert(option);
1476
1477                         if (issel) sel_idx = i;
1478                 }
1479
1480                 // Chrome doesn't seem to just select stuff when you pass new Option(x, y, true)
1481                 if (sel_idx >= 0) elem.selectedIndex = sel_idx;
1482
1483         } catch (e) {
1484                 exception_error("dropbox_replace_options", e);
1485         }
1486 }
1487
1488 // mode = all, none, invert
1489 function selectTableRows(id, mode) {
1490         try {
1491                 var rows = $(id).rows;
1492
1493                 for (var i = 0; i < rows.length; i++) {
1494                         var row = rows[i];
1495                         var cb = false;
1496                         var dcb = false;
1497
1498                         if (row.id && row.className) {
1499                                 var bare_id = row.id.replace(/^[A-Z]*?-/, "");
1500                                 var inputs = rows[i].getElementsByTagName("input");
1501
1502                                 for (var j = 0; j < inputs.length; j++) {
1503                                         var input = inputs[j];
1504
1505                                         if (input.getAttribute("type") == "checkbox" &&
1506                                                         input.id.match(bare_id)) {
1507
1508                                                 cb = input;
1509                                                 dcb = dijit.getEnclosingWidget(cb);
1510                                                 break;
1511                                         }
1512                                 }
1513
1514                                 if (cb || dcb) {
1515                                         var issel = row.hasClassName("Selected");
1516
1517                                         if (mode == "all" && !issel) {
1518                                                 row.addClassName("Selected");
1519                                                 cb.checked = true;
1520                                                 if (dcb) dcb.set("checked", true);
1521                                         } else if (mode == "none" && issel) {
1522                                                 row.removeClassName("Selected");
1523                                                 cb.checked = false;
1524                                                 if (dcb) dcb.set("checked", false);
1525
1526                                         } else if (mode == "invert") {
1527
1528                                                 if (issel) {
1529                                                         row.removeClassName("Selected");
1530                                                         cb.checked = false;
1531                                                         if (dcb) dcb.set("checked", false);
1532                                                 } else {
1533                                                         row.addClassName("Selected");
1534                                                         cb.checked = true;
1535                                                         if (dcb) dcb.set("checked", true);
1536                                                 }
1537                                         }
1538                                 }
1539                         }
1540                 }
1541
1542         } catch (e) {
1543                 exception_error("selectTableRows", e);
1544
1545         }
1546 }
1547
1548 function getSelectedTableRowIds(id) {
1549         var rows = [];
1550
1551         try {
1552                 var elem_rows = $(id).rows;
1553
1554                 for (var i = 0; i < elem_rows.length; i++) {
1555                         if (elem_rows[i].hasClassName("Selected")) {
1556                                 var bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1557                                 rows.push(bare_id);
1558                         }
1559                 }
1560
1561         } catch (e) {
1562                 exception_error("getSelectedTableRowIds", e);
1563         }
1564
1565         return rows;
1566 }
1567
1568 function editFeed(feed, event) {
1569         try {
1570                 if (feed <= 0)
1571                         return alert(__("You can't edit this kind of feed."));
1572
1573                 var query = "backend.php?op=pref-feeds&method=editfeed&id=" +
1574                         param_escape(feed);
1575
1576                 console.log(query);
1577
1578                 if (dijit.byId("filterEditDlg"))
1579                         dijit.byId("filterEditDlg").destroyRecursive();
1580
1581                 if (dijit.byId("feedEditDlg"))
1582                         dijit.byId("feedEditDlg").destroyRecursive();
1583
1584                 dialog = new dijit.Dialog({
1585                         id: "feedEditDlg",
1586                         title: __("Edit Feed"),
1587                         style: "width: 600px",
1588                         execute: function() {
1589                                 if (this.validate()) {
1590 //                                      console.log(dojo.objectToQuery(this.attr('value')));
1591
1592                                         notify_progress("Saving data...", true);
1593
1594                                         new Ajax.Request("backend.php", {
1595                                                 parameters: dojo.objectToQuery(dialog.attr('value')),
1596                                                 onComplete: function(transport) {
1597                                                         dialog.hide();
1598                                                         notify('');
1599                                                         updateFeedList();
1600                                         }});
1601                                 }
1602                         },
1603                         href: query});
1604
1605                 dialog.show();
1606
1607         } catch (e) {
1608                 exception_error("editFeed", e);
1609         }
1610 }
1611
1612 function feedBrowser() {
1613         try {
1614                 var query = "backend.php?op=feeds&method=feedBrowser";
1615
1616                 if (dijit.byId("feedAddDlg"))
1617                         dijit.byId("feedAddDlg").hide();
1618
1619                 if (dijit.byId("feedBrowserDlg"))
1620                         dijit.byId("feedBrowserDlg").destroyRecursive();
1621
1622                 var dialog = new dijit.Dialog({
1623                         id: "feedBrowserDlg",
1624                         title: __("More Feeds"),
1625                         style: "width: 600px",
1626                         getSelectedFeedIds: function() {
1627                                 var list = $$("#browseFeedList li[id*=FBROW]");
1628                                 var selected = new Array();
1629
1630                                 list.each(function(child) {
1631                                         var id = child.id.replace("FBROW-", "");
1632
1633                                         if (child.hasClassName('Selected')) {
1634                                                 selected.push(id);
1635                                         }
1636                                 });
1637
1638                                 return selected;
1639                         },
1640                         getSelectedFeeds: function() {
1641                                 var list = $$("#browseFeedList li.Selected");
1642                                 var selected = new Array();
1643
1644                                 list.each(function(child) {
1645                                         var title = child.getElementsBySelector("span.fb_feedTitle")[0].innerHTML;
1646                                         var url = child.getElementsBySelector("a.fb_feedUrl")[0].href;
1647
1648                                         selected.push([title,url]);
1649
1650                                 });
1651
1652                                 return selected;
1653                         },
1654
1655                         subscribe: function() {
1656                                 var mode = this.attr('value').mode;
1657                                 var selected = [];
1658
1659                                 if (mode == "1")
1660                                         selected = this.getSelectedFeeds();
1661                                 else
1662                                         selected = this.getSelectedFeedIds();
1663
1664                                 if (selected.length > 0) {
1665                                         dijit.byId("feedBrowserDlg").hide();
1666
1667                                         notify_progress("Loading, please wait...", true);
1668
1669                                         // we use dojo.toJson instead of JSON.stringify because
1670                                         // it somehow escapes everything TWICE, at least in Chrome 9
1671
1672                                         var query = "?op=rpc&method=massSubscribe&payload="+
1673                                                 param_escape(dojo.toJson(selected)) + "&mode=" + param_escape(mode);
1674
1675                                         console.log(query);
1676
1677                                         new Ajax.Request("backend.php", {
1678                                                 parameters: query,
1679                                                 onComplete: function(transport) {
1680                                                         notify('');
1681                                                         updateFeedList();
1682                                                 } });
1683
1684                                 } else {
1685                                         alert(__("No feeds are selected."));
1686                                 }
1687
1688                         },
1689                         update: function() {
1690                                 var query = dojo.objectToQuery(dialog.attr('value'));
1691
1692                                 Element.show('feed_browser_spinner');
1693
1694                                 new Ajax.Request("backend.php", {
1695                                         parameters: query,
1696                                         onComplete: function(transport) {
1697                                                 notify('');
1698
1699                                                 Element.hide('feed_browser_spinner');
1700
1701                                                 var c = $("browseFeedList");
1702
1703                                                 var reply = JSON.parse(transport.responseText);
1704
1705                                                 var r = reply['content'];
1706                                                 var mode = reply['mode'];
1707
1708                                                 if (c && r) {
1709                                                         c.innerHTML = r;
1710                                                 }
1711
1712                                                 dojo.parser.parse("browseFeedList");
1713
1714                                                 if (mode == 2) {
1715                                                         Element.show(dijit.byId('feed_archive_remove').domNode);
1716                                                 } else {
1717                                                         Element.hide(dijit.byId('feed_archive_remove').domNode);
1718                                                 }
1719
1720                                         } });
1721                         },
1722                         removeFromArchive: function() {
1723                                 var selected = this.getSelectedFeedIds();
1724
1725                                 if (selected.length > 0) {
1726
1727                                         var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1728
1729                                         if (confirm(pr)) {
1730                                                 Element.show('feed_browser_spinner');
1731
1732                                                 var query = "?op=rpc&method=remarchive&ids=" +
1733                                                         param_escape(selected.toString());;
1734
1735                                                 new Ajax.Request("backend.php", {
1736                                                         parameters: query,
1737                                                         onComplete: function(transport) {
1738                                                                 dialog.update();
1739                                                         } });
1740                                         }
1741                                 }
1742                         },
1743                         execute: function() {
1744                                 if (this.validate()) {
1745                                         this.subscribe();
1746                                 }
1747                         },
1748                         href: query});
1749
1750                 dialog.show();
1751
1752         } catch (e) {
1753                 exception_error("editFeed", e);
1754         }
1755 }
1756
1757 function showFeedsWithErrors() {
1758         try {
1759                 var query = "backend.php?op=pref-feeds&method=feedsWithErrors";
1760
1761                 if (dijit.byId("errorFeedsDlg"))
1762                         dijit.byId("errorFeedsDlg").destroyRecursive();
1763
1764                 dialog = new dijit.Dialog({
1765                         id: "errorFeedsDlg",
1766                         title: __("Feeds with update errors"),
1767                         style: "width: 600px",
1768                         getSelectedFeeds: function() {
1769                                 return getSelectedTableRowIds("prefErrorFeedList");
1770                         },
1771                         removeSelected: function() {
1772                                 var sel_rows = this.getSelectedFeeds();
1773
1774                                 console.log(sel_rows);
1775
1776                                 if (sel_rows.length > 0) {
1777                                         var ok = confirm(__("Remove selected feeds?"));
1778
1779                                         if (ok) {
1780                                                 notify_progress("Removing selected feeds...", true);
1781
1782                                                 var query = "?op=pref-feeds&method=remove&ids="+
1783                                                         param_escape(sel_rows.toString());
1784
1785                                                 new Ajax.Request("backend.php", {
1786                                                         parameters: query,
1787                                                         onComplete: function(transport) {
1788                                                                 notify('');
1789                                                                 dialog.hide();
1790                                                                 updateFeedList();
1791                                                         } });
1792                                         }
1793
1794                                 } else {
1795                                         alert(__("No feeds are selected."));
1796                                 }
1797                         },
1798                         execute: function() {
1799                                 if (this.validate()) {
1800                                 }
1801                         },
1802                         href: query});
1803
1804                 dialog.show();
1805
1806         } catch (e) {
1807                 exception_error("showFeedsWithErrors", e);
1808         }
1809
1810 }
1811
1812 /* new support functions for SelectByTag */
1813
1814 function get_all_tags(selObj){
1815         try {
1816                 if( !selObj ) return "";
1817
1818                 var result = "";
1819                 var len = selObj.options.length;
1820
1821                 for (var i=0; i < len; i++){
1822                         if (selObj.options[i].selected) {
1823                                 result += selObj[i].value + "%2C";   // is really a comma
1824                         }
1825                 }
1826
1827                 if (result.length > 0){
1828                         result = result.substr(0, result.length-3);  // remove trailing %2C
1829                 }
1830
1831                 return(result);
1832
1833         } catch (e) {
1834                 exception_error("get_all_tags", e);
1835         }
1836 }
1837
1838 function get_radio_checked(radioObj) {
1839         try {
1840                 if (!radioObj) return "";
1841
1842                 var len = radioObj.length;
1843
1844                 if (len == undefined){
1845                         if(radioObj.checked){
1846                                 return(radioObj.value);
1847                         } else {
1848                                 return("");
1849                         }
1850                 }
1851
1852                 for( var i=0; i < len; i++ ){
1853                         if( radioObj[i].checked ){
1854                                 return( radioObj[i].value);
1855                         }
1856                 }
1857
1858         } catch (e) {
1859                 exception_error("get_radio_checked", e);
1860         }
1861         return("");
1862 }
1863
1864 function get_timestamp() {
1865         var date = new Date();
1866         return Math.round(date.getTime() / 1000);
1867 }
1868
1869 function helpDialog(topic) {
1870         try {
1871                 var query = "backend.php?op=backend&method=help&topic=" + param_escape(topic);
1872
1873                 if (dijit.byId("helpDlg"))
1874                         dijit.byId("helpDlg").destroyRecursive();
1875
1876                 dialog = new dijit.Dialog({
1877                         id: "helpDlg",
1878                         title: __("Help"),
1879                         style: "width: 600px",
1880                         href: query,
1881                 });
1882
1883                 dialog.show();
1884
1885         } catch (e) {
1886                 exception_error("helpDialog", e);
1887         }
1888 }
1889
1890 function htmlspecialchars_decode (string, quote_style) {
1891   // http://kevin.vanzonneveld.net
1892   // +   original by: Mirek Slugen
1893   // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1894   // +   bugfixed by: Mateusz "loonquawl" Zalega
1895   // +      input by: ReverseSyntax
1896   // +      input by: Slawomir Kaniecki
1897   // +      input by: Scott Cariss
1898   // +      input by: Francois
1899   // +   bugfixed by: Onno Marsman
1900   // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
1901   // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
1902   // +      input by: Ratheous
1903   // +      input by: Mailfaker (http://www.weedem.fr/)
1904   // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
1905   // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
1906   // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
1907   // *     returns 1: '<p>this -> &quot;</p>'
1908   // *     example 2: htmlspecialchars_decode("&amp;quot;");
1909   // *     returns 2: '&quot;'
1910   var optTemp = 0,
1911     i = 0,
1912     noquotes = false;
1913   if (typeof quote_style === 'undefined') {
1914     quote_style = 2;
1915   }
1916   string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
1917   var OPTS = {
1918     'ENT_NOQUOTES': 0,
1919     'ENT_HTML_QUOTE_SINGLE': 1,
1920     'ENT_HTML_QUOTE_DOUBLE': 2,
1921     'ENT_COMPAT': 2,
1922     'ENT_QUOTES': 3,
1923     'ENT_IGNORE': 4
1924   };
1925   if (quote_style === 0) {
1926     noquotes = true;
1927   }
1928   if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
1929     quote_style = [].concat(quote_style);
1930     for (i = 0; i < quote_style.length; i++) {
1931       // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
1932       if (OPTS[quote_style[i]] === 0) {
1933         noquotes = true;
1934       } else if (OPTS[quote_style[i]]) {
1935         optTemp = optTemp | OPTS[quote_style[i]];
1936       }
1937     }
1938     quote_style = optTemp;
1939   }
1940   if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
1941     string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
1942     // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
1943   }
1944   if (!noquotes) {
1945     string = string.replace(/&quot;/g, '"');
1946   }
1947   // Put this in last place to avoid escape being double-decoded
1948   string = string.replace(/&amp;/g, '&');
1949
1950   return string;
1951 }
1952
1953
1954 function label_to_feed_id(label) {
1955         return _label_base_index - 1 - Math.abs(label);
1956 }
1957
1958 function feed_to_label_id(feed) {
1959         return _label_base_index - 1 + Math.abs(feed);
1960 }
1961
1962 // http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac
1963
1964 function getSelectionText() {
1965         var text = "";
1966
1967         if (typeof window.getSelection != "undefined") {
1968                 var sel = window.getSelection();
1969                 if (sel.rangeCount) {
1970                         var container = document.createElement("div");
1971                         for (var i = 0, len = sel.rangeCount; i < len; ++i) {
1972                                 container.appendChild(sel.getRangeAt(i).cloneContents());
1973                         }
1974                         text = container.innerHTML;
1975                 }
1976         } else if (typeof document.selection != "undefined") {
1977                 if (document.selection.type == "Text") {
1978                         text = document.selection.createRange().textText;
1979                 }
1980         }
1981
1982         return text.stripTags();
1983 }