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