]> git.wh0rd.org Git - tt-rss.git/blob - functions.js
Merge branch 'master' into digest-experimental
[tt-rss.git] / functions.js
1 var hotkeys_enabled = true;
2 var notify_silent = false;
3 var last_progress_point = 0;
4 var async_counters_work = false;
5 var sanity_check_done = false;
6
7 /* add method to remove element from array */
8
9 Array.prototype.remove = function(s) {
10         for (var i=0; i < this.length; i++) {
11                 if (s == this[i]) this.splice(i, 1);
12         }
13 }
14
15 /* create console.log if it doesn't exist */
16
17 if (!window.console) console = {};
18 console.log = console.log || function(msg) { debug(msg); };
19 console.warn = console.warn || function(msg) { debug(msg); };
20 console.error = console.error || function(msg) { debug(msg); };
21
22 function exception_error(location, e, ext_info) {
23         var msg = format_exception_error(location, e);
24
25         if (!ext_info) ext_info = false;
26
27         disableHotkeys();
28
29         try {
30
31                 var ebc = $("xebContent");
32         
33                 if (ebc) {
34         
35                         Element.show("dialog_overlay");
36                         Element.show("errorBoxShadow");
37         
38                         if (ext_info) {
39                                 if (ext_info.responseText) {
40                                         ext_info = ext_info.responseText;
41                                 }
42                         }
43         
44                         ebc.innerHTML = 
45                                 "<div><b>Error message:</b></div>" +
46                                 "<pre>" + msg + "</pre>";
47
48                         if (ext_info) {
49                                 ebc.innerHTML += "<div><b>Additional information:</b></div>" +
50                                 "<textarea readonly=\"1\">" + ext_info + "</textarea>";
51                         }
52
53                         ebc.innerHTML += "<div><b>Stack trace:</b></div>" +
54                                 "<textarea readonly=\"1\">" + e.stack + "</textarea>";
55         
56                 } else {
57                         alert(msg);
58                 }
59
60         } catch (e) {
61                 alert(msg);
62
63         }
64
65 }
66
67 function format_exception_error(location, e) {
68         var msg;
69
70         if (e.fileName) {
71                 var base_fname = e.fileName.substring(e.fileName.lastIndexOf("/") + 1);
72         
73                 msg = "Exception: " + e.name + ", " + e.message + 
74                         "\nFunction: " + location + "()" +
75                         "\nLocation: " + base_fname + ":" + e.lineNumber;
76
77         } else if (e.description) {
78                 msg = "Exception: " + e.description + "\nFunction: " + location + "()";
79         } else {
80                 msg = "Exception: " + e + "\nFunction: " + location + "()";
81         }
82
83         console.error("EXCEPTION: " + msg);
84
85         return msg;
86 }
87
88
89 function disableHotkeys() {
90         hotkeys_enabled = false;
91 }
92
93 function enableHotkeys() {
94         hotkeys_enabled = true;
95 }
96
97 function param_escape(arg) {
98         if (typeof encodeURIComponent != 'undefined')
99                 return encodeURIComponent(arg); 
100         else
101                 return escape(arg);
102 }
103
104 function param_unescape(arg) {
105         if (typeof decodeURIComponent != 'undefined')
106                 return decodeURIComponent(arg); 
107         else
108                 return unescape(arg);
109 }
110
111 function delay(gap) {
112         var then,now; 
113         then=new Date().getTime();
114         now=then;
115         while((now-then)<gap) {
116                 now=new Date().getTime();
117         }
118 }
119
120 var notify_hide_timerid = false;
121
122 function hide_notify() {
123         var n = $("notify");
124         if (n) {
125                 n.style.display = "none";
126         }
127
128
129 function notify_silent_next() {
130         notify_silent = true;
131 }
132
133 function notify_real(msg, no_hide, n_type) {
134
135         if (notify_silent) {
136                 notify_silent = false;
137                 return;
138         }
139
140         var n = $("notify");
141         var nb = $("notify_body");
142
143         if (!n || !nb) return;
144
145         if (notify_hide_timerid) {
146                 window.clearTimeout(notify_hide_timerid);
147         }
148
149         if (msg == "") {
150                 if (n.style.display == "block") {
151                         notify_hide_timerid = window.setTimeout("hide_notify()", 0);
152                 }
153                 return;
154         } else {
155                 n.style.display = "block";
156         }
157
158         /* types:
159
160                 1 - generic
161                 2 - progress
162                 3 - error
163                 4 - info
164
165         */
166
167         if (typeof __ != 'undefined') {
168                 msg = __(msg);
169         }
170
171         if (n_type == 1) {
172                 n.className = "notify";
173         } else if (n_type == 2) {
174                 n.className = "notifyProgress";
175                 msg = "<img src='"+getInitParam("sign_progress")+"'> " + msg;
176         } else if (n_type == 3) {
177                 n.className = "notifyError";
178                 msg = "<img src='"+getInitParam("sign_excl")+"'> " + msg;
179         } else if (n_type == 4) {
180                 n.className = "notifyInfo";
181                 msg = "<img src='"+getInitParam("sign_info")+"'> " + msg;
182         }
183
184 //      msg = "<img src='images/live_com_loading.gif'> " + msg;
185
186         nb.innerHTML = msg;
187
188         if (!no_hide) {
189                 notify_hide_timerid = window.setTimeout("hide_notify()", 3000);
190         }
191 }
192
193 function notify(msg, no_hide) {
194         notify_real(msg, no_hide, 1);
195 }
196
197 function notify_progress(msg, no_hide) {
198         notify_real(msg, no_hide, 2);
199 }
200
201 function notify_error(msg, no_hide) {
202         notify_real(msg, no_hide, 3);
203
204 }
205
206 function notify_info(msg, no_hide) {
207         notify_real(msg, no_hide, 4);
208 }
209
210 function printLockingError() {
211         notify_info("Please wait until operation finishes.");
212 }
213
214 function cleanSelected(element) {
215         var content = $(element);
216
217         for (i = 0; i < content.rows.length; i++) {
218                 content.rows[i].className = content.rows[i].className.replace("Selected", "");
219         }
220 }
221
222 function getVisibleUnreadHeadlines() {
223         var content = $("headlinesList");
224
225         var rows = new Array();
226
227         if (!content) return rows;
228
229         for (i = 0; i < content.rows.length; i++) {
230                 var row_id = content.rows[i].id.replace("RROW-", "");
231                 if (row_id.length > 0 && content.rows[i].className.match("Unread")) {
232                                 rows.push(row_id);      
233                 }
234         }
235         return rows;
236 }
237
238 function getVisibleHeadlineIds() {
239
240         var content = $("headlinesList");
241
242         var rows = new Array();
243
244         if (!content) return rows;
245
246         for (i = 0; i < content.rows.length; i++) {
247                 var row_id = content.rows[i].id.replace("RROW-", "");
248                 if (row_id.length > 0) {
249                                 rows.push(row_id);      
250                 }
251         }
252         return rows;
253 }
254
255 function getFirstVisibleHeadlineId() {
256         if (isCdmMode()) {
257                 var rows = cdmGetVisibleArticles();
258                 return rows[0];
259         } else {
260                 var rows = getVisibleHeadlineIds();
261                 return rows[0];
262         }
263 }
264
265 function getLastVisibleHeadlineId() {
266         if (isCdmMode()) {
267                 var rows = cdmGetVisibleArticles();
268                 return rows[rows.length-1];
269         } else {
270                 var rows = getVisibleHeadlineIds();
271                 return rows[rows.length-1];
272         }
273 }
274
275 function markHeadline(id) {
276         var row = $("RROW-" + id);
277         if (row) {
278                 var is_active = false;
279         
280                 if (row.className.match("Active")) {
281                         is_active = true;
282                 }
283                 row.className = row.className.replace("Selected", "");
284                 row.className = row.className.replace("Active", "");
285                 row.className = row.className.replace("Insensitive", "");
286                 
287                 if (is_active) {
288                         row.className = row.className = "Active";
289                 }
290                 
291                 var check = $("RCHK-" + id);
292
293                 if (check) {
294                         check.checked = true;
295                 }
296
297                 row.className = row.className + "Selected"; 
298                 
299         }
300 }
301
302 function getFeedIds() {
303         var content = $("feedsList");
304
305         var rows = new Array();
306
307         for (i = 0; i < content.rows.length; i++) {
308                 var id = content.rows[i].id.replace("FEEDR-", "");
309                 if (id.length > 0) {
310                         rows.push(id);
311                 }
312         }
313
314         return rows;
315 }
316
317 function setCookie(name, value, lifetime, path, domain, secure) {
318         
319         var d = false;
320         
321         if (lifetime) {
322                 d = new Date();
323                 d.setTime(d.getTime() + (lifetime * 1000));
324         }
325
326         console.log("setCookie: " + name + " => " + value + ": " + d);
327         
328         int_setCookie(name, value, d, path, domain, secure);
329
330 }
331
332 function int_setCookie(name, value, expires, path, domain, secure) {
333         document.cookie= name + "=" + escape(value) +
334                 ((expires) ? "; expires=" + expires.toGMTString() : "") +
335                 ((path) ? "; path=" + path : "") +
336                 ((domain) ? "; domain=" + domain : "") +
337                 ((secure) ? "; secure" : "");
338 }
339
340 function delCookie(name, path, domain) {
341         if (getCookie(name)) {
342                 document.cookie = name + "=" +
343                 ((path) ? ";path=" + path : "") +
344                 ((domain) ? ";domain=" + domain : "" ) +
345                 ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
346         }
347 }
348                 
349
350 function getCookie(name) {
351
352         var dc = document.cookie;
353         var prefix = name + "=";
354         var begin = dc.indexOf("; " + prefix);
355         if (begin == -1) {
356             begin = dc.indexOf(prefix);
357             if (begin != 0) return null;
358         }
359         else {
360             begin += 2;
361         }
362         var end = document.cookie.indexOf(";", begin);
363         if (end == -1) {
364             end = dc.length;
365         }
366         return unescape(dc.substring(begin + prefix.length, end));
367 }
368
369 function gotoPreferences() {
370         document.location.href = "prefs.php";
371 }
372
373 function gotoMain() {
374         document.location.href = "tt-rss.php";
375 }
376
377 function gotoExportOpml() {
378         document.location.href = "opml.php?op=Export";
379 }
380
381 function parse_counters(reply, scheduled_call) {
382         try {
383
384                 var feeds_found = 0;
385
386                 var elems = reply.getElementsByTagName("counter");
387
388                 for (var l = 0; l < elems.length; l++) {
389
390                         var id = elems[l].getAttribute("id");
391                         var t = elems[l].getAttribute("type");
392                         var ctr = elems[l].getAttribute("counter");
393                         var error = elems[l].getAttribute("error");
394                         var has_img = elems[l].getAttribute("hi");
395                         var updated = elems[l].getAttribute("updated");
396                         var title = elems[l].getAttribute("title");
397                         var xmsg = elems[l].getAttribute("xmsg");
398         
399                         if (id == "global-unread") {
400
401                                 if (ctr > global_unread) {
402                                         offlineDownloadStart(1);
403                                 }
404
405                                 global_unread = ctr;
406                                 updateTitle();
407                                 continue;
408                         }
409
410                         if (id == "subscribed-feeds") {
411                                 feeds_found = ctr;
412                                 continue;
413                         }
414         
415                         if (t == "category") {
416                                 var catctr = $("FCATCTR-" + id);
417                                 if (catctr) {
418                                         catctr.innerHTML = "(" + ctr + ")";
419                                         if (ctr > 0) {
420                                                 catctr.className = "catCtrHasUnread";
421                                         } else {
422                                                 catctr.className = "catCtrNoUnread";
423                                         }
424                                 }
425                                 continue;
426                         }
427                 
428                         var feedctr = $("FEEDCTR-" + id);
429                         var feedu = $("FEEDU-" + id);
430                         var feedr = $("FEEDR-" + id);
431                         var feed_img = $("FIMG-" + id);
432                         var feedlink = $("FEEDL-" + id);
433                         var feedupd = $("FLUPD-" + id);
434
435                         if (updated && feedlink) {
436                                 if (error) {
437                                         feedlink.title = "Error: " + error + " (" + updated + ")";
438                                 } else {
439                                         feedlink.title = "Updated: " + updated;
440                                 }
441                         }
442
443                         if (feedupd) {
444                                 if (!updated) updated = "";
445
446                                 if (error) {
447                                         if (xmsg) {
448                                                 feedupd.innerHTML = updated + " " + xmsg + " (Error)";
449                                         } else {
450                                                 feedupd.innerHTML = updated + " (Error)";
451                                         }
452                                 } else {
453                                         if (xmsg) {
454                                                 feedupd.innerHTML = updated + " " + xmsg;
455                                         } else {
456                                                 feedupd.innerHTML = updated;
457                                         }
458                                 }
459                         }
460
461                         if (has_img && feed_img) {
462                                 if (!feed_img.src.match(id + ".ico")) {
463                                         feed_img.src = getInitParam("icons_location") + "/" + id + ".ico";
464                                 }
465                         }
466
467                         if (feedlink && title) {
468                                 feedlink.innerHTML = title;
469                         }
470
471                         if (feedctr && feedu && feedr) {
472
473                                 if (parseInt(ctr) > 0 && 
474                                                 parseInt(feedu.innerHTML) < parseInt(ctr) && 
475                                                 id == getActiveFeedId() && scheduled_call) {
476
477                                         displayNewContentPrompt(id);
478                                 }
479
480                                 var row_needs_hl = (ctr > 0 && ctr > parseInt(feedu.innerHTML));
481
482                                 feedu.innerHTML = ctr;
483
484                                 if (error) {
485                                         feedr.className = feedr.className.replace("feed", "error");
486                                 } else if (id > 0) {
487                                         feedr.className = feedr.className.replace("error", "feed");
488                                 }
489         
490                                 if (ctr > 0) {                                  
491                                         feedctr.className = "feedCtrHasUnread";
492                                         if (!feedr.className.match("Unread")) {
493                                                 var is_selected = feedr.className.match("Selected");
494                 
495                                                 feedr.className = feedr.className.replace("Selected", "");
496                                                 feedr.className = feedr.className.replace("Unread", "");
497                 
498                                                 feedr.className = feedr.className + "Unread";
499                 
500                                                 if (is_selected) {
501                                                         feedr.className = feedr.className + "Selected";
502                                                 }       
503                                                 
504                                         }
505
506                                         if (row_needs_hl && 
507                                                         !getInitParam("theme_options").match('no_highlights')) { 
508                                                 new Effect.Highlight(feedr, {duration: 1, startcolor: "#fff7d5",
509                                                         queue: { position:'end', scope: 'EFQ-' + id, limit: 1 } } );
510
511                                                 cache_invalidate("F:" + id);
512                                         }
513                                 } else {
514                                         feedctr.className = "feedCtrNoUnread";
515                                         feedr.className = feedr.className.replace("Unread", "");
516                                 }                       
517                         }
518                 }
519
520                 hideOrShowFeeds(getInitParam("hide_read_feeds") == 1);
521
522                 var feeds_stored = number_of_feeds;
523
524                 console.log("Feed counters, C: " + feeds_found + ", S:" + feeds_stored);
525
526                 if (feeds_stored != feeds_found) {
527                         number_of_feeds = feeds_found;
528
529                         if (feeds_stored != 0 && feeds_found != 0) {
530                                 console.log("Subscribed feed number changed, refreshing feedlist");
531                                 setTimeout('updateFeedList(false, false)', 50);
532                         }
533                 } else {
534 /*                      var fl = $("feeds-frame").innerHTML;
535                         if (fl) {
536                                 cache_invalidate("FEEDLIST");
537                                 cache_inject("FEEDLIST", fl, getInitParam("num_feeds"));
538                         } */
539                 }
540
541         } catch (e) {
542                 exception_error("parse_counters", e);
543         }
544 }
545
546 function parse_counters_reply(transport, scheduled_call) {
547
548         if (!transport.responseXML) {
549                 notify_error("Backend did not return valid XML", true);
550                 return;
551         }
552
553         var reply = transport.responseXML.firstChild;
554         
555         if (!reply) {
556                 notify_error("Backend did not return expected XML object", true);
557                 updateTitle("");
558                 return;
559         } 
560
561         if (!transport_error_check(transport)) return;
562
563         var counters = reply.getElementsByTagName("counters")[0];
564         
565         parse_counters(counters, scheduled_call);
566
567         var runtime_info = reply.getElementsByTagName("runtime-info")[0];
568
569         parse_runtime_info(runtime_info);
570
571         if (feedsSortByUnread()) {
572                 resort_feedlist();
573         }
574
575         hideOrShowFeeds(getInitParam("hide_read_feeds") == 1);
576
577 }
578
579 function all_counters_callback2(transport, async_call) {
580         try {
581                 if (async_call) async_counters_work = true;
582                 
583                 if (offline_mode) return;
584
585                 console.log("<b>all_counters_callback2 IN: " + transport + "</b>");
586                 parse_counters_reply(transport);
587                 console.log("<b>all_counters_callback2 OUT: " + transport + "</b>");
588
589         } catch (e) {
590                 exception_error("all_counters_callback2", e, transport);
591         }
592 }
593
594 function get_feed_unread(id) {
595         try {
596                 return parseInt($("FEEDU-" + id).innerHTML);    
597         } catch (e) {
598                 return -1;
599         }
600 }
601
602 function get_cat_unread(id) {
603         try {
604                 var ctr = $("FCATCTR-" + id).innerHTML;
605                 ctr = ctr.replace("(", "");
606                 ctr = ctr.replace(")", "");
607                 return parseInt(ctr);
608         } catch (e) {
609                 return -1;
610         }
611 }
612
613 function get_feed_entry_unread(elem) {
614
615         var id = elem.id.replace("FEEDR-", "");
616
617         if (id <= 0) {
618                 return -1;
619         }
620
621         try {
622                 return parseInt($("FEEDU-" + id).innerHTML);    
623         } catch (e) {
624                 return -1;
625         }
626 }
627
628 function get_feed_entry_name(elem) {
629         var id = elem.id.replace("FEEDR-", "");
630         return getFeedName(id);
631 }
632
633
634 function resort_category(node, cat_mode) {
635
636         try {
637
638                 console.log("resort_category: " + node + " CM=" + cat_mode);
639         
640                 var by_unread = feedsSortByUnread();
641         
642                 var list = node.getElementsByTagName("LI");
643         
644                 for (i = 0; i < list.length; i++) {
645         
646                         for (j = i+1; j < list.length; j++) {                   
647         
648                                 var tmp_val = get_feed_entry_unread(list[i]);
649                                 var cur_val = get_feed_entry_unread(list[j]);
650         
651                                 var tmp_name = get_feed_entry_name(list[i]);
652                                 var cur_name = get_feed_entry_name(list[j]);
653
654                                 var valid_pair = cat_mode || (list[i].id.match(/FEEDR-[0-9]/) &&
655                                                 list[j].id.match(/FEEDR-[0-9]/));
656
657                                 if (valid_pair && ((by_unread && (cur_val > tmp_val)) || (!by_unread && (cur_name < tmp_name)))) {
658                                         tempnode_i = list[i].cloneNode(true);
659                                         tempnode_j = list[j].cloneNode(true);
660                                         node.replaceChild(tempnode_i, list[j]);
661                                         node.replaceChild(tempnode_j, list[i]);
662                                 }
663                         }
664                 }
665
666         } catch (e) {
667                 exception_error("resort_category", e);
668         }
669
670 }
671
672 function resort_feedlist() {
673         console.log("resort_feedlist");
674
675         if ($("FCATLIST--1")) {
676
677                 var lists = document.getElementsByTagName("UL");
678
679                 for (var i = 0; i < lists.length; i++) {
680                         if (lists[i].id && lists[i].id.match("FCATLIST-")) {
681                                 resort_category(lists[i], true);
682                         }
683                 }
684
685         } else {
686                 resort_category($("feedList"), false);
687         }
688 }
689
690 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
691   * * @author Sundar Dorai-Raj
692   * * Email: sdoraira@vt.edu
693   * * This program is free software; you can redistribute it and/or
694   * * modify it under the terms of the GNU General Public License 
695   * * as published by the Free Software Foundation; either version 2 
696   * * of the License, or (at your option) any later version, 
697   * * provided that any use properly credits the author. 
698   * * This program is distributed in the hope that it will be useful,
699   * * but WITHOUT ANY WARRANTY; without even the implied warranty of
700   * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
701   * * GNU General Public License for more details at http://www.gnu.org * * */
702
703   var numbers=".0123456789";
704   function isNumeric(x) {
705     // is x a String or a character?
706     if(x.length>1) {
707       // remove negative sign
708       x=Math.abs(x)+"";
709       for(j=0;j<x.length;j++) {
710         // call isNumeric recursively for each character
711         number=isNumeric(x.substring(j,j+1));
712         if(!number) return number;
713       }
714       return number;
715     }
716     else {
717       // if x is number return true
718       if(numbers.indexOf(x)>=0) return true;
719       return false;
720     }
721   }
722
723
724 function hideOrShowFeeds(hide) {
725
726         try {
727
728         console.log("hideOrShowFeeds: " + hide);
729
730         if ($("FCATLIST--1")) {
731
732                 var lists = document.getElementsByTagName("UL");
733
734                 for (var i = 0; i < lists.length; i++) {
735                         if (lists[i].id && lists[i].id.match("FCATLIST-")) {
736
737                                 var id = lists[i].id.replace("FCATLIST-", "");
738                                 hideOrShowFeedsCategory(id, hide);
739                         }
740                 }
741
742         } else {
743                 hideOrShowFeedsCategory(null, hide);
744         }
745
746         } catch (e) {
747                 exception_error("hideOrShowFeeds", e);
748         }
749 }
750
751 function hideOrShowFeedsCategory(id, hide) {
752
753         try {
754         
755                 var node = null;
756                 var cat_node = null;
757
758                 if (id) {
759                         node = $("FCATLIST-" + id);
760                         cat_node = $("FCAT-" + id);
761                 } else {
762                         node = $("feedList"); // no categories
763                 }
764
765         //      console.log("hideOrShowFeedsCategory: " + node + " (" + hide + ")");
766         
767                 var cat_unread = 0;
768         
769                 if (!node) {
770                         console.log("hideOrShowFeeds: passed node is null, aborting");
771                         return;
772                 }
773         
774         //      console.log("cat: " + node.id);
775         
776                 if (node.hasChildNodes() && node.firstChild.nextSibling != false) {  
777                         for (i = 0; i < node.childNodes.length; i++) {
778                                 if (node.childNodes[i].nodeName != "LI") { continue; }
779         
780                                 if (node.childNodes[i].style != undefined) {
781         
782                                         var has_unread = (node.childNodes[i].className != "feed" &&
783                                                 node.childNodes[i].className != "label" && 
784                                                 !(!getInitParam("hide_read_shows_special") && 
785                                                         node.childNodes[i].className == "virt") && 
786                                                 node.childNodes[i].className != "error" && 
787                                                 node.childNodes[i].className != "tag");
788                 
789         //                              console.log(node.childNodes[i].id + " --> " + has_unread);
790                 
791                                         if (hide && !has_unread) {
792                                                 //node.childNodes[i].style.display = "none";
793                                                 var id = node.childNodes[i].id;
794                                                 Effect.Fade(node.childNodes[i], {duration : 0.3, 
795                                                         queue: { position: 'end', scope: 'FFADE-' + id, limit: 1 }});
796                                         }
797                 
798                                         if (!hide) {
799                                                 node.childNodes[i].style.display = "list-item";
800                                                 //Effect.Appear(node.childNodes[i], {duration : 0.3});
801                                         }
802                 
803                                         if (has_unread) {
804                                                 node.childNodes[i].style.display = "list-item";
805                                                 cat_unread++;
806                                                 //Effect.Appear(node.childNodes[i], {duration : 0.3});
807                                                 //Effect.Highlight(node.childNodes[i]);
808                                         }
809                                 }
810                         }
811                 }       
812         
813         //      console.log("end cat: " + node.id + " unread " + cat_unread);
814
815                 if (cat_node) {
816
817                         if (cat_unread == 0) {
818                                 if (cat_node.style == undefined) {
819                                         console.log("ERROR: supplied cat_node " + cat_node + 
820                                                 " has no styles. WTF?");
821                                         return;
822                                 }
823                                 if (hide) {
824                                         //cat_node.style.display = "none";
825                                         Effect.Fade(cat_node, {duration : 0.3, 
826                                                 queue: { position: 'end', scope: 'CFADE-' + node.id, limit: 1 }});
827                                 } else {
828                                         cat_node.style.display = "list-item";
829                                 }
830                         } else {
831                                 try {
832                                         cat_node.style.display = "list-item";
833                                 } catch (e) {
834                                         console.log(e);
835                                 }
836                         }
837                 }
838
839 //      console.log("unread for category: " + cat_unread);
840
841         } catch (e) {
842                 exception_error("hideOrShowFeedsCategory", e);
843         }
844 }
845
846 function selectTableRow(r, do_select) {
847         r.className = r.className.replace("Selected", "");
848         
849         if (do_select) {
850                 r.className = r.className + "Selected";
851         }
852 }
853
854 function selectTableRowById(elem_id, check_id, do_select) {
855
856         try {
857
858                 var row = $(elem_id);
859
860                 if (row) {
861                         selectTableRow(row, do_select);
862                 }               
863
864                 var check = $(check_id);
865
866                 if (check) {
867                         check.checked = do_select;
868                 }
869         } catch (e) {
870                 exception_error("selectTableRowById", e);
871         }
872 }
873
874 function selectTableRowsByIdPrefix(content_id, prefix, check_prefix, do_select, 
875         classcheck, reset_others) {
876
877         var content = $(content_id);
878
879         if (!content) {
880                 console.log("[selectTableRows] Element " + content_id + " not found.");
881                 return;
882         }
883
884         for (i = 0; i < content.rows.length; i++) {
885                 if (Element.visible(content.rows[i])) {
886                         if (!classcheck || content.rows[i].className.match(classcheck)) {
887                 
888                                 if (content.rows[i].id.match(prefix)) {
889                                         selectTableRow(content.rows[i], do_select);
890                                 
891                                         var row_id = content.rows[i].id.replace(prefix, "");
892                                         var check = $(check_prefix + row_id);
893         
894                                         if (check) {
895                                                 check.checked = do_select;
896                                         }
897                                 } else if (reset_others) {
898                                         selectTableRow(content.rows[i], false);
899         
900                                         var row_id = content.rows[i].id.replace(prefix, "");
901                                         var check = $(check_prefix + row_id);
902         
903                                         if (check) {
904                                                 check.checked = false;
905                                         }
906         
907                                 }
908                         } else if (reset_others) {
909                                 selectTableRow(content.rows[i], false);
910         
911                                 var row_id = content.rows[i].id.replace(prefix, "");
912                                 var check = $(check_prefix + row_id);
913         
914                                 if (check) {
915                                         check.checked = false;
916                                 }
917         
918                         }
919                 }
920         }
921 }
922
923 function getSelectedTableRowIds(content_id, prefix) {
924
925         var content = $(content_id);
926
927         if (!content) {
928                 console.log("[getSelectedTableRowIds] Element " + content_id + " not found.");
929                 return new Array();
930         }
931
932         var sel_rows = new Array();
933
934         for (i = 0; i < content.rows.length; i++) {
935                 if (content.rows[i].id.match(prefix) && 
936                                 content.rows[i].className.match("Selected")) {
937                                 
938                         var row_id = content.rows[i].id.replace(prefix + "-", "");
939                         sel_rows.push(row_id);  
940                 }
941         }
942
943         return sel_rows;
944
945 }
946
947 function toggleSelectRowById(sender, id) {
948         var row = $(id);
949
950         if (sender.checked) {
951                 if (!row.className.match("Selected")) {
952                         row.className = row.className + "Selected";
953                 }
954         } else {
955                 if (row.className.match("Selected")) {
956                         row.className = row.className.replace("Selected", "");
957                 }
958         }
959 }
960
961 function toggleSelectListRow(sender) {
962         var parent_row = sender.parentNode;
963
964         if (sender.checked) {
965                 if (!parent_row.className.match("Selected")) {
966                         parent_row.className = parent_row.className + "Selected";
967                 }
968         } else {
969                 if (parent_row.className.match("Selected")) {
970                         parent_row.className = parent_row.className.replace("Selected", "");
971                 }
972         }
973 }
974
975 function tSR(sender) {
976         return toggleSelectRow(sender);
977 }
978
979 function toggleSelectRow(sender) {
980         var parent_row = sender.parentNode.parentNode;
981
982         if (sender.checked) {
983                 if (!parent_row.className.match("Selected")) {
984                         parent_row.className = parent_row.className + "Selected";
985                 }
986         } else {
987                 if (parent_row.className.match("Selected")) {
988                         parent_row.className = parent_row.className.replace("Selected", "");
989                 }
990         }
991 }
992
993 function getNextUnreadCat(id) {
994         try {
995                 var rows = $("feedList").getElementsByTagName("LI");
996                 var feeds = new Array();
997
998                 var unread_only = true;
999                 var is_cat = true;
1000
1001                 for (var i = 0; i < rows.length; i++) {
1002                         if (rows[i].id.match("FCAT-")) {
1003                                 if (rows[i].id == "FCAT-" + id && is_cat || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1004
1005                                         var cat_id = parseInt(rows[i].id.replace("FCAT-", ""));
1006
1007                                         if (cat_id >= 0) {
1008                                                 if (!unread_only || get_cat_unread(cat_id) > 0) {
1009                                                         feeds.push(cat_id);
1010                                                 }
1011                                         }
1012                                 }
1013                         }
1014                 }
1015
1016                 var idx = feeds.indexOf(id);
1017                 if (idx != -1 && idx < feeds.length) {
1018                         return feeds[idx+1];                                    
1019                 } else {
1020                         return feeds.shift();
1021                 }
1022
1023         } catch (e) {
1024                 exception_error("getNextUnreadCat", e);
1025         }
1026 }
1027
1028 function getRelativeFeedId2(id, is_cat, direction, unread_only) {       
1029         try {
1030
1031 //              alert(id + " IC: " + is_cat + " D: " + direction + " U: " + unread_only);
1032
1033                 var rows = $("feedList").getElementsByTagName("LI");
1034                 var feeds = new Array();
1035         
1036                 for (var i = 0; i < rows.length; i++) {
1037                         if (rows[i].id.match("FEEDR-")) {
1038         
1039                                 if (rows[i].id == "FEEDR-" + id && !is_cat || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1040         
1041                                         if (!unread_only || 
1042                                                         (rows[i].className.match("Unread") || rows[i].id == "FEEDR-" + id)) {
1043                                                 feeds.push(rows[i].id.replace("FEEDR-", ""));
1044                                         }
1045                                 }
1046                         }
1047
1048                         if (rows[i].id.match("FCAT-")) {
1049                                 if (rows[i].id == "FCAT-" + id && is_cat || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1050
1051                                         var cat_id = parseInt(rows[i].id.replace("FCAT-", ""));
1052
1053                                         if (cat_id >= 0) {
1054                                                 if (!unread_only || get_cat_unread(cat_id) > 0) {
1055                                                         feeds.push("CAT:"+cat_id);
1056                                                 }
1057                                         }
1058                                 }
1059                         }
1060                 }
1061         
1062 //              alert(feeds.toString());
1063
1064                 if (!id) {
1065                         if (direction == "next") {
1066                                 return feeds.shift();
1067                         } else {
1068                                 return feeds.pop();
1069                         }
1070                 } else {
1071                         if (direction == "next") {
1072                                 if (is_cat) id = "CAT:" + id;
1073                                 var idx = feeds.indexOf(id);
1074                                 if (idx != -1 && idx < feeds.length) {
1075                                         return feeds[idx+1];                                    
1076                                 } else {
1077                                         return getRelativeFeedId2(false, is_cat, direction, unread_only);
1078                                 }
1079                         } else {
1080                                 if (is_cat) id = "CAT:" + id;
1081                                 var idx = feeds.indexOf(id);
1082                                 if (idx > 0) {
1083                                         return feeds[idx-1];
1084                                 } else {
1085                                         return getRelativeFeedId2(false, is_cat, direction, unread_only);
1086                                 }
1087                         }
1088         
1089                 }
1090
1091         } catch (e) {
1092                 exception_error("getRelativeFeedId2", e);
1093         }
1094 }
1095
1096 function getRelativeFeedId(list, id, direction, unread_only) {  
1097         var rows = list.getElementsByTagName("LI");
1098         var feeds = new Array();
1099
1100         for (var i = 0; i < rows.length; i++) {
1101                 if (rows[i].id.match("FEEDR-")) {
1102
1103                         if (rows[i].id == "FEEDR-" + id || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1104
1105                                 if (!unread_only || 
1106                                                 (rows[i].className.match("Unread") || rows[i].id == "FEEDR-" + id)) {
1107                                         feeds.push(rows[i].id.replace("FEEDR-", ""));
1108                                 }
1109                         }
1110                 }
1111         }
1112
1113         if (!id) {
1114                 if (direction == "next") {
1115                         return feeds.shift();
1116                 } else {
1117                         return feeds.pop();
1118                 }
1119         } else {
1120                 if (direction == "next") {
1121                         var idx = feeds.indexOf(id);
1122                         if (idx != -1 && idx < feeds.length) {
1123                                 return feeds[idx+1];                                    
1124                         } else {
1125                                 return getRelativeFeedId(list, false, direction, unread_only);
1126                         }
1127                 } else {
1128                         var idx = feeds.indexOf(id);
1129                         if (idx > 0) {
1130                                 return feeds[idx-1];
1131                         } else {
1132                                 return getRelativeFeedId(list, false, direction, unread_only);
1133                         }
1134                 }
1135
1136         }
1137 }
1138
1139 function showBlockElement(id, h_id) {
1140         var elem = $(id);
1141
1142         if (elem) {
1143                 elem.style.display = "block";
1144
1145                 if (h_id) {
1146                         elem = $(h_id);
1147                         if (elem) {
1148                                 elem.style.display = "none";
1149                         }
1150                 }
1151         } else {
1152                 alert("[showBlockElement] can't find element with id " + id);
1153         } 
1154 }
1155
1156 function appearBlockElement_afh(effect) {
1157
1158 }
1159
1160 function checkboxToggleElement(elem, id) {
1161         if (elem.checked) {
1162                 Effect.Appear(id, {duration : 0.5});
1163         } else {
1164                 Effect.Fade(id, {duration : 0.5});
1165         }
1166 }
1167
1168 function appearBlockElement(id, h_id) {
1169
1170         try {
1171                 if (h_id) {
1172                         Effect.Fade(h_id);
1173                 }
1174                 Effect.SlideDown(id, {duration : 1.0, afterFinish: appearBlockElement_afh});
1175         } catch (e) {
1176                 exception_error("appearBlockElement", e);
1177         }
1178
1179 }
1180
1181 function hideParentElement(e) {
1182         e.parentNode.style.display = "none";
1183 }
1184
1185 function dropboxSelect(e, v) {
1186         for (i = 0; i < e.length; i++) {
1187                 if (e[i].value == v) {
1188                         e.selectedIndex = i;
1189                         break;
1190                 }
1191         }
1192 }
1193
1194 // originally stolen from http://www.11tmr.com/11tmr.nsf/d6plinks/MWHE-695L9Z
1195 // bugfixed just a little bit :-)
1196 function getURLParam(strParamName){
1197   var strReturn = "";
1198   var strHref = window.location.href;
1199
1200   if (strHref.indexOf("#") == strHref.length-1) {
1201                 strHref = strHref.substring(0, strHref.length-1);
1202   }
1203
1204   if ( strHref.indexOf("?") > -1 ){
1205     var strQueryString = strHref.substr(strHref.indexOf("?"));
1206     var aQueryString = strQueryString.split("&");
1207     for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
1208       if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
1209         var aParam = aQueryString[iParam].split("=");
1210         strReturn = aParam[1];
1211         break;
1212       }
1213     }
1214   }
1215   return strReturn;
1216
1217
1218 function leading_zero(p) {
1219         var s = String(p);
1220         if (s.length == 1) s = "0" + s;
1221         return s;
1222 }
1223
1224 function make_timestamp() {
1225         var d = new Date();
1226
1227         return leading_zero(d.getHours()) + ":" + leading_zero(d.getMinutes()) +
1228                         ":" + leading_zero(d.getSeconds());
1229 }
1230
1231
1232 function closeErrorBox() {
1233
1234         if (Element.visible("errorBoxShadow")) {
1235                 Element.hide("dialog_overlay");
1236                 Element.hide("errorBoxShadow");
1237
1238                 enableHotkeys();
1239         }
1240
1241         return false;
1242 }
1243
1244 function closeInfoBox(cleanup) {
1245
1246         try {
1247                 enableHotkeys();
1248
1249                 if (Element.visible("infoBoxShadow")) {
1250                         Element.hide("dialog_overlay");
1251                         Element.hide("infoBoxShadow");
1252
1253                         if (cleanup) $("infoBox").innerHTML = "&nbsp;";
1254                 }
1255         } catch (e) {
1256                 exception_error("closeInfoBox", e);
1257         }
1258         
1259         return false;
1260 }
1261
1262
1263 function displayDlg(id, param, callback) {
1264
1265         notify_progress("Loading, please wait...", true);
1266
1267         disableHotkeys();
1268
1269         var query = "?op=dlg&id=" +
1270                 param_escape(id) + "&param=" + param_escape(param);
1271
1272         new Ajax.Request("backend.php", {
1273                 parameters: query,
1274                 onComplete: function (transport) {
1275                         infobox_callback2(transport);
1276                         if (callback) callback(transport);
1277                 } });
1278
1279         return false;
1280 }
1281
1282 function infobox_submit_callback2(transport) {
1283         closeInfoBox();
1284
1285         try {
1286                 // called from prefs, reload tab
1287                 if (typeof active_tab != 'undefined' && active_tab) {
1288                         selectTab(active_tab, false);
1289                 }
1290         } catch (e) { }
1291
1292         if (transport.responseText) {
1293                 notify_info(transport.responseText);
1294         }
1295 }
1296
1297 function infobox_callback2(transport) {
1298         try {
1299
1300                 console.log("infobox_callback2");
1301
1302                 var box = $('infoBox');
1303                 
1304                 if (box) {                      
1305
1306                         if (!getInitParam("infobox_disable_overlay")) {
1307                                 Element.show("dialog_overlay");
1308                         }
1309
1310                         box.innerHTML=transport.responseText;                   
1311                         Element.show("infoBoxShadow");
1312                         //Effect.SlideDown("infoBoxShadow", {duration : 1.0});
1313
1314
1315                 }
1316
1317                 disableHotkeys();
1318
1319                 notify("");
1320         } catch (e) {
1321                 exception_error("infobox_callback2", e);
1322         }
1323 }
1324
1325 function createFilter() {
1326
1327         try {
1328
1329                 var form = document.forms['filter_add_form'];
1330                 var reg_exp = form.reg_exp.value;
1331         
1332                 if (reg_exp == "") {
1333                         alert(__("Can't add filter: nothing to match on."));
1334                         return false;
1335                 }
1336         
1337                 var query = Form.serialize("filter_add_form");
1338         
1339                 // we can be called from some other tab in Prefs                
1340                 if (typeof active_tab != 'undefined' && active_tab) {
1341                         active_tab = "filterConfig";
1342                 }
1343         
1344                 new Ajax.Request("backend.php?" + query, {
1345                         onComplete: function (transport) {
1346                                 infobox_submit_callback2(transport);
1347                         } });
1348                 
1349                 return true;
1350
1351         } catch (e) {
1352                 exception_error("createFilter", e);
1353         }
1354 }
1355
1356 function isValidURL(s) {
1357         return s.match("http://") != null || s.match("https://") != null || s.match("feed://") != null;
1358 }
1359
1360 function subscribeToFeed() {
1361
1362         try {
1363
1364         var form = document.forms['feed_add_form'];
1365         var feed_url = form.feed_url.value;
1366
1367         if (feed_url == "") {
1368                 alert(__("Can't subscribe: no feed URL given."));
1369                 return false;
1370         }
1371
1372         notify_progress(__("Subscribing to feed..."), true);
1373
1374         var query = Form.serialize("feed_add_form");
1375         
1376         console.log("subscribe q: " + query);
1377
1378         Form.disable("feed_add_form");
1379
1380         new Ajax.Request("backend.php", {
1381                 parameters: query,
1382                 onComplete: function(transport) { 
1383                         //dlg_frefresh_callback(transport); 
1384
1385                         notify('');
1386
1387                         var result = transport.responseXML.getElementsByTagName('result')[0];
1388                         var rc = parseInt(result.getAttribute('code'));
1389
1390                         Form.enable("feed_add_form");
1391
1392                         switch (rc) {
1393                         case 1:
1394                                 closeInfoBox();
1395                                 notify_info(__("Subscribed to %s").replace("%s", feed_url));
1396
1397                                 if (inPreferences()) {
1398                                         updateFeedList();
1399                                 } else {
1400                                         setTimeout('updateFeedList(false, false)', 50);
1401                                 }
1402                                 break;
1403                         case 2:
1404                                 alert(__("Can't subscribe to the specified URL."));
1405                                 break;
1406                         case 0:
1407                                 alert(__("You are already subscribed to this feed."));
1408                                 break;
1409                         }
1410
1411                 } });
1412
1413         } catch (e) {
1414                 exception_error("subscribeToFeed", e);
1415         }
1416
1417         return false;
1418 }
1419
1420 function filterCR(e, f)
1421 {
1422      var key;
1423
1424      if(window.event)
1425           key = window.event.keyCode;     //IE
1426      else
1427           key = e.which;     //firefox
1428
1429         if (key == 13) {
1430                 if (typeof f != 'undefined') {
1431                         f();
1432                         return false;
1433                 } else {
1434                         return false;
1435                 }
1436         } else {
1437                 return true;
1438         }
1439 }
1440
1441 var debug_last_class = "even";
1442
1443 function debug(msg) {
1444
1445         if (debug_last_class == "even") {
1446                 debug_last_class = "odd";
1447         } else {
1448                 debug_last_class = "even";
1449         }
1450
1451         var c = $('debug_output');
1452         if (c && Element.visible(c)) {
1453                 while (c.lastChild != 'undefined' && c.childNodes.length > 100) {
1454                         c.removeChild(c.lastChild);
1455                 }
1456         
1457                 var ts = make_timestamp();
1458                 c.innerHTML = "<li class=\"" + debug_last_class + "\"><span class=\"debugTS\">[" + ts + "]</span> " + 
1459                         msg + "</li>" + c.innerHTML;
1460         }
1461 }
1462
1463 function getInitParam(key) {
1464         return init_params[key];
1465 }
1466
1467 function setInitParam(key, value) {
1468         init_params[key] = value;
1469 }
1470
1471 function fatalError(code, msg, ext_info) {
1472         try {   
1473
1474                 if (!ext_info) ext_info = "N/A";
1475
1476                 if (code == 6) {
1477                         window.location.href = "tt-rss.php";                    
1478                 } else if (code == 5) {
1479                         window.location.href = "update.php";
1480                 } else {
1481         
1482                         if (msg == "") msg = "Unknown error";
1483
1484                         var ebc = $("xebContent");
1485         
1486                         if (ebc) {
1487         
1488                                 Element.show("dialog_overlay");
1489                                 Element.show("errorBoxShadow");
1490                                 Element.hide("xebBtn");
1491
1492                                 if (ext_info) {
1493                                         if (ext_info.responseText) {
1494                                                 ext_info = ext_info.responseText;
1495                                         }
1496                                 }
1497         
1498                                 ebc.innerHTML = 
1499                                         "<div><b>Error message:</b></div>" +
1500                                         "<pre>" + msg + "</pre>" +
1501                                         "<div><b>Additional information:</b></div>" +
1502                                         "<textarea readonly=\"1\">" + ext_info + "</textarea>";
1503                         }
1504                 }
1505
1506         } catch (e) {
1507                 exception_error("fatalError", e);
1508         }
1509 }
1510
1511 function getFeedName(id, is_cat) {      
1512         var e;
1513
1514         if (is_cat) {
1515                 e = $("FCATN-" + id);
1516         } else {
1517                 e = $("FEEDN-" + id);
1518         }
1519         if (e) {
1520                 return e.innerHTML.stripTags();
1521         } else {
1522                 return null;
1523         }
1524 }
1525
1526 function filterDlgCheckType(sender) {
1527
1528         try {
1529
1530                 var ftype = sender[sender.selectedIndex].value;
1531
1532                 var form = document.forms["filter_add_form"];
1533         
1534                 if (!form) {
1535                         form = document.forms["filter_edit_form"];
1536                 }
1537
1538                 if (!form) {
1539                         console.log("filterDlgCheckType: can't find form!");
1540                         return;
1541                 }
1542
1543                 // if selected filter type is 5 (Date) enable the modifier dropbox
1544                 if (ftype == 5) {
1545                         Element.show("filter_dlg_date_mod_box");
1546                         Element.show("filter_dlg_date_chk_box");
1547                 } else {
1548                         Element.hide("filter_dlg_date_mod_box");
1549                         Element.hide("filter_dlg_date_chk_box");
1550
1551                 }
1552
1553         } catch (e) {
1554                 exception_error("filterDlgCheckType", e);
1555         }
1556
1557 }
1558
1559 function filterDlgCheckAction(sender) {
1560
1561         try {
1562
1563                 var action = sender[sender.selectedIndex].value;
1564
1565                 var form = document.forms["filter_add_form"];
1566         
1567                 if (!form) {
1568                         form = document.forms["filter_edit_form"];
1569                 }
1570
1571                 if (!form) {
1572                         console.log("filterDlgCheckAction: can't find form!");
1573                         return;
1574                 }
1575
1576                 var action_param = $("filter_dlg_param_box");
1577
1578                 if (!action_param) {
1579                         console.log("filterDlgCheckAction: can't find action param box!");
1580                         return;
1581                 }
1582
1583                 // if selected action supports parameters, enable params field
1584                 if (action == 4 || action == 6 || action == 7) {
1585                         Element.show(action_param);
1586                         if (action != 7) {
1587                                 Element.show(form.action_param);
1588                                 Element.hide(form.action_param_label);
1589                         } else {
1590                                 Element.show(form.action_param_label);
1591                                 Element.hide(form.action_param);
1592                         }
1593                 } else {
1594                         Element.hide(action_param);
1595                 }
1596
1597         } catch (e) {
1598                 exception_error("filterDlgCheckAction", e);
1599         }
1600
1601 }
1602
1603 function filterDlgCheckDate() {
1604         try {
1605                 var form = document.forms["filter_add_form"];
1606         
1607                 if (!form) {
1608                         form = document.forms["filter_edit_form"];
1609                 }
1610
1611                 if (!form) {
1612                         console.log("filterDlgCheckAction: can't find form!");
1613                         return;
1614                 }
1615
1616                 var reg_exp = form.reg_exp.value;
1617
1618                 var query = "?op=rpc&subop=checkDate&date=" + reg_exp;
1619
1620                 new Ajax.Request("backend.php", {
1621                         parameters: query,
1622                         onComplete: function(transport) { 
1623
1624                                 var form = document.forms["filter_add_form"];
1625         
1626                                 if (!form) {
1627                                         form = document.forms["filter_edit_form"];
1628                                 }
1629
1630                                 if (transport.responseXML) {
1631                                         var result = transport.responseXML.getElementsByTagName("result")[0];
1632
1633                                         if (result && result.firstChild) {
1634                                                 if (result.firstChild.nodeValue == "1") {
1635
1636                                                         new Effect.Highlight(form.reg_exp, {startcolor : '#00ff00'});
1637
1638                                                         return;
1639                                                 }
1640                                         }
1641                                 }
1642
1643                                 new Effect.Highlight(form.reg_exp, {startcolor : '#ff0000'});
1644
1645                         } });
1646
1647
1648         } catch (e) {
1649                 exception_error("filterDlgCheckDate", e);
1650         }
1651 }
1652
1653 function explainError(code) {
1654         return displayDlg("explainError", code);
1655 }
1656
1657 // this only searches loaded headlines list, not in CDM
1658 function getRelativePostIds(id, limit) {
1659
1660         if (!limit) limit = 3;
1661
1662         console.log("getRelativePostIds: " + id + " limit=" + limit);
1663
1664         var ids = new Array();
1665         var container = $("headlinesList");
1666
1667         if (container) {
1668                 var rows = container.rows;
1669
1670                 for (var i = 0; i < rows.length; i++) {
1671                         var r_id = rows[i].id.replace("RROW-", "");
1672
1673                         if (r_id == id) {
1674                                 for (var k = 1; k <= limit; k++) {
1675                                         var nid = false;
1676
1677                                         if (i > k-1) var nid = rows[i-k].id.replace("RROW-", "");
1678                                         if (nid) ids.push(nid);
1679
1680                                         if (i < rows.length-k) nid = rows[i+k].id.replace("RROW-", "");
1681                                         if (nid) ids.push(nid);
1682                                 }
1683
1684                                 return ids;
1685                         }
1686                 }
1687         }
1688
1689         return false;
1690 }
1691
1692 function openArticleInNewWindow(id) {
1693         try {
1694                 console.log("openArticleInNewWindow: " + id);
1695
1696                 var query = "?op=rpc&subop=getArticleLink&id=" + id;
1697                 var wname = "ttrss_article_" + id;
1698
1699                 console.log(query + " " + wname);
1700
1701                 var w = window.open("", wname);
1702
1703                 if (!w) notify_error("Failed to open window for the article");
1704
1705                 new Ajax.Request("backend.php", {
1706                         parameters: query,
1707                         onComplete: function(transport) { 
1708
1709                                         var link = transport.responseXML.getElementsByTagName("link")[0];
1710                                         var id = transport.responseXML.getElementsByTagName("id")[0];
1711                 
1712                                         console.log("open_article received link: " + link);
1713                 
1714                                         if (link && id) {
1715                 
1716                                                 var wname = "ttrss_article_" + id.firstChild.nodeValue;
1717                 
1718                                                 console.log("link url: " + link.firstChild.nodeValue + ", wname " + wname);
1719                 
1720                                                 var w = window.open(link.firstChild.nodeValue, wname);
1721                 
1722                                                 if (!w) { notify_error("Failed to load article in new window"); }
1723                 
1724                                                 if (id) {
1725                                                         id = id.firstChild.nodeValue;
1726                                                         if (!$("headlinesList")) {
1727                                                                 window.setTimeout("toggleUnread(" + id + ", 0)", 100);
1728                                                         }
1729                                                 }
1730                                         } else {
1731                                                 notify_error("Can't open article: received invalid article link");
1732                                         }
1733                                 } });
1734
1735         } catch (e) {
1736                 exception_error("openArticleInNewWindow", e);
1737         }
1738 }
1739
1740 /* http://textsnippets.com/posts/show/835 */
1741
1742 Position.GetWindowSize = function(w) {
1743         w = w ? w : window;
1744         var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
1745         var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
1746         return [width, height]
1747 }
1748
1749 /* http://textsnippets.com/posts/show/836 */
1750
1751 Position.Center = function(element, parent) {
1752         var w, h, pw, ph;
1753         var d = Element.getDimensions(element);
1754         w = d.width;
1755         h = d.height;
1756         Position.prepare();
1757         if (!parent) {
1758                 var ws = Position.GetWindowSize();
1759                 pw = ws[0];
1760                 ph = ws[1];
1761         } else {
1762                 pw = parent.offsetWidth;
1763                 ph = parent.offsetHeight;
1764         }
1765         element.style.top = (ph/2) - (h/2) -  Position.deltaY + "px";
1766         element.style.left = (pw/2) - (w/2) -  Position.deltaX + "px";
1767 }
1768
1769
1770 function isCdmMode() {
1771         return !$("headlinesList");
1772 }
1773
1774 function getSelectedArticleIds2() {
1775         var rows = new Array();
1776         var cdm_mode = isCdmMode();
1777
1778         if (cdm_mode) {
1779                 rows = cdmGetSelectedArticles();
1780         } else {        
1781                 rows = getSelectedTableRowIds("headlinesList", "RROW", "RCHK");
1782         }
1783
1784         var ids = new Array();
1785
1786         for (var i = 0; i < rows.length; i++) {
1787                 var chk = $("RCHK-" + rows[i]);
1788                 if (chk && chk.checked) {
1789                         ids.push(rows[i]);
1790                 }
1791         }
1792
1793         return ids;
1794 }
1795
1796 function displayHelpInfobox(topic_id) {
1797
1798         var url = "backend.php?op=help&tid=" + param_escape(topic_id);
1799
1800         var w = window.open(url, "ttrss_help", 
1801                 "status=0,toolbar=0,location=0,width=450,height=500,scrollbars=1,menubar=0");
1802
1803 }
1804
1805 function focus_element(id) {
1806         try {
1807                 var e = $(id);
1808                 if (e) e.focus();
1809         } catch (e) {
1810                 exception_error("focus_element", e);
1811         }
1812         return false;
1813 }
1814
1815 function loading_set_progress(p) {
1816         try {
1817                 if (p < last_progress_point || !Element.visible("overlay")) return;
1818
1819                 console.log("<b>loading_set_progress : " + p + " (" + last_progress_point + ")</b>");
1820
1821                 var o = $("l_progress_i");
1822
1823 //              o.style.width = (p * 2) + "px";
1824
1825                 new Effect.Scale(o, p, { 
1826                         scaleY : false,
1827                         scaleFrom : last_progress_point,
1828                         scaleMode: { originalWidth : 200 },
1829                         queue: { position: 'end', scope: 'LSP-Q', limit: 3 } }); 
1830
1831                 last_progress_point = p;
1832
1833         } catch (e) {
1834                 exception_error("loading_set_progress", e);
1835         }
1836 }
1837
1838 function remove_splash() {
1839         if (Element.visible("overlay")) {
1840                 console.log("about to remove splash, OMG!");
1841                 Element.hide("overlay");
1842                 console.log("removed splash!");
1843         }
1844 }
1845
1846 function getSelectedFeedsFromBrowser() {
1847
1848         var list = $("browseFeedList");
1849
1850         var selected = new Array();
1851         
1852         for (i = 0; i < list.childNodes.length; i++) {
1853                 var child = list.childNodes[i];
1854                 if (child.id && child.id.match("FBROW-")) {
1855                         var id = child.id.replace("FBROW-", "");
1856                         
1857                         var cb = $("FBCHK-" + id);
1858
1859                         if (cb.checked) {
1860                                 selected.push(id);
1861                         }
1862                 }
1863         }
1864
1865         return selected;
1866 }
1867
1868 function updateFeedBrowser() {
1869         try {
1870
1871                 var query = Form.serialize("feed_browser");
1872
1873                 Element.show('feed_browser_spinner');
1874
1875                 new Ajax.Request("backend.php", {
1876                         parameters: query,
1877                         onComplete: function(transport) { 
1878                                 notify('');
1879
1880                                 Element.hide('feed_browser_spinner');
1881
1882                                 var c = $("browseFeedList");
1883                                 var r = transport.responseXML.getElementsByTagName("content")[0];
1884                                 var nr = transport.responseXML.getElementsByTagName("num-results")[0];
1885                                 var mode = transport.responseXML.getElementsByTagName("mode")[0];
1886
1887                                 if (c && r) {
1888                                         c.innerHTML = r.firstChild.nodeValue;
1889                                 }
1890
1891                                 if (parseInt(mode.getAttribute("value")) == 2) {
1892                                         Element.show('feed_archive_remove');
1893                                 } else {
1894                                         Element.hide('feed_archive_remove');
1895                                 }
1896         
1897                         } });
1898
1899         } catch (e) {
1900                 exception_error("updateFeedBrowser", e);
1901         }
1902
1903 }
1904
1905 function transport_error_check(transport) {
1906         try {
1907                 if (transport.responseXML) {
1908                         var error = transport.responseXML.getElementsByTagName("error")[0];
1909
1910                         if (error) {
1911                                 var code = error.getAttribute("error-code");
1912                                 var msg = error.getAttribute("error-msg");
1913                                 if (code != 0) {
1914                                         fatalError(code, msg);
1915                                         return false;
1916                                 }
1917                         }
1918                 }
1919         } catch (e) {
1920                 exception_error("check_for_error_xml", e);
1921         }
1922         return true;
1923 }
1924
1925 function strip_tags(s) {
1926         return s.replace(/<\/?[^>]+(>|$)/g, "");
1927 }
1928
1929 function truncate_string(s, length) {
1930         if (!length) length = 30;
1931         var tmp = s.substring(0, length);
1932         if (s.length > length) tmp += "&hellip;";
1933         return tmp;
1934 }
1935
1936 function hotkey_prefix_timeout() {
1937         try {
1938
1939                 var date = new Date();
1940                 var ts = Math.round(date.getTime() / 1000);
1941
1942                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
1943                         console.log("hotkey_prefix seems to be stuck, aborting");
1944                         hotkey_prefix_pressed = false;
1945                         hotkey_prefix = false;
1946                         Element.hide('cmdline');
1947                 }
1948
1949                 setTimeout("hotkey_prefix_timeout()", 1000);
1950
1951         } catch  (e) {
1952                 exception_error("hotkey_prefix_timeout", e);
1953         }
1954 }
1955
1956 function hideAuxDlg() {
1957         try {
1958                 Element.hide('auxDlg');
1959         } catch (e) {
1960                 exception_error("hideAuxDlg", e);
1961         }
1962 }
1963
1964 function displayNewContentPrompt(id) {
1965         try {
1966
1967                 var msg = "<a href='#' onclick='viewfeed("+id+")'>" +
1968                         __("New articles available in this feed (click to show)") + "</a>";
1969
1970                 msg = msg.replace("%s", getFeedName(id));
1971
1972                 $('auxDlg').innerHTML = msg;
1973
1974                 Element.show('auxDlg');
1975
1976         } catch (e) {
1977                 exception_error("displayNewContentPrompt", e);
1978         }
1979 }
1980
1981 function feedBrowserSubscribe() {
1982         try {
1983
1984                 var selected = getSelectedFeedsFromBrowser();
1985
1986                 var mode = document.forms['feed_browser'].mode;
1987
1988                 mode = mode[mode.selectedIndex].value;
1989
1990                 if (selected.length > 0) {
1991                         closeInfoBox();
1992
1993                         notify_progress("Loading, please wait...", true);
1994
1995                         var query = "?op=rpc&subop=massSubscribe&ids="+
1996                                 param_escape(selected.toString()) + "&mode=" + param_escape(mode);
1997
1998                         new Ajax.Request("backend.php", {
1999                                 parameters: query,
2000                                 onComplete: function(transport) { 
2001
2002                                         var nf = transport.responseXML.getElementsByTagName('num-feeds')[0];
2003                                         var nf_value = nf.getAttribute("value");
2004
2005                                         notify_info(__("Subscribed to %d feed(s).").replace("%d", nf_value));
2006
2007                                         if (inPreferences()) {
2008                                                 updateFeedList();
2009                                         } else {
2010                                                 setTimeout('updateFeedList(false, false)', 50);
2011                                         }
2012                                 } });
2013
2014                 } else {
2015                         alert(__("No feeds are selected."));
2016                 }
2017
2018         } catch (e) {
2019                 exception_error("feedBrowserSubscribe", e);
2020         }
2021 }
2022
2023 function feedArchiveRemove() {
2024         try {
2025
2026                 var selected = getSelectedFeedsFromBrowser();
2027
2028                 if (selected.length > 0) {
2029
2030                         var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
2031
2032                         if (confirm(pr)) {
2033                                 Element.show('feed_browser_spinner');
2034
2035                                 var query = "?op=rpc&subop=remarchived&ids=" + 
2036                                         param_escape(selected.toString());;
2037
2038                                 new Ajax.Request("backend.php", {
2039                                         parameters: query,
2040                                         onComplete: function(transport) { 
2041                                                 updateFeedBrowser();
2042                                         } }); 
2043                         }
2044
2045                 } else {
2046                         alert(__("No feeds are selected."));
2047                 }
2048
2049         } catch (e) {
2050                 exception_error("feedArchiveRemove", e);
2051         }
2052 }
2053
2054 function uploadIconHandler(rc) {
2055         try {
2056                 switch (rc) {
2057                         case 0:
2058                                 notify_info("Upload complete.");
2059                                 if (inPreferences()) {
2060                                         updateFeedList();
2061                                 } else {
2062                                         setTimeout('updateFeedList(false, false)', 50);
2063                                 }
2064                                 break;
2065                         case 1:
2066                                 notify_error("Upload failed: icon is too big.");
2067                                 break;
2068                         case 2:
2069                                 notify_error("Upload failed.");
2070                                 break;
2071                 }
2072
2073         } catch (e) {
2074                 exception_error("uploadIconHandler", e);
2075         }
2076 }
2077
2078 function removeFeedIcon(id) {
2079
2080         try {
2081
2082                 if (confirm(__("Remove stored feed icon?"))) {
2083                         var query = "backend.php?op=pref-feeds&subop=removeicon&feed_id=" + param_escape(id);
2084
2085                         console.log(query);
2086
2087                         notify_progress("Removing feed icon...", true);
2088
2089                         new Ajax.Request("backend.php", {
2090                                 parameters: query,
2091                                 onComplete: function(transport) { 
2092                                         notify_info("Feed icon removed.");
2093                                         if (inPreferences()) {
2094                                                 updateFeedList();
2095                                         } else {
2096                                                 setTimeout('updateFeedList(false, false)', 50);
2097                                         }
2098                                 } }); 
2099                 }
2100
2101                 return false;
2102         } catch (e) {
2103                 exception_error("uploadFeedIcon", e);
2104         }
2105 }
2106
2107 function uploadFeedIcon() {
2108
2109         try {
2110
2111                 var file = $("icon_file");
2112
2113                 if (file.value.length == 0) {
2114                         alert(__("Please select an image file to upload."));
2115                 } else {
2116                         if (confirm(__("Upload new icon for this feed?"))) {
2117                                 notify_progress("Uploading, please wait...", true);
2118                                 return true;
2119                         }
2120                 }
2121
2122                 return false;
2123
2124         } catch (e) {
2125                 exception_error("uploadFeedIcon", e);
2126         }
2127 }
2128
2129 function addLabel() {
2130
2131         try {
2132
2133                 var caption = prompt(__("Please enter label caption:"), "");
2134
2135                 if (caption != undefined) {
2136         
2137                         if (caption == "") {
2138                                 alert(__("Can't create label: missing caption."));
2139                                 return false;
2140                         }
2141
2142                         var query = "?op=pref-labels&subop=add&caption=" + 
2143                                 param_escape(caption);
2144
2145                         notify_progress("Loading, please wait...", true);
2146
2147                         if (inPreferences()) active_tab = "labelConfig";
2148
2149                         new Ajax.Request("backend.php", {
2150                                 parameters: query,
2151                                 onComplete: function(transport) { 
2152                                         if (inPreferences()) {
2153                                                 infobox_submit_callback2(transport);
2154                                         } else {
2155                                                 updateFeedList();
2156                                         }
2157                         } });
2158
2159                 }
2160
2161         } catch (e) {
2162                 exception_error("addLabel", e);
2163         }
2164 }
2165
2166 function quickAddFeed() {
2167         displayDlg('quickAddFeed', '',
2168            function () {$('feed_url').focus();});
2169 }
2170
2171 function quickAddFilter() {
2172         displayDlg('quickAddFilter', '',
2173            function () {document.forms['filter_add_form'].reg_exp.focus();});
2174 }
2175
2176 function unsubscribeFeed(feed_id, title) {
2177
2178         var msg = __("Unsubscribe from %s?").replace("%s", title);
2179
2180         if (title == undefined || confirm(msg)) {
2181                 notify_progress("Removing feed...");
2182
2183                 var query = "?op=pref-feeds&quiet=1&subop=remove&ids=" + feed_id;
2184
2185                 new Ajax.Request("backend.php", {
2186                         parameters: query,
2187                         onComplete: function(transport) {
2188
2189                                         closeInfoBox();
2190
2191                                         if (inPreferences()) {
2192                                                 updateFeedList();                               
2193                                         } else {
2194                                                 dlg_frefresh_callback(transport, feed_id);
2195                                         }
2196
2197                                 } });
2198         }
2199
2200         return false;
2201 }
2202
2203
2204 function backend_sanity_check_callback(transport) {
2205
2206         try {
2207
2208                 if (sanity_check_done) {
2209                         fatalError(11, "Sanity check request received twice. This can indicate "+
2210                       "presence of Firebug or some other disrupting extension. "+
2211                                 "Please disable it and try again.");
2212                         return;
2213                 }
2214
2215                 if (!transport.responseXML) {
2216                         if (!store) {
2217                                 fatalError(3, "Sanity check: Received reply is not XML", 
2218                                         transport.responseText);
2219                                 return;
2220                         } else {
2221                                 init_offline();
2222                                 return;
2223                         }
2224                 }
2225
2226                 if (getURLParam("offline")) {
2227                         return init_offline();
2228                 }
2229
2230                 var reply = transport.responseXML.firstChild.firstChild;
2231
2232                 if (!reply) {
2233                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
2234                         return;
2235                 }
2236
2237                 var error_code = reply.getAttribute("error-code");
2238         
2239                 if (error_code && error_code != 0) {
2240                         return fatalError(error_code, reply.getAttribute("error-msg"));
2241                 }
2242
2243                 console.log("sanity check ok");
2244
2245                 var params = reply.nextSibling;
2246
2247                 if (params) {
2248                         console.log('reading init-params...');
2249                         var param = params.firstChild;
2250
2251                         while (param) {
2252                                 var k = param.getAttribute("key");
2253                                 var v = param.getAttribute("value");
2254                                 console.log(k + " => " + v);
2255                                 init_params[k] = v;                                     
2256
2257                                 if (db) {
2258                                         db.execute("DELETE FROM init_params WHERE key = ?", [k]);
2259                                         db.execute("INSERT INTO init_params (key,value) VALUES (?, ?)",
2260                                                 [k, v]);
2261                                 }
2262
2263                                 param = param.nextSibling;
2264                         }
2265                 }
2266
2267                 sanity_check_done = true;
2268
2269                 init_second_stage();
2270
2271         } catch (e) {
2272                 exception_error("backend_sanity_check_callback", e, transport); 
2273         } 
2274 }
2275
2276