]> git.wh0rd.org Git - tt-rss.git/blob - functions.js
simplify adding/removing labels manually; simplify headline popup menu
[tt-rss.git] / functions.js
1 var notify_silent = false;
2 var loading_progress = 0;
3 var sanity_check_done = false;
4
5 /* add method to remove element from array */
6
7 Array.prototype.remove = function(s) {
8         for (var i=0; i < this.length; i++) {
9                 if (s == this[i]) this.splice(i, 1);
10         }
11 }
12
13 /* create console.log if it doesn't exist */
14
15 if (!window.console) console = {};
16 console.log = console.log || function(msg) { };
17 console.warn = console.warn || function(msg) { };
18 console.error = console.error || function(msg) { };
19
20 function exception_error(location, e, ext_info) {
21         var msg = format_exception_error(location, e);
22
23         if (!ext_info) ext_info = false;
24
25         try {
26
27                 if (ext_info) {
28                         if (ext_info.responseText) {
29                                 ext_info = ext_info.responseText;
30                         }
31                 }
32
33                 var content = "<div class=\"fatalError\">" +
34                         "<pre>" + msg + "</pre>";
35
36                 if (ext_info) {
37                         content += "<div><b>Additional information:</b></div>" +
38                         "<textarea readonly=\"1\">" + ext_info + "</textarea>";
39                 }
40
41                 content += "<div><b>Stack trace:</b></div>" +
42                         "<textarea readonly=\"1\">" + e.stack + "</textarea>";
43
44                 content += "</div>";
45
46                 content += "<div class='dlgButtons'>";
47
48                 content += "<button dojoType=\"dijit.form.Button\""+
49                                 "onclick=\"dijit.byId('exceptionDlg').report()\">" +
50                                 __('Report to tt-rss.org') + "</button> ";
51                 content += "<button dojoType=\"dijit.form.Button\" "+
52                                 "onclick=\"dijit.byId('exceptionDlg').hide()\">" + 
53                                 __('Close') + "</button>";
54                 content += "</div>";
55
56
57                 var dialog = new dijit.Dialog({
58                         id: "exceptionDlg",
59                         title: "Unhandled exception",
60                         style: "width: 600px",
61                         report: function() {
62                                 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."))) {
63
64                                         var params = $H({
65                                                 message: msg,
66                                                 xinfo: ext_info,
67                                                 stack: e.stack,         
68                                                 browserName: navigator.appName,
69                                                 browserVersion: navigator.appVersion,
70                                                 browserPlatform: navigator.platform,
71                                                 browserCookies: navigator.cookieEnabled,
72                                         });
73
74                                         var url = "http://tt-rss.org/report.php?" + params.toQueryString();
75
76                                         window.open(url);
77
78                                 }
79                         },
80                         content: content});
81
82                 dialog.show();
83
84         } catch (e) {
85                 alert(msg);
86         }
87
88 }
89
90 function format_exception_error(location, e) {
91         var msg;
92
93         if (e.fileName) {
94                 var base_fname = e.fileName.substring(e.fileName.lastIndexOf("/") + 1);
95         
96                 msg = "Exception: " + e.name + ", " + e.message + 
97                         "\nFunction: " + location + "()" +
98                         "\nLocation: " + base_fname + ":" + e.lineNumber;
99
100         } else if (e.description) {
101                 msg = "Exception: " + e.description + "\nFunction: " + location + "()";
102         } else {
103                 msg = "Exception: " + e + "\nFunction: " + location + "()";
104         }
105
106         console.error("EXCEPTION: " + msg);
107
108         return msg;
109 }
110
111 function param_escape(arg) {
112         if (typeof encodeURIComponent != 'undefined')
113                 return encodeURIComponent(arg); 
114         else
115                 return escape(arg);
116 }
117
118 function param_unescape(arg) {
119         if (typeof decodeURIComponent != 'undefined')
120                 return decodeURIComponent(arg); 
121         else
122                 return unescape(arg);
123 }
124
125 var notify_hide_timerid = false;
126
127 function hide_notify() {
128         var n = $("notify");
129         if (n) {
130                 n.style.display = "none";
131         }
132
133
134 function notify_silent_next() {
135         notify_silent = true;
136 }
137
138 function notify_real(msg, no_hide, n_type) {
139
140         if (notify_silent) {
141                 notify_silent = false;
142                 return;
143         }
144
145         var n = $("notify");
146         var nb = $("notify_body");
147
148         if (!n || !nb) return;
149
150         if (notify_hide_timerid) {
151                 window.clearTimeout(notify_hide_timerid);
152         }
153
154         if (msg == "") {
155                 if (n.style.display == "block") {
156                         notify_hide_timerid = window.setTimeout("hide_notify()", 0);
157                 }
158                 return;
159         } else {
160                 n.style.display = "block";
161         }
162
163         /* types:
164
165                 1 - generic
166                 2 - progress
167                 3 - error
168                 4 - info
169
170         */
171
172         if (typeof __ != 'undefined') {
173                 msg = __(msg);
174         }
175
176         if (n_type == 1) {
177                 n.className = "notify";
178         } else if (n_type == 2) {
179                 n.className = "notifyProgress";
180                 msg = "<img src='"+getInitParam("sign_progress")+"'> " + msg;
181         } else if (n_type == 3) {
182                 n.className = "notifyError";
183                 msg = "<img src='"+getInitParam("sign_excl")+"'> " + msg;
184         } else if (n_type == 4) {
185                 n.className = "notifyInfo";
186                 msg = "<img src='"+getInitParam("sign_info")+"'> " + msg;
187         }
188
189 //      msg = "<img src='images/live_com_loading.gif'> " + msg;
190
191         nb.innerHTML = msg;
192
193         if (!no_hide) {
194                 notify_hide_timerid = window.setTimeout("hide_notify()", 3000);
195         }
196 }
197
198 function notify(msg, no_hide) {
199         notify_real(msg, no_hide, 1);
200 }
201
202 function notify_progress(msg, no_hide) {
203         notify_real(msg, no_hide, 2);
204 }
205
206 function notify_error(msg, no_hide) {
207         notify_real(msg, no_hide, 3);
208
209 }
210
211 function notify_info(msg, no_hide) {
212         notify_real(msg, no_hide, 4);
213 }
214
215 function setCookie(name, value, lifetime, path, domain, secure) {
216         
217         var d = false;
218         
219         if (lifetime) {
220                 d = new Date();
221                 d.setTime(d.getTime() + (lifetime * 1000));
222         }
223
224         console.log("setCookie: " + name + " => " + value + ": " + d);
225         
226         int_setCookie(name, value, d, path, domain, secure);
227
228 }
229
230 function int_setCookie(name, value, expires, path, domain, secure) {
231         document.cookie= name + "=" + escape(value) +
232                 ((expires) ? "; expires=" + expires.toGMTString() : "") +
233                 ((path) ? "; path=" + path : "") +
234                 ((domain) ? "; domain=" + domain : "") +
235                 ((secure) ? "; secure" : "");
236 }
237
238 function delCookie(name, path, domain) {
239         if (getCookie(name)) {
240                 document.cookie = name + "=" +
241                 ((path) ? ";path=" + path : "") +
242                 ((domain) ? ";domain=" + domain : "" ) +
243                 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
244         }
245 }
246                 
247
248 function getCookie(name) {
249
250         var dc = document.cookie;
251         var prefix = name + "=";
252         var begin = dc.indexOf("; " + prefix);
253         if (begin == -1) {
254             begin = dc.indexOf(prefix);
255             if (begin != 0) return null;
256         }
257         else {
258             begin += 2;
259         }
260         var end = document.cookie.indexOf(";", begin);
261         if (end == -1) {
262             end = dc.length;
263         }
264         return unescape(dc.substring(begin + prefix.length, end));
265 }
266
267 function gotoPreferences() {
268         document.location.href = "prefs.php";
269 }
270
271 function gotoMain() {
272         document.location.href = "tt-rss.php";
273 }
274
275 function gotoExportOpml() {
276         document.location.href = "opml.php?op=Export";
277 }
278
279
280 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
281   * * @author Sundar Dorai-Raj
282   * * Email: sdoraira@vt.edu
283   * * This program is free software; you can redistribute it and/or
284   * * modify it under the terms of the GNU General Public License 
285   * * as published by the Free Software Foundation; either version 2 
286   * * of the License, or (at your option) any later version, 
287   * * provided that any use properly credits the author. 
288   * * This program is distributed in the hope that it will be useful,
289   * * but WITHOUT ANY WARRANTY; without even the implied warranty of
290   * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
291   * * GNU General Public License for more details at http://www.gnu.org * * */
292
293   var numbers=".0123456789";
294   function isNumeric(x) {
295     // is x a String or a character?
296     if(x.length>1) {
297       // remove negative sign
298       x=Math.abs(x)+"";
299       for(j=0;j<x.length;j++) {
300         // call isNumeric recursively for each character
301         number=isNumeric(x.substring(j,j+1));
302         if(!number) return number;
303       }
304       return number;
305     }
306     else {
307       // if x is number return true
308       if(numbers.indexOf(x)>=0) return true;
309       return false;
310     }
311   }
312
313
314 function toggleSelectRowById(sender, id) {
315         var row = $(id);
316         return toggleSelectRow(sender, row);
317 }
318
319 function toggleSelectListRow(sender) {
320         var row = sender.parentNode;
321         return toggleSelectRow(sender, row);
322 }
323
324 /* this is for dijit Checkbox */
325 function toggleSelectListRow2(sender) {
326         var row = sender.domNode.parentNode;
327         return toggleSelectRow(sender, row);
328 }
329
330 function tSR(sender, row) {
331         return toggleSelectRow(sender, row);
332 }
333
334 /* this is for dijit Checkbox */
335 function toggleSelectRow2(sender, row) {
336
337         if (!row) row = sender.domNode.parentNode.parentNode;
338
339         if (sender.checked && !row.hasClassName('Selected'))
340                 row.addClassName('Selected');
341         else
342                 row.removeClassName('Selected');
343 }
344
345
346 function toggleSelectRow(sender, row) {
347
348         if (!row) row = sender.parentNode.parentNode;
349
350         if (sender.checked && !row.hasClassName('Selected'))
351                 row.addClassName('Selected');
352         else
353                 row.removeClassName('Selected');
354 }
355
356 function checkboxToggleElement(elem, id) {
357         if (elem.checked) {
358                 Effect.Appear(id, {duration : 0.5});
359         } else {
360                 Effect.Fade(id, {duration : 0.5});
361         }
362 }
363
364 function dropboxSelect(e, v) {
365         for (i = 0; i < e.length; i++) {
366                 if (e[i].value == v) {
367                         e.selectedIndex = i;
368                         break;
369                 }
370         }
371 }
372
373 // originally stolen from http://www.11tmr.com/11tmr.nsf/d6plinks/MWHE-695L9Z
374 // bugfixed just a little bit :-)
375 function getURLParam(strParamName){
376   var strReturn = "";
377   var strHref = window.location.href;
378
379   if (strHref.indexOf("#") == strHref.length-1) {
380                 strHref = strHref.substring(0, strHref.length-1);
381   }
382
383   if ( strHref.indexOf("?") > -1 ){
384     var strQueryString = strHref.substr(strHref.indexOf("?"));
385     var aQueryString = strQueryString.split("&");
386     for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
387       if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
388         var aParam = aQueryString[iParam].split("=");
389         strReturn = aParam[1];
390         break;
391       }
392     }
393   }
394   return strReturn;
395
396
397 function leading_zero(p) {
398         var s = String(p);
399         if (s.length == 1) s = "0" + s;
400         return s;
401 }
402
403 function make_timestamp() {
404         var d = new Date();
405
406         return leading_zero(d.getHours()) + ":" + leading_zero(d.getMinutes()) +
407                         ":" + leading_zero(d.getSeconds());
408 }
409
410
411 function closeErrorBox() {
412
413         if (Element.visible("errorBoxShadow")) {
414                 Element.hide("dialog_overlay");
415                 Element.hide("errorBoxShadow");
416         }
417
418         return false;
419 }
420
421 function closeInfoBox(cleanup) {
422         try {
423                 dialog = dijit.byId("infoBox");
424
425                 if (dialog)     dialog.hide();
426
427         } catch (e) {
428                 //exception_error("closeInfoBox", e);
429         }
430         return false;
431 }
432
433
434 function displayDlg(id, param, callback) {
435
436         notify_progress("Loading, please wait...", true);
437
438         var query = "?op=dlg&id=" +
439                 param_escape(id) + "&param=" + param_escape(param);
440
441         new Ajax.Request("backend.php", {
442                 parameters: query,
443                 onComplete: function (transport) {
444                         infobox_callback2(transport);
445                         if (callback) callback(transport);
446                 } });
447
448         return false;
449 }
450
451 function infobox_callback2(transport) {
452         try {
453                 var dialog = false;
454
455                 if (dijit.byId("infoBox")) {
456                         dialog = dijit.byId("infoBox");
457                 }
458
459                 //console.log("infobox_callback2");
460                 notify('');
461
462                 var content;
463                 var dtitle = "Dialog";
464
465                 var dlg = transport.responseXML.getElementsByTagName("dlg")[0];
466
467                 var title = transport.responseXML.getElementsByTagName("title")[0];
468                 if (title)
469                         title = title.firstChild.nodeValue;
470
471                 var content = transport.responseXML.getElementsByTagName("content")[0];
472                 
473                 content = content.firstChild.nodeValue;
474
475                 if (!dialog) {
476                         dialog = new dijit.Dialog({
477                                 title: title,
478                                 id: 'infoBox',
479                                 style: "width: 600px",
480                                 onCancel: function() {
481                                         return true;
482                                 },
483                                 onExecute: function() {
484                                         return true;
485                                 },
486                                 onClose: function() {
487                                         return true;
488                                         },
489                                 content: content});
490                 } else {
491                         dialog.attr('title', title);
492                         dialog.attr('content', content);
493                 }
494
495                 dialog.show();
496
497                 notify("");
498         } catch (e) {
499                 exception_error("infobox_callback2", e);
500         }
501 }
502
503 function filterCR(e, f)
504 {
505      var key;
506
507      if(window.event)
508           key = window.event.keyCode;     //IE
509      else
510           key = e.which;     //firefox
511
512         if (key == 13) {
513                 if (typeof f != 'undefined') {
514                         f();
515                         return false;
516                 } else {
517                         return false;
518                 }
519         } else {
520                 return true;
521         }
522 }
523
524 function getInitParam(key) {
525         return init_params[key];
526 }
527
528 function setInitParam(key, value) {
529         init_params[key] = value;
530 }
531
532 function fatalError(code, msg, ext_info) {
533         try {   
534
535                 if (code == 6) {
536                         window.location.href = "tt-rss.php";                    
537                 } else if (code == 5) {
538                         window.location.href = "db-updater.php";
539                 } else {
540         
541                         if (msg == "") msg = "Unknown error";
542
543                         if (ext_info) {
544                                 if (ext_info.responseText) {
545                                         ext_info = ext_info.responseText;
546                                 }
547                         }
548
549                         if (ERRORS && ERRORS[code] && !msg) {
550                                 msg = ERRORS[code];
551                         }
552         
553                         var content = "<div><b>Error code:</b> " + code + "</div>" +
554                                 "<p>" + msg + "</p>";
555
556                         if (ext_info) {
557                                 content = content + "<div><b>Additional information:</b></div>" +
558                                         "<textarea style='width: 100%' readonly=\"1\">" + 
559                                         ext_info + "</textarea>";
560                         }
561
562                         var dialog = new dijit.Dialog({
563                                 title: "Fatal error",
564                                 style: "width: 600px",
565                                 content: content});
566
567                         dialog.show();
568
569                 }
570
571                 return false;
572
573         } catch (e) {
574                 exception_error("fatalError", e);
575         }
576 }
577
578 function filterDlgCheckType(sender) {
579
580         try {
581
582                 var ftype = sender.value;
583
584                 // if selected filter type is 5 (Date) enable the modifier dropbox
585                 if (ftype == 5) {
586                         Element.show("filterDlg_dateModBox");
587                         Element.show("filterDlg_dateChkBox");
588                 } else {
589                         Element.hide("filterDlg_dateModBox");
590                         Element.hide("filterDlg_dateChkBox");
591
592                 }
593
594         } catch (e) {
595                 exception_error("filterDlgCheckType", e);
596         }
597
598 }
599
600 function filterDlgCheckAction(sender) {
601
602         try {
603
604                 var action = sender.value;
605
606                 var action_param = $("filterDlg_paramBox");
607
608                 if (!action_param) {
609                         console.log("filterDlgCheckAction: can't find action param box!");
610                         return;
611                 }
612
613                 // if selected action supports parameters, enable params field
614                 if (action == 4 || action == 6 || action == 7) {
615                         new Effect.Appear(action_param, {duration : 0.5});
616                         if (action != 7) {
617                                 Element.show(dijit.byId("filterDlg_actionParam").domNode);
618                                 Element.hide(dijit.byId("filterDlg_actionParamLabel").domNode);
619                         } else {
620                                 Element.show(dijit.byId("filterDlg_actionParamLabel").domNode);
621                                 Element.hide(dijit.byId("filterDlg_actionParam").domNode);
622                         }
623                 } else {
624                         Element.hide(action_param);
625                 }
626
627         } catch (e) {
628                 exception_error("filterDlgCheckAction", e);
629         }
630
631 }
632
633 function filterDlgCheckDate() {
634         try {
635                 var dialog = dijit.byId("filterEditDlg");
636
637                 var reg_exp = dialog.attr('value').reg_exp;
638
639                 var query = "?op=rpc&subop=checkDate&date=" + reg_exp;
640
641                 new Ajax.Request("backend.php", {
642                         parameters: query,
643                         onComplete: function(transport) { 
644
645                                 var reply = JSON.parse(transport.responseText);
646
647                                 if (reply['result'] == true) {
648                                         alert(__("Date syntax appears to be correct."));
649                                         return;
650                                 } else {
651                                         alert(__("Date syntax is incorrect."));
652                                 }
653
654                         } });
655
656
657         } catch (e) {
658                 exception_error("filterDlgCheckDate", e);
659         }
660 }
661
662 function explainError(code) {
663         return displayDlg("explainError", code);
664 }
665
666 function displayHelpInfobox(topic_id) {
667
668         var url = "backend.php?op=help&tid=" + param_escape(topic_id);
669
670         var w = window.open(url, "ttrss_help", 
671                 "status=0,toolbar=0,location=0,width=450,height=500,scrollbars=1,menubar=0");
672
673 }
674
675 function loading_set_progress(p) {
676         try {
677                 loading_progress += p;
678
679                 if (dijit.byId("loading_bar"))
680                         dijit.byId("loading_bar").update({progress: loading_progress});
681
682                 if (loading_progress >= 90)
683                         remove_splash();
684
685         } catch (e) {
686                 exception_error("loading_set_progress", e);
687         }
688 }
689
690 function remove_splash() {
691
692         if (Element.visible("overlay")) {
693                 console.log("about to remove splash, OMG!");
694                 Element.hide("overlay");
695                 console.log("removed splash!");
696         }
697 }
698
699 function transport_error_check(transport) {
700         try {
701                 if (transport.responseXML) {
702                         var error = transport.responseXML.getElementsByTagName("error")[0];
703
704                         if (error) {
705                                 var code = error.getAttribute("error-code");
706                                 var msg = error.getAttribute("error-msg");
707                                 if (code != 0) {
708                                         fatalError(code, msg);
709                                         return false;
710                                 }
711                         }
712                 }
713         } catch (e) {
714                 exception_error("check_for_error_xml", e);
715         }
716         return true;
717 }
718
719 function strip_tags(s) {
720         return s.replace(/<\/?[^>]+(>|$)/g, "");
721 }
722
723 function truncate_string(s, length) {
724         if (!length) length = 30;
725         var tmp = s.substring(0, length);
726         if (s.length > length) tmp += "&hellip;";
727         return tmp;
728 }
729
730 function hotkey_prefix_timeout() {
731         try {
732
733                 var date = new Date();
734                 var ts = Math.round(date.getTime() / 1000);
735
736                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
737                         console.log("hotkey_prefix seems to be stuck, aborting");
738                         hotkey_prefix_pressed = false;
739                         hotkey_prefix = false;
740                         Element.hide('cmdline');
741                 }
742
743                 setTimeout("hotkey_prefix_timeout()", 1000);
744
745         } catch  (e) {
746                 exception_error("hotkey_prefix_timeout", e);
747         }
748 }
749
750 function hideAuxDlg() {
751         try {
752                 Element.hide('auxDlg');
753         } catch (e) {
754                 exception_error("hideAuxDlg", e);
755         }
756 }
757
758
759 function uploadIconHandler(rc) {
760         try {
761                 switch (rc) {
762                         case 0:
763                                 notify_info("Upload complete.");
764                                 if (inPreferences()) {
765                                         updateFeedList();
766                                 } else {
767                                         setTimeout('updateFeedList(false, false)', 50);
768                                 }
769                                 break;
770                         case 1:
771                                 notify_error("Upload failed: icon is too big.");
772                                 break;
773                         case 2:
774                                 notify_error("Upload failed.");
775                                 break;
776                 }
777
778         } catch (e) {
779                 exception_error("uploadIconHandler", e);
780         }
781 }
782
783 function removeFeedIcon(id) {
784
785         try {
786
787                 if (confirm(__("Remove stored feed icon?"))) {
788                         var query = "backend.php?op=pref-feeds&subop=removeicon&feed_id=" + param_escape(id);
789
790                         console.log(query);
791
792                         notify_progress("Removing feed icon...", true);
793
794                         new Ajax.Request("backend.php", {
795                                 parameters: query,
796                                 onComplete: function(transport) { 
797                                         notify_info("Feed icon removed.");
798                                         if (inPreferences()) {
799                                                 updateFeedList();
800                                         } else {
801                                                 setTimeout('updateFeedList(false, false)', 50);
802                                         }
803                                 } }); 
804                 }
805
806                 return false;
807         } catch (e) {
808                 exception_error("uploadFeedIcon", e);
809         }
810 }
811
812 function uploadFeedIcon() {
813
814         try {
815
816                 var file = $("icon_file");
817
818                 if (file.value.length == 0) {
819                         alert(__("Please select an image file to upload."));
820                 } else {
821                         if (confirm(__("Upload new icon for this feed?"))) {
822                                 notify_progress("Uploading, please wait...", true);
823                                 return true;
824                         }
825                 }
826
827                 return false;
828
829         } catch (e) {
830                 exception_error("uploadFeedIcon", e);
831         }
832 }
833
834 function addLabel(select, callback) {
835
836         try {
837
838                 var caption = prompt(__("Please enter label caption:"), "");
839
840                 if (caption != undefined) {
841         
842                         if (caption == "") {
843                                 alert(__("Can't create label: missing caption."));
844                                 return false;
845                         }
846
847                         var query = "?op=pref-labels&subop=add&caption=" + 
848                                 param_escape(caption);
849
850                         if (select)
851                                 query += "&output=select";
852
853                         notify_progress("Loading, please wait...", true);
854
855                         if (inPreferences() && !select) active_tab = "labelConfig";
856
857                         new Ajax.Request("backend.php", {
858                                 parameters: query,
859                                 onComplete: function(transport) { 
860                                         if (callback) {
861                                                 callback(transport);
862                                         } else if (inPreferences()) {
863                                                 updateLabelList();
864                                         } else {
865                                                 updateFeedList();
866                                         }
867                         } });
868
869                 }
870
871         } catch (e) {
872                 exception_error("addLabel", e);
873         }
874 }
875
876 function quickAddFeed() {
877         try {
878                 var query = "backend.php?op=dlg&id=quickAddFeed";
879
880                 if (dijit.byId("feedAddDlg"))
881                         dijit.byId("feedAddDlg").destroyRecursive();
882
883                 var dialog = new dijit.Dialog({
884                         id: "feedAddDlg",
885                         title: __("Subscribe to Feed"),
886                         style: "width: 600px",
887                         execute: function() {
888                                 if (this.validate()) {
889                                         console.log(dojo.objectToQuery(this.attr('value')));
890
891                                         var feed_url = this.attr('value').feed;
892
893                                         notify_progress(__("Subscribing to feed..."), true);
894
895                                         new Ajax.Request("backend.php", {
896                                                 parameters: dojo.objectToQuery(this.attr('value')),
897                                                 onComplete: function(transport) { 
898                                                         try {
899
900                                                                 var reply = JSON.parse(transport.responseText);
901                                 
902                                                                 var rc = parseInt(reply['result']);
903                                         
904                                                                 notify('');
905
906                                                                 console.log("GOT RC: " + rc);
907                                         
908                                                                 switch (rc) {
909                                                                 case 1:
910                                                                         dialog.hide();
911                                                                         notify_info(__("Subscribed to %s").replace("%s", feed_url));
912                                         
913                                                                         updateFeedList();
914                                                                         break;
915                                                                 case 2:
916                                                                         alert(__("Specified URL seems to be invalid."));
917                                                                         break;
918                                                                 case 3:
919                                                                         alert(__("Specified URL doesn't seem to contain any feeds."));
920                                                                         break;
921                                                                 case 4:
922                                                                         notify_progress("Searching for feed urls...", true);
923
924                                                                         new Ajax.Request("backend.php", {
925                                                                                 parameters: 'op=rpc&subop=extractfeedurls&url=' + param_escape(feed_url),
926                                                                                 onComplete: function(transport, dialog, feed_url) {
927
928                                                                                         notify('');
929
930                                                                                         var reply = JSON.parse(transport.responseText);
931
932                                                                                         var feeds = reply['urls'];
933
934                                                                                         console.log(transport.responseText);
935
936                                                                                         var select = dijit.byId("feedDlg_feedContainerSelect");
937
938                                                                                         while (select.getOptions().length > 0)
939                                                                                                 select.removeOption(0);
940
941                                                                                         var count = 0;
942                                                                                         for (var feedUrl in feeds) {
943                                                                                                 select.addOption({value: feedUrl, label: feeds[feedUrl]});
944                                                                                                 count++;
945                                                                                         }
946
947 //                                                                                      if (count > 5) count = 5;
948 //                                                                                      select.size = count; 
949                                         
950                                                                                         Effect.Appear('feedDlg_feedsContainer', {duration : 0.5}); 
951                                                                                 }
952                                                                         });
953                                                                         break;
954                                                                 case 5:
955                                                                         alert(__("Couldn't download the specified URL."));
956                                                                         break;
957                                                                 case 0:
958                                                                         alert(__("You are already subscribed to this feed."));
959                                                                         break;
960                                                                 }
961                                 
962                                                         } catch (e) {
963                                                                 exception_error("subscribeToFeed", e);
964                                                         }
965                                 
966                                                 } });
967
968                                         }
969                         },
970                         href: query});
971
972                 dialog.show();
973         } catch (e) {
974                 exception_error("quickAddFeed", e);
975         }
976 }
977
978 function quickAddFilter() {
979         try {
980                 var query = "backend.php?op=dlg&id=quickAddFilter";
981
982                 if (dijit.byId("filterEditDlg"))
983                         dijit.byId("filterEditDlg").destroyRecursive();
984
985                 dialog = new dijit.Dialog({
986                         id: "filterEditDlg",
987                         title: __("Create Filter"),
988                         style: "width: 600px",
989                         execute: function() {
990                                 if (this.validate()) {
991
992                                         var query = "?op=rpc&subop=verifyRegexp&reg_exp=" + 
993                                                 param_escape(dialog.attr('value').reg_exp);
994
995                                         notify_progress("Verifying regular expression...");
996
997                                         new Ajax.Request("backend.php", {
998                                                 parameters: query,
999                                                 onComplete: function(transport) {
1000                                                         var reply = JSON.parse(transport.responseText); 
1001
1002                                                         if (reply) {
1003                                                                 notify('');
1004
1005                                                                 if (!reply['status']) {
1006                                                                         alert("Match regular expression seems to be invalid.");
1007                                                                         return;
1008                                                                 } else {
1009                                                                         notify_progress("Saving data...", true);
1010
1011                                                                         console.log(dojo.objectToQuery(dialog.attr('value')));
1012
1013                                                                         new Ajax.Request("backend.php", {
1014                                                                                 parameters: dojo.objectToQuery(dialog.attr('value')),
1015                                                                                 onComplete: function(transport) {
1016                                                                                         dialog.hide();
1017                                                                                         notify_info(transport.responseText);
1018                                                                                         if (inPreferences()) {
1019                                                                                                 updateFilterList();                             
1020                                                                                         }
1021                                                                         }})
1022                                                                 }       
1023                                                         }
1024                                         }});
1025                                 }
1026                         },
1027                         href: query});
1028
1029                 dialog.show();
1030         } catch (e) {
1031                 exception_error("quickAddFilter", e);
1032         }
1033 }
1034
1035 function unsubscribeFeed(feed_id, title) {
1036
1037         var msg = __("Unsubscribe from %s?").replace("%s", title);
1038
1039         if (title == undefined || confirm(msg)) {
1040                 notify_progress("Removing feed...");
1041
1042                 var query = "?op=pref-feeds&quiet=1&subop=remove&ids=" + feed_id;
1043
1044                 new Ajax.Request("backend.php", {
1045                         parameters: query,
1046                         onComplete: function(transport) {
1047
1048                                         if (dijit.byId("feedEditDlg")) dijit.byId("feedEditDlg").hide();
1049                 
1050                                         if (inPreferences()) {
1051                                                 updateFeedList();                               
1052                                         } else {
1053                                                 if (feed_id == getActiveFeedId())
1054                                                         setTimeout("viewfeed(-5)", 100);
1055                                         }
1056
1057                                 } });
1058         }
1059
1060         return false;
1061 }
1062
1063
1064 function backend_sanity_check_callback(transport) {
1065
1066         try {
1067
1068                 if (sanity_check_done) {
1069                         fatalError(11, "Sanity check request received twice. This can indicate "+
1070                       "presence of Firebug or some other disrupting extension. "+
1071                                 "Please disable it and try again.");
1072                         return;
1073                 }
1074
1075                 if (!transport.responseXML) {
1076                         if (!store) {
1077                                 fatalError(3, "Sanity check: Received reply is not XML", 
1078                                         transport.responseText);
1079                                 return;
1080                         }
1081                 }
1082
1083                 var reply = transport.responseXML.getElementsByTagName("error")[0];
1084
1085                 if (!reply) {
1086                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
1087                         return;
1088                 }
1089
1090                 var error_code = reply.getAttribute("error-code");
1091         
1092                 if (error_code && error_code != 0) {
1093                         return fatalError(error_code, reply.getAttribute("error-msg"));
1094                 }
1095
1096                 console.log("sanity check ok");
1097
1098                 var params = transport.responseXML.getElementsByTagName("init-params")[0];
1099
1100                 if (params) {
1101                         console.log('reading init-params...');
1102
1103                         params = JSON.parse(params.firstChild.nodeValue);
1104
1105                         if (params) {
1106                                 for (k in params) {
1107                                         var v = params[k];
1108                                         console.log("IP: " + k + " => " + v);
1109                                 }
1110                         }
1111
1112                         init_params = params;
1113                 }
1114
1115                 sanity_check_done = true;
1116
1117                 init_second_stage();
1118
1119         } catch (e) {
1120                 exception_error("backend_sanity_check_callback", e, transport); 
1121         } 
1122 }
1123
1124 function has_local_storage() {
1125         try {
1126                 return 'sessionStorage' in window && window['sessionStorage'] != null;
1127         } catch (e) {
1128                 return false;
1129         } 
1130 }
1131
1132 function catSelectOnChange(elem) {
1133         try {
1134 /*              var value = elem[elem.selectedIndex].value;
1135                 var def = elem.getAttribute('default');
1136
1137                 if (value == "ADD_CAT") {
1138
1139                         if (def)
1140                                 dropboxSelect(elem, def);
1141                         else
1142                                 elem.selectedIndex = 0;
1143
1144                         quickAddCat(elem);
1145                 } */
1146
1147         } catch (e) {
1148                 exception_error("catSelectOnChange", e);
1149         }
1150 }
1151
1152 function quickAddCat(elem) {
1153         try {
1154                 var cat = prompt(__("Please enter category title:"));
1155
1156                 if (cat) {
1157
1158                         var query = "?op=rpc&subop=quickAddCat&cat=" + param_escape(cat);
1159
1160                         notify_progress("Loading, please wait...", true);
1161
1162                         new Ajax.Request("backend.php", {
1163                                 parameters: query,
1164                                 onComplete: function (transport) {
1165                                         var response = transport.responseXML;
1166                                         var select = response.getElementsByTagName("select")[0];
1167                                         var options = select.getElementsByTagName("option");
1168
1169                                         dropbox_replace_options(elem, options);
1170
1171                                         notify('');
1172
1173                         } });
1174
1175                 }
1176
1177         } catch (e) {
1178                 exception_error("quickAddCat", e);
1179         }
1180 }
1181
1182 function genUrlChangeKey(feed, is_cat) {
1183
1184         try {
1185                 var ok = confirm(__("Generate new syndication address for this feed?"));
1186         
1187                 if (ok) {
1188         
1189                         notify_progress("Trying to change address...", true);
1190         
1191                         var query = "?op=rpc&subop=regenFeedKey&id=" + param_escape(feed) + 
1192                                 "&is_cat=" + param_escape(is_cat);
1193
1194                         new Ajax.Request("backend.php", {
1195                                 parameters: query,
1196                                 onComplete: function(transport) {
1197                                                 var reply = JSON.parse(transport.responseText);
1198                                                 var new_link = reply.link;
1199         
1200                                                 var e = $('gen_feed_url');
1201         
1202                                                 if (new_link) {
1203                                                         
1204                                                         e.innerHTML = e.innerHTML.replace(/\&amp;key=.*$/, 
1205                                                                 "&amp;key=" + new_link);
1206
1207                                                         e.href = e.href.replace(/\&amp;key=.*$/,
1208                                                                 "&amp;key=" + new_link);
1209
1210                                                         new Effect.Highlight(e);
1211
1212                                                         notify('');
1213         
1214                                                 } else {
1215                                                         notify_error("Could not change feed URL.");
1216                                                 }
1217                                 } });
1218                 }
1219         } catch (e) {
1220                 exception_error("genUrlChangeKey", e);
1221         }
1222         return false;
1223 }
1224
1225 function labelSelectOnChange(elem) {
1226         try {
1227 /*              var value = elem[elem.selectedIndex].value;
1228                 var def = elem.getAttribute('default');
1229
1230                 if (value == "ADD_LABEL") {
1231
1232                         if (def)
1233                                 dropboxSelect(elem, def);
1234                         else
1235                                 elem.selectedIndex = 0;
1236
1237                         addLabel(elem, function(transport) {
1238
1239                                         try {
1240
1241                                                 var response = transport.responseXML;
1242                                                 var select = response.getElementsByTagName("select")[0];
1243                                                 var options = select.getElementsByTagName("option");
1244
1245                                                 dropbox_replace_options(elem, options);
1246
1247                                                 notify('');
1248                                         } catch (e) {
1249                                                 exception_error("addLabel", e);
1250                                         }
1251                         });
1252                 } */
1253
1254         } catch (e) {
1255                 exception_error("labelSelectOnChange", e);
1256         }
1257 }
1258
1259 function dropbox_replace_options(elem, options) {
1260
1261         try {
1262                 while (elem.hasChildNodes())
1263                         elem.removeChild(elem.firstChild);
1264
1265                 var sel_idx = -1;
1266
1267                 for (var i = 0; i < options.length; i++) {
1268                         var text = options[i].firstChild.nodeValue;
1269                         var value = options[i].getAttribute("value");
1270
1271                         if (value == undefined) value = text;
1272
1273                         var issel = options[i].getAttribute("selected") == "1";
1274
1275                         var option = new Option(text, value, issel);
1276
1277                         if (options[i].getAttribute("disabled"))
1278                                 option.setAttribute("disabled", true);
1279
1280                         elem.insert(option);
1281
1282                         if (issel) sel_idx = i;
1283                 }
1284
1285                 // Chrome doesn't seem to just select stuff when you pass new Option(x, y, true)
1286                 if (sel_idx >= 0) elem.selectedIndex = sel_idx;
1287
1288         } catch (e) {
1289                 exception_error("dropbox_replace_options", e);
1290         }
1291 }
1292
1293 // mode = all, none, invert
1294 function selectTableRows(id, mode) {
1295         try {
1296                 var rows = $(id).rows;
1297
1298                 for (var i = 0; i < rows.length; i++) {
1299                         var row = rows[i];
1300                         var cb = false;
1301
1302                         if (row.id && row.className) {
1303                                 var bare_id = row.id.replace(/^[A-Z]*?-/, "");
1304                                 var inputs = rows[i].getElementsByTagName("input");
1305
1306                                 for (var j = 0; j < inputs.length; j++) {
1307                                         var input = inputs[j];
1308
1309                                         if (input.getAttribute("type") == "checkbox" && 
1310                                                         input.id.match(bare_id)) {
1311
1312                                                 cb = input;
1313                                                 break;
1314                                         }
1315                                 }
1316
1317                                 if (cb) {
1318                                         var issel = row.hasClassName("Selected");
1319
1320                                         if (mode == "all" && !issel) {
1321                                                 row.addClassName("Selected");
1322                                                 cb.checked = true;
1323                                         } else if (mode == "none" && issel) {
1324                                                 row.removeClassName("Selected");
1325                                                 cb.checked = false;
1326                                         } else if (mode == "invert") {
1327
1328                                                 if (issel) {
1329                                                         row.removeClassName("Selected");
1330                                                         cb.checked = false;
1331                                                 } else {
1332                                                         row.addClassName("Selected");
1333                                                         cb.checked = true;
1334                                                 }
1335                                         }
1336                                 }
1337                         }
1338                 }
1339
1340         } catch (e) {
1341                 exception_error("selectTableRows", e);
1342
1343         }
1344 }
1345
1346 function getSelectedTableRowIds(id) {
1347         var rows = [];
1348
1349         try {
1350                 var elem_rows = $(id).rows;
1351
1352                 for (i = 0; i < elem_rows.length; i++) {
1353                         if (elem_rows[i].hasClassName("Selected")) {
1354                                 var bare_id = elem_rows[i].id.replace(/^[A-Z]*?-/, "");
1355                                 rows.push(bare_id);
1356                         }
1357                 }
1358
1359         } catch (e) {
1360                 exception_error("getSelectedTableRowIds", e);
1361         }
1362
1363         return rows;
1364 }
1365
1366 function editFeed(feed, event) {
1367         try {
1368                 if (feed <= 0)
1369                         return alert(__("You can't edit this kind of feed."));
1370
1371                 var query = "backend.php?op=pref-feeds&subop=editfeed&id=" +
1372                         param_escape(feed);
1373
1374                 console.log(query);
1375
1376                 if (dijit.byId("feedEditDlg"))
1377                         dijit.byId("feedEditDlg").destroyRecursive();
1378
1379                 dialog = new dijit.Dialog({
1380                         id: "feedEditDlg",
1381                         title: __("Edit Feed"),
1382                         style: "width: 600px",
1383                         execute: function() {
1384                                 if (this.validate()) {
1385 //                                      console.log(dojo.objectToQuery(this.attr('value')));
1386
1387                                         notify_progress("Saving data...", true);
1388
1389                                         new Ajax.Request("backend.php", {
1390                                                 parameters: dojo.objectToQuery(dialog.attr('value')),
1391                                                 onComplete: function(transport) {
1392                                                         dialog.hide();
1393                                                         notify('');
1394                                                         updateFeedList();
1395                                         }})
1396                                 }
1397                         },
1398                         href: query});
1399
1400                 dialog.show();
1401
1402         } catch (e) {
1403                 exception_error("editFeed", e);
1404         }
1405 }
1406
1407 function feedBrowser() {
1408         try {
1409                 var query = "backend.php?op=dlg&id=feedBrowser";
1410
1411                 if (dijit.byId("feedAddDlg"))
1412                         dijit.byId("feedAddDlg").hide();
1413
1414                 if (dijit.byId("feedBrowserDlg"))
1415                         dijit.byId("feedBrowserDlg").destroyRecursive();
1416
1417                 var dialog = new dijit.Dialog({
1418                         id: "feedBrowserDlg",
1419                         title: __("More Feeds"),
1420                         style: "width: 600px",
1421                         getSelectedFeeds: function() {
1422                                 var list = $$("#browseFeedList li[id*=FBROW]");
1423                                 var selected = new Array();
1424                         
1425                                 list.each(function(child) {     
1426                                         var id = child.id.replace("FBROW-", "");
1427                         
1428                                         if (child.hasClassName('Selected')) {
1429                                                 selected.push(id);
1430                                         }       
1431                                 });
1432                         
1433                                 return selected;
1434                         },
1435                         subscribe: function() {
1436                                 var selected = this.getSelectedFeeds();
1437                                 var mode = this.attr('value').mode;
1438                 
1439                                 if (selected.length > 0) {
1440                                         dijit.byId("feedBrowserDlg").hide();
1441                 
1442                                         notify_progress("Loading, please wait...", true);
1443                 
1444                                         var query = "?op=rpc&subop=massSubscribe&ids="+
1445                                                 param_escape(selected.toString()) + "&mode=" + param_escape(mode);
1446
1447                                         console.log(query);
1448                 
1449                                         new Ajax.Request("backend.php", {
1450                                                 parameters: query,
1451                                                 onComplete: function(transport) { 
1452                                                         if (inPreferences()) {
1453                                                                 updateFeedList();
1454                                                         }
1455                                                 } });
1456                 
1457                                 } else {
1458                                         alert(__("No feeds are selected."));
1459                                 }
1460                 
1461                         },
1462                         update: function() {
1463                                 var query = dojo.objectToQuery(dialog.attr('value'));
1464                 
1465                                 Element.show('feed_browser_spinner');
1466                 
1467                                 new Ajax.Request("backend.php", {
1468                                         parameters: query,
1469                                         onComplete: function(transport) { 
1470                                                 notify('');
1471                 
1472                                                 Element.hide('feed_browser_spinner');
1473                 
1474                                                 var c = $("browseFeedList");
1475
1476                                                 var reply = JSON.parse(transport.responseText);
1477
1478                                                 var r = reply['content'];
1479                                                 var mode = reply['mode'];
1480                 
1481                                                 if (c && r) {
1482                                                         c.innerHTML = r;
1483                                                 }
1484                 
1485                                                 dojo.parser.parse("browseFeedList");
1486                 
1487                                                 if (mode == 2) {
1488                                                         Element.show(dijit.byId('feed_archive_remove').domNode);
1489                                                 } else {
1490                                                         Element.hide(dijit.byId('feed_archive_remove').domNode);
1491                                                 }
1492                         
1493                                         } });
1494                         },
1495                         removeFromArchive: function() {
1496                                 var selected = this.getSelectedFeeds();
1497                 
1498                                 if (selected.length > 0) {
1499                 
1500                                         var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1501                 
1502                                         if (confirm(pr)) {
1503                                                 Element.show('feed_browser_spinner');
1504                 
1505                                                 var query = "?op=rpc&subop=remarchived&ids=" + 
1506                                                         param_escape(selected.toString());;
1507                 
1508                                                 new Ajax.Request("backend.php", {
1509                                                         parameters: query,
1510                                                         onComplete: function(transport) { 
1511                                                                 dialog.update();
1512                                                         } }); 
1513                                         }
1514                                 }
1515                         },
1516                         execute: function() {
1517                                 if (this.validate()) {
1518                                         this.subscribe();
1519                                 }
1520                         },
1521                         href: query});
1522
1523                 dialog.show();
1524
1525         } catch (e) {
1526                 exception_error("editFeed", e);
1527         }
1528 }
1529
1530