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