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