]> git.wh0rd.org Git - tt-rss.git/blob - functions.js
change counter.cat and counter.tag to counter.kind
[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 = JSON.parse(reply.firstChild.nodeValue);
387
388                 for (var l = 0; l < elems.length; l++) {
389
390                         var id = elems[l].id
391                         var kind = elems[l].kind;
392                         var ctr = parseInt(elems[l].counter)
393                         var error = elems[l].error;
394                         var has_img = elems[l].has_img;
395                         var updated = elems[l].updated;
396                         var title = elems[l].title;
397                         var xmsg = elems[l].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 (kind && kind == "cat") {
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_url") + "/" + 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         if (counters)
566                 parse_counters(counters, scheduled_call);
567
568         var runtime_info = reply.getElementsByTagName("runtime-info")[0];
569
570         if (runtime_info)
571                 parse_runtime_info(runtime_info);
572
573         if (feedsSortByUnread()) {
574                 resort_feedlist();
575         }
576
577         hideOrShowFeeds(getInitParam("hide_read_feeds") == 1);
578
579 }
580
581 function all_counters_callback2(transport, async_call) {
582         try {
583                 if (async_call) async_counters_work = true;
584                 
585                 if (offline_mode) return;
586
587                 console.log("<b>all_counters_callback2 IN: " + transport + "</b>");
588                 parse_counters_reply(transport);
589                 console.log("<b>all_counters_callback2 OUT: " + transport + "</b>");
590
591         } catch (e) {
592                 exception_error("all_counters_callback2", e, transport);
593         }
594 }
595
596 function get_feed_unread(id) {
597         try {
598                 return parseInt($("FEEDU-" + id).innerHTML);    
599         } catch (e) {
600                 return -1;
601         }
602 }
603
604 function get_cat_unread(id) {
605         try {
606                 var ctr = $("FCATCTR-" + id).innerHTML;
607                 ctr = ctr.replace("(", "");
608                 ctr = ctr.replace(")", "");
609                 return parseInt(ctr);
610         } catch (e) {
611                 return -1;
612         }
613 }
614
615 function get_feed_entry_unread(elem) {
616
617         var id = elem.id.replace("FEEDR-", "");
618
619         if (id <= 0) {
620                 return -1;
621         }
622
623         try {
624                 return parseInt($("FEEDU-" + id).innerHTML);    
625         } catch (e) {
626                 return -1;
627         }
628 }
629
630 function get_feed_entry_name(elem) {
631         var id = elem.id.replace("FEEDR-", "");
632         return getFeedName(id);
633 }
634
635
636 function resort_category(node, cat_mode) {
637
638         try {
639
640                 console.log("resort_category: " + node + " CM=" + cat_mode);
641         
642                 var by_unread = feedsSortByUnread();
643         
644                 var list = node.getElementsByTagName("LI");
645         
646                 for (i = 0; i < list.length; i++) {
647         
648                         for (j = i+1; j < list.length; j++) {                   
649         
650                                 var tmp_val = get_feed_entry_unread(list[i]);
651                                 var cur_val = get_feed_entry_unread(list[j]);
652         
653                                 var tmp_name = get_feed_entry_name(list[i]);
654                                 var cur_name = get_feed_entry_name(list[j]);
655
656                                 var valid_pair = cat_mode || (list[i].id.match(/FEEDR-[0-9]/) &&
657                                                 list[j].id.match(/FEEDR-[0-9]/));
658
659                                 if (valid_pair && ((by_unread && (cur_val > tmp_val)) || (!by_unread && (cur_name < tmp_name)))) {
660                                         tempnode_i = list[i].cloneNode(true);
661                                         tempnode_j = list[j].cloneNode(true);
662                                         node.replaceChild(tempnode_i, list[j]);
663                                         node.replaceChild(tempnode_j, list[i]);
664                                 }
665                         }
666                 }
667
668         } catch (e) {
669                 exception_error("resort_category", e);
670         }
671
672 }
673
674 function resort_feedlist() {
675         console.log("resort_feedlist");
676
677         if ($("FCATLIST--1")) {
678
679                 var lists = document.getElementsByTagName("UL");
680
681                 for (var i = 0; i < lists.length; i++) {
682                         if (lists[i].id && lists[i].id.match("FCATLIST-")) {
683                                 resort_category(lists[i], true);
684                         }
685                 }
686
687         } else {
688                 resort_category($("feedList"), false);
689         }
690 }
691
692 /** * @(#)isNumeric.js * * Copyright (c) 2000 by Sundar Dorai-Raj
693   * * @author Sundar Dorai-Raj
694   * * Email: sdoraira@vt.edu
695   * * This program is free software; you can redistribute it and/or
696   * * modify it under the terms of the GNU General Public License 
697   * * as published by the Free Software Foundation; either version 2 
698   * * of the License, or (at your option) any later version, 
699   * * provided that any use properly credits the author. 
700   * * This program is distributed in the hope that it will be useful,
701   * * but WITHOUT ANY WARRANTY; without even the implied warranty of
702   * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
703   * * GNU General Public License for more details at http://www.gnu.org * * */
704
705   var numbers=".0123456789";
706   function isNumeric(x) {
707     // is x a String or a character?
708     if(x.length>1) {
709       // remove negative sign
710       x=Math.abs(x)+"";
711       for(j=0;j<x.length;j++) {
712         // call isNumeric recursively for each character
713         number=isNumeric(x.substring(j,j+1));
714         if(!number) return number;
715       }
716       return number;
717     }
718     else {
719       // if x is number return true
720       if(numbers.indexOf(x)>=0) return true;
721       return false;
722     }
723   }
724
725
726 function hideOrShowFeeds(hide) {
727
728         try {
729
730         console.log("hideOrShowFeeds: " + hide);
731
732         if ($("FCATLIST--1")) {
733
734                 var lists = document.getElementsByTagName("UL");
735
736                 for (var i = 0; i < lists.length; i++) {
737                         if (lists[i].id && lists[i].id.match("FCATLIST-")) {
738
739                                 var id = lists[i].id.replace("FCATLIST-", "");
740                                 hideOrShowFeedsCategory(id, hide);
741                         }
742                 }
743
744         } else {
745                 hideOrShowFeedsCategory(null, hide);
746         }
747
748         } catch (e) {
749                 exception_error("hideOrShowFeeds", e);
750         }
751 }
752
753 function hideOrShowFeedsCategory(id, hide) {
754
755         try {
756         
757                 var node = null;
758                 var cat_node = null;
759
760                 if (id) {
761                         node = $("FCATLIST-" + id);
762                         cat_node = $("FCAT-" + id);
763                 } else {
764                         node = $("feedList"); // no categories
765                 }
766
767         //      console.log("hideOrShowFeedsCategory: " + node + " (" + hide + ")");
768         
769                 var cat_unread = 0;
770         
771                 if (!node) {
772                         console.log("hideOrShowFeeds: passed node is null, aborting");
773                         return;
774                 }
775         
776         //      console.log("cat: " + node.id);
777         
778                 if (node.hasChildNodes() && node.firstChild.nextSibling != false) {  
779                         for (i = 0; i < node.childNodes.length; i++) {
780                                 if (node.childNodes[i].nodeName != "LI") { continue; }
781         
782                                 if (node.childNodes[i].style != undefined) {
783         
784                                         var has_unread = (node.childNodes[i].className != "feed" &&
785                                                 node.childNodes[i].className != "label" && 
786                                                 !(!getInitParam("hide_read_shows_special") && 
787                                                         node.childNodes[i].className == "virt") && 
788                                                 node.childNodes[i].className != "error" && 
789                                                 node.childNodes[i].className != "tag");
790                 
791         //                              console.log(node.childNodes[i].id + " --> " + has_unread);
792                 
793                                         if (hide && !has_unread) {
794                                                 //node.childNodes[i].style.display = "none";
795                                                 var id = node.childNodes[i].id;
796                                                 Effect.Fade(node.childNodes[i], {duration : 0.3, 
797                                                         queue: { position: 'end', scope: 'FFADE-' + id, limit: 1 }});
798                                         }
799                 
800                                         if (!hide) {
801                                                 node.childNodes[i].style.display = "list-item";
802                                                 //Effect.Appear(node.childNodes[i], {duration : 0.3});
803                                         }
804                 
805                                         if (has_unread) {
806                                                 node.childNodes[i].style.display = "list-item";
807                                                 cat_unread++;
808                                                 //Effect.Appear(node.childNodes[i], {duration : 0.3});
809                                                 //Effect.Highlight(node.childNodes[i]);
810                                         }
811                                 }
812                         }
813                 }       
814         
815         //      console.log("end cat: " + node.id + " unread " + cat_unread);
816
817                 if (cat_node) {
818
819                         if (cat_unread == 0) {
820                                 if (cat_node.style == undefined) {
821                                         console.log("ERROR: supplied cat_node " + cat_node + 
822                                                 " has no styles. WTF?");
823                                         return;
824                                 }
825                                 if (hide) {
826                                         //cat_node.style.display = "none";
827                                         Effect.Fade(cat_node, {duration : 0.3, 
828                                                 queue: { position: 'end', scope: 'CFADE-' + node.id, limit: 1 }});
829                                 } else {
830                                         cat_node.style.display = "list-item";
831                                 }
832                         } else {
833                                 try {
834                                         cat_node.style.display = "list-item";
835                                 } catch (e) {
836                                         console.log(e);
837                                 }
838                         }
839                 }
840
841 //      console.log("unread for category: " + cat_unread);
842
843         } catch (e) {
844                 exception_error("hideOrShowFeedsCategory", e);
845         }
846 }
847
848 function selectTableRow(r, do_select) {
849         r.className = r.className.replace("Selected", "");
850         
851         if (do_select) {
852                 r.className = r.className + "Selected";
853         }
854 }
855
856 function selectTableRowById(elem_id, check_id, do_select) {
857
858         try {
859
860                 var row = $(elem_id);
861
862                 if (row) {
863                         selectTableRow(row, do_select);
864                 }               
865
866                 var check = $(check_id);
867
868                 if (check) {
869                         check.checked = do_select;
870                 }
871         } catch (e) {
872                 exception_error("selectTableRowById", e);
873         }
874 }
875
876 function selectTableRowsByIdPrefix(content_id, prefix, check_prefix, do_select, 
877         classcheck, reset_others) {
878
879         var content = $(content_id);
880
881         if (!content) {
882                 console.log("[selectTableRows] Element " + content_id + " not found.");
883                 return;
884         }
885
886         for (i = 0; i < content.rows.length; i++) {
887                 if (Element.visible(content.rows[i])) {
888                         if (!classcheck || content.rows[i].className.match(classcheck)) {
889                 
890                                 if (content.rows[i].id.match(prefix)) {
891                                         selectTableRow(content.rows[i], do_select);
892                                 
893                                         var row_id = content.rows[i].id.replace(prefix, "");
894                                         var check = $(check_prefix + row_id);
895         
896                                         if (check) {
897                                                 check.checked = do_select;
898                                         }
899                                 } else if (reset_others) {
900                                         selectTableRow(content.rows[i], false);
901         
902                                         var row_id = content.rows[i].id.replace(prefix, "");
903                                         var check = $(check_prefix + row_id);
904         
905                                         if (check) {
906                                                 check.checked = false;
907                                         }
908         
909                                 }
910                         } else if (reset_others) {
911                                 selectTableRow(content.rows[i], false);
912         
913                                 var row_id = content.rows[i].id.replace(prefix, "");
914                                 var check = $(check_prefix + row_id);
915         
916                                 if (check) {
917                                         check.checked = false;
918                                 }
919         
920                         }
921                 }
922         }
923 }
924
925 function getSelectedTableRowIds(content_id, prefix) {
926
927         var content = $(content_id);
928
929         if (!content) {
930                 console.log("[getSelectedTableRowIds] Element " + content_id + " not found.");
931                 return new Array();
932         }
933
934         var sel_rows = new Array();
935
936         for (i = 0; i < content.rows.length; i++) {
937                 if (content.rows[i].id.match(prefix) && 
938                                 content.rows[i].className.match("Selected")) {
939                                 
940                         var row_id = content.rows[i].id.replace(prefix + "-", "");
941                         sel_rows.push(row_id);  
942                 }
943         }
944
945         return sel_rows;
946
947 }
948
949 function toggleSelectRowById(sender, id) {
950         var row = $(id);
951
952         if (sender.checked) {
953                 if (!row.className.match("Selected")) {
954                         row.className = row.className + "Selected";
955                 }
956         } else {
957                 if (row.className.match("Selected")) {
958                         row.className = row.className.replace("Selected", "");
959                 }
960         }
961 }
962
963 function toggleSelectListRow(sender) {
964         var parent_row = sender.parentNode;
965
966         if (sender.checked) {
967                 if (!parent_row.className.match("Selected")) {
968                         parent_row.className = parent_row.className + "Selected";
969                 }
970         } else {
971                 if (parent_row.className.match("Selected")) {
972                         parent_row.className = parent_row.className.replace("Selected", "");
973                 }
974         }
975 }
976
977 function tSR(sender) {
978         return toggleSelectRow(sender);
979 }
980
981 function toggleSelectRow(sender) {
982         var parent_row = sender.parentNode.parentNode;
983
984         if (sender.checked) {
985                 if (!parent_row.className.match("Selected")) {
986                         parent_row.className = parent_row.className + "Selected";
987                 }
988         } else {
989                 if (parent_row.className.match("Selected")) {
990                         parent_row.className = parent_row.className.replace("Selected", "");
991                 }
992         }
993 }
994
995 function getNextUnreadCat(id) {
996         try {
997                 var rows = $("feedList").getElementsByTagName("LI");
998                 var feeds = new Array();
999
1000                 var unread_only = true;
1001                 var is_cat = true;
1002
1003                 for (var i = 0; i < rows.length; i++) {
1004                         if (rows[i].id.match("FCAT-")) {
1005                                 if (rows[i].id == "FCAT-" + id && is_cat || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1006
1007                                         var cat_id = parseInt(rows[i].id.replace("FCAT-", ""));
1008
1009                                         if (cat_id >= 0) {
1010                                                 if (!unread_only || get_cat_unread(cat_id) > 0) {
1011                                                         feeds.push(cat_id);
1012                                                 }
1013                                         }
1014                                 }
1015                         }
1016                 }
1017
1018                 var idx = feeds.indexOf(id);
1019                 if (idx != -1 && idx < feeds.length) {
1020                         return feeds[idx+1];                                    
1021                 } else {
1022                         return feeds.shift();
1023                 }
1024
1025         } catch (e) {
1026                 exception_error("getNextUnreadCat", e);
1027         }
1028 }
1029
1030 function getRelativeFeedId2(id, is_cat, direction, unread_only) {       
1031         try {
1032
1033 //              alert(id + " IC: " + is_cat + " D: " + direction + " U: " + unread_only);
1034
1035                 var rows = $("feedList").getElementsByTagName("LI");
1036                 var feeds = new Array();
1037         
1038                 for (var i = 0; i < rows.length; i++) {
1039                         if (rows[i].id.match("FEEDR-")) {
1040         
1041                                 if (rows[i].id == "FEEDR-" + id && !is_cat || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1042         
1043                                         if (!unread_only || 
1044                                                         (rows[i].className.match("Unread") || rows[i].id == "FEEDR-" + id)) {
1045                                                 feeds.push(rows[i].id.replace("FEEDR-", ""));
1046                                         }
1047                                 }
1048                         }
1049
1050                         if (rows[i].id.match("FCAT-")) {
1051                                 if (rows[i].id == "FCAT-" + id && is_cat || (Element.visible(rows[i]) && Element.visible(rows[i].parentNode))) {
1052
1053                                         var cat_id = parseInt(rows[i].id.replace("FCAT-", ""));
1054
1055                                         if (cat_id >= 0) {
1056                                                 if (!unread_only || get_cat_unread(cat_id) > 0) {
1057                                                         feeds.push("CAT:"+cat_id);
1058                                                 }
1059                                         }
1060                                 }
1061                         }
1062                 }
1063         
1064 //              alert(feeds.toString());
1065
1066                 if (!id) {
1067                         if (direction == "next") {
1068                                 return feeds.shift();
1069                         } else {
1070                                 return feeds.pop();
1071                         }
1072                 } else {
1073                         if (direction == "next") {
1074                                 if (is_cat) id = "CAT:" + id;
1075                                 var idx = feeds.indexOf(id);
1076                                 if (idx != -1 && idx < feeds.length) {
1077                                         return feeds[idx+1];                                    
1078                                 } else {
1079                                         return getRelativeFeedId2(false, is_cat, direction, unread_only);
1080                                 }
1081                         } else {
1082                                 if (is_cat) id = "CAT:" + id;
1083                                 var idx = feeds.indexOf(id);
1084                                 if (idx > 0) {
1085                                         return feeds[idx-1];
1086                                 } else {
1087                                         return getRelativeFeedId2(false, is_cat, direction, unread_only);
1088                                 }
1089                         }
1090         
1091                 }
1092
1093         } catch (e) {
1094                 exception_error("getRelativeFeedId2", e);
1095         }
1096 }
1097
1098 function checkboxToggleElement(elem, id) {
1099         if (elem.checked) {
1100                 Effect.Appear(id, {duration : 0.5});
1101         } else {
1102                 Effect.Fade(id, {duration : 0.5});
1103         }
1104 }
1105
1106 function dropboxSelect(e, v) {
1107         for (i = 0; i < e.length; i++) {
1108                 if (e[i].value == v) {
1109                         e.selectedIndex = i;
1110                         break;
1111                 }
1112         }
1113 }
1114
1115 // originally stolen from http://www.11tmr.com/11tmr.nsf/d6plinks/MWHE-695L9Z
1116 // bugfixed just a little bit :-)
1117 function getURLParam(strParamName){
1118   var strReturn = "";
1119   var strHref = window.location.href;
1120
1121   if (strHref.indexOf("#") == strHref.length-1) {
1122                 strHref = strHref.substring(0, strHref.length-1);
1123   }
1124
1125   if ( strHref.indexOf("?") > -1 ){
1126     var strQueryString = strHref.substr(strHref.indexOf("?"));
1127     var aQueryString = strQueryString.split("&");
1128     for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
1129       if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
1130         var aParam = aQueryString[iParam].split("=");
1131         strReturn = aParam[1];
1132         break;
1133       }
1134     }
1135   }
1136   return strReturn;
1137
1138
1139 function leading_zero(p) {
1140         var s = String(p);
1141         if (s.length == 1) s = "0" + s;
1142         return s;
1143 }
1144
1145 function make_timestamp() {
1146         var d = new Date();
1147
1148         return leading_zero(d.getHours()) + ":" + leading_zero(d.getMinutes()) +
1149                         ":" + leading_zero(d.getSeconds());
1150 }
1151
1152
1153 function closeErrorBox() {
1154
1155         if (Element.visible("errorBoxShadow")) {
1156                 Element.hide("dialog_overlay");
1157                 Element.hide("errorBoxShadow");
1158
1159                 enableHotkeys();
1160         }
1161
1162         return false;
1163 }
1164
1165 function closeInfoBox(cleanup) {
1166
1167         try {
1168                 enableHotkeys();
1169
1170                 if (Element.visible("infoBoxShadow")) {
1171                         Element.hide("dialog_overlay");
1172                         Element.hide("infoBoxShadow");
1173
1174                         if (cleanup) $("infoBox").innerHTML = "&nbsp;";
1175                 }
1176         } catch (e) {
1177                 exception_error("closeInfoBox", e);
1178         }
1179         
1180         return false;
1181 }
1182
1183
1184 function displayDlg(id, param, callback) {
1185
1186         notify_progress("Loading, please wait...", true);
1187
1188         disableHotkeys();
1189
1190         var query = "?op=dlg&id=" +
1191                 param_escape(id) + "&param=" + param_escape(param);
1192
1193         new Ajax.Request("backend.php", {
1194                 parameters: query,
1195                 onComplete: function (transport) {
1196                         infobox_callback2(transport);
1197                         if (callback) callback(transport);
1198                 } });
1199
1200         return false;
1201 }
1202
1203 function infobox_submit_callback2(transport) {
1204         closeInfoBox();
1205
1206         try {
1207                 // called from prefs, reload tab
1208                 if (typeof active_tab != 'undefined' && active_tab) {
1209                         selectTab(active_tab, false);
1210                 }
1211         } catch (e) { }
1212
1213         if (transport.responseText) {
1214                 notify_info(transport.responseText);
1215         }
1216 }
1217
1218 function infobox_callback2(transport) {
1219         try {
1220
1221                 console.log("infobox_callback2");
1222
1223                 var box = $('infoBox');
1224                 
1225                 if (box) {                      
1226
1227                         if (!getInitParam("infobox_disable_overlay")) {
1228                                 Element.show("dialog_overlay");
1229                         }
1230
1231                         box.innerHTML=transport.responseText;                   
1232                         Element.show("infoBoxShadow");
1233                         //Effect.SlideDown("infoBoxShadow", {duration : 1.0});
1234
1235
1236                 }
1237
1238                 disableHotkeys();
1239
1240                 notify("");
1241         } catch (e) {
1242                 exception_error("infobox_callback2", e);
1243         }
1244 }
1245
1246 function createFilter() {
1247
1248         try {
1249
1250                 var form = document.forms['filter_add_form'];
1251                 var reg_exp = form.reg_exp.value;
1252         
1253                 if (reg_exp == "") {
1254                         alert(__("Can't add filter: nothing to match on."));
1255                         return false;
1256                 }
1257         
1258                 var query = Form.serialize("filter_add_form");
1259         
1260                 // we can be called from some other tab in Prefs                
1261                 if (typeof active_tab != 'undefined' && active_tab) {
1262                         active_tab = "filterConfig";
1263                 }
1264         
1265                 new Ajax.Request("backend.php?" + query, {
1266                         onComplete: function (transport) {
1267                                 infobox_submit_callback2(transport);
1268                         } });
1269                 
1270                 return true;
1271
1272         } catch (e) {
1273                 exception_error("createFilter", e);
1274         }
1275 }
1276
1277 function isValidURL(s) {
1278         return s.match("http://") != null || s.match("https://") != null || s.match("feed://") != null;
1279 }
1280
1281 function subscribeToFeed() {
1282
1283         try {
1284
1285         var form = document.forms['feed_add_form'];
1286         var feed_url = form.feed_url.value;
1287
1288         if (feed_url == "") {
1289                 alert(__("Can't subscribe: no feed URL given."));
1290                 return false;
1291         }
1292
1293         notify_progress(__("Subscribing to feed..."), true);
1294
1295         var query = Form.serialize("feed_add_form");
1296         
1297         console.log("subscribe q: " + query);
1298
1299         Form.disable("feed_add_form");
1300
1301         new Ajax.Request("backend.php", {
1302                 parameters: query,
1303                 onComplete: function(transport) { 
1304                         //dlg_frefresh_callback(transport); 
1305
1306                         notify('');
1307
1308                         var result = transport.responseXML.getElementsByTagName('result')[0];
1309                         var rc = parseInt(result.getAttribute('code'));
1310
1311                         Form.enable("feed_add_form");
1312
1313                         switch (rc) {
1314                         case 1:
1315                                 closeInfoBox();
1316                                 notify_info(__("Subscribed to %s").replace("%s", feed_url));
1317
1318                                 if (inPreferences()) {
1319                                         updateFeedList();
1320                                 } else {
1321                                         setTimeout('updateFeedList(false, false)', 50);
1322                                 }
1323                                 break;
1324                         case 2:
1325                                 alert(__("Can't subscribe to the specified URL."));
1326                                 break;
1327                         case 0:
1328                                 alert(__("You are already subscribed to this feed."));
1329                                 break;
1330                         }
1331
1332                 } });
1333
1334         } catch (e) {
1335                 exception_error("subscribeToFeed", e);
1336         }
1337
1338         return false;
1339 }
1340
1341 function filterCR(e, f)
1342 {
1343      var key;
1344
1345      if(window.event)
1346           key = window.event.keyCode;     //IE
1347      else
1348           key = e.which;     //firefox
1349
1350         if (key == 13) {
1351                 if (typeof f != 'undefined') {
1352                         f();
1353                         return false;
1354                 } else {
1355                         return false;
1356                 }
1357         } else {
1358                 return true;
1359         }
1360 }
1361
1362 var debug_last_class = "even";
1363
1364 function debug(msg) {
1365
1366         if (debug_last_class == "even") {
1367                 debug_last_class = "odd";
1368         } else {
1369                 debug_last_class = "even";
1370         }
1371
1372         var c = $('debug_output');
1373         if (c && Element.visible(c)) {
1374                 while (c.lastChild != 'undefined' && c.childNodes.length > 100) {
1375                         c.removeChild(c.lastChild);
1376                 }
1377         
1378                 var ts = make_timestamp();
1379                 c.innerHTML = "<li class=\"" + debug_last_class + "\"><span class=\"debugTS\">[" + ts + "]</span> " + 
1380                         msg + "</li>" + c.innerHTML;
1381         }
1382 }
1383
1384 function getInitParam(key) {
1385         return init_params[key];
1386 }
1387
1388 function setInitParam(key, value) {
1389         init_params[key] = value;
1390 }
1391
1392 function fatalError(code, msg, ext_info) {
1393         try {   
1394
1395                 if (!ext_info) ext_info = "N/A";
1396
1397                 if (code == 6) {
1398                         window.location.href = "tt-rss.php";                    
1399                 } else if (code == 5) {
1400                         window.location.href = "update.php";
1401                 } else {
1402         
1403                         if (msg == "") msg = "Unknown error";
1404
1405                         var ebc = $("xebContent");
1406         
1407                         if (ebc) {
1408         
1409                                 Element.show("dialog_overlay");
1410                                 Element.show("errorBoxShadow");
1411                                 Element.hide("xebBtn");
1412
1413                                 if (ext_info) {
1414                                         if (ext_info.responseText) {
1415                                                 ext_info = ext_info.responseText;
1416                                         }
1417                                 }
1418         
1419                                 ebc.innerHTML = 
1420                                         "<div><b>Error message:</b></div>" +
1421                                         "<pre>" + msg + "</pre>" +
1422                                         "<div><b>Additional information:</b></div>" +
1423                                         "<textarea readonly=\"1\">" + ext_info + "</textarea>";
1424                         }
1425                 }
1426
1427         } catch (e) {
1428                 exception_error("fatalError", e);
1429         }
1430 }
1431
1432 function getFeedName(id, is_cat) {      
1433         var e;
1434
1435         if (is_cat) {
1436                 e = $("FCATN-" + id);
1437         } else {
1438                 e = $("FEEDN-" + id);
1439         }
1440         if (e) {
1441                 return e.innerHTML.stripTags();
1442         } else {
1443                 return null;
1444         }
1445 }
1446
1447 function filterDlgCheckType(sender) {
1448
1449         try {
1450
1451                 var ftype = sender[sender.selectedIndex].value;
1452
1453                 var form = document.forms["filter_add_form"];
1454         
1455                 if (!form) {
1456                         form = document.forms["filter_edit_form"];
1457                 }
1458
1459                 if (!form) {
1460                         console.log("filterDlgCheckType: can't find form!");
1461                         return;
1462                 }
1463
1464                 // if selected filter type is 5 (Date) enable the modifier dropbox
1465                 if (ftype == 5) {
1466                         Element.show("filter_dlg_date_mod_box");
1467                         Element.show("filter_dlg_date_chk_box");
1468                 } else {
1469                         Element.hide("filter_dlg_date_mod_box");
1470                         Element.hide("filter_dlg_date_chk_box");
1471
1472                 }
1473
1474         } catch (e) {
1475                 exception_error("filterDlgCheckType", e);
1476         }
1477
1478 }
1479
1480 function filterDlgCheckAction(sender) {
1481
1482         try {
1483
1484                 var action = sender[sender.selectedIndex].value;
1485
1486                 var form = document.forms["filter_add_form"];
1487         
1488                 if (!form) {
1489                         form = document.forms["filter_edit_form"];
1490                 }
1491
1492                 if (!form) {
1493                         console.log("filterDlgCheckAction: can't find form!");
1494                         return;
1495                 }
1496
1497                 var action_param = $("filter_dlg_param_box");
1498
1499                 if (!action_param) {
1500                         console.log("filterDlgCheckAction: can't find action param box!");
1501                         return;
1502                 }
1503
1504                 // if selected action supports parameters, enable params field
1505                 if (action == 4 || action == 6 || action == 7) {
1506                         Element.show(action_param);
1507                         if (action != 7) {
1508                                 Element.show(form.action_param);
1509                                 Element.hide(form.action_param_label);
1510                         } else {
1511                                 Element.show(form.action_param_label);
1512                                 Element.hide(form.action_param);
1513                         }
1514                 } else {
1515                         Element.hide(action_param);
1516                 }
1517
1518         } catch (e) {
1519                 exception_error("filterDlgCheckAction", e);
1520         }
1521
1522 }
1523
1524 function filterDlgCheckDate() {
1525         try {
1526                 var form = document.forms["filter_add_form"];
1527         
1528                 if (!form) {
1529                         form = document.forms["filter_edit_form"];
1530                 }
1531
1532                 if (!form) {
1533                         console.log("filterDlgCheckAction: can't find form!");
1534                         return;
1535                 }
1536
1537                 var reg_exp = form.reg_exp.value;
1538
1539                 var query = "?op=rpc&subop=checkDate&date=" + reg_exp;
1540
1541                 new Ajax.Request("backend.php", {
1542                         parameters: query,
1543                         onComplete: function(transport) { 
1544
1545                                 var form = document.forms["filter_add_form"];
1546         
1547                                 if (!form) {
1548                                         form = document.forms["filter_edit_form"];
1549                                 }
1550
1551                                 if (transport.responseXML) {
1552                                         var result = transport.responseXML.getElementsByTagName("result")[0];
1553
1554                                         if (result && result.firstChild) {
1555                                                 if (result.firstChild.nodeValue == "1") {
1556
1557                                                         new Effect.Highlight(form.reg_exp, {startcolor : '#00ff00'});
1558
1559                                                         return;
1560                                                 }
1561                                         }
1562                                 }
1563
1564                                 new Effect.Highlight(form.reg_exp, {startcolor : '#ff0000'});
1565
1566                         } });
1567
1568
1569         } catch (e) {
1570                 exception_error("filterDlgCheckDate", e);
1571         }
1572 }
1573
1574 function explainError(code) {
1575         return displayDlg("explainError", code);
1576 }
1577
1578 // this only searches loaded headlines list, not in CDM
1579 function getRelativePostIds(id, limit) {
1580
1581         if (!limit) limit = 3;
1582
1583         console.log("getRelativePostIds: " + id + " limit=" + limit);
1584
1585         var ids = new Array();
1586         var container = $("headlinesList");
1587
1588         if (container) {
1589                 var rows = container.rows;
1590
1591                 for (var i = 0; i < rows.length; i++) {
1592                         var r_id = rows[i].id.replace("RROW-", "");
1593
1594                         if (r_id == id) {
1595                                 for (var k = 1; k <= limit; k++) {
1596                                         var nid = false;
1597
1598                                         if (i > k-1) var nid = rows[i-k].id.replace("RROW-", "");
1599                                         if (nid) ids.push(nid);
1600
1601                                         if (i < rows.length-k) nid = rows[i+k].id.replace("RROW-", "");
1602                                         if (nid) ids.push(nid);
1603                                 }
1604
1605                                 return ids;
1606                         }
1607                 }
1608         }
1609
1610         return false;
1611 }
1612
1613 function openArticleInNewWindow(id) {
1614         try {
1615                 console.log("openArticleInNewWindow: " + id);
1616
1617                 var query = "?op=rpc&subop=getArticleLink&id=" + id;
1618                 var wname = "ttrss_article_" + id;
1619
1620                 console.log(query + " " + wname);
1621
1622                 var w = window.open("", wname);
1623
1624                 if (!w) notify_error("Failed to open window for the article");
1625
1626                 new Ajax.Request("backend.php", {
1627                         parameters: query,
1628                         onComplete: function(transport) { 
1629
1630                                         var link = transport.responseXML.getElementsByTagName("link")[0];
1631                                         var id = transport.responseXML.getElementsByTagName("id")[0];
1632                 
1633                                         console.log("open_article received link: " + link);
1634                 
1635                                         if (link && id) {
1636                 
1637                                                 var wname = "ttrss_article_" + id.firstChild.nodeValue;
1638                 
1639                                                 console.log("link url: " + link.firstChild.nodeValue + ", wname " + wname);
1640                 
1641                                                 var w = window.open(link.firstChild.nodeValue, wname);
1642                 
1643                                                 if (!w) { notify_error("Failed to load article in new window"); }
1644                 
1645                                                 if (id) {
1646                                                         id = id.firstChild.nodeValue;
1647                                                         if (!$("headlinesList")) {
1648                                                                 window.setTimeout("toggleUnread(" + id + ", 0)", 100);
1649                                                         }
1650                                                 }
1651                                         } else {
1652                                                 notify_error("Can't open article: received invalid article link");
1653                                         }
1654                                 } });
1655
1656         } catch (e) {
1657                 exception_error("openArticleInNewWindow", e);
1658         }
1659 }
1660
1661 /* http://textsnippets.com/posts/show/835 */
1662
1663 Position.GetWindowSize = function(w) {
1664         w = w ? w : window;
1665         var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
1666         var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
1667         return [width, height]
1668 }
1669
1670 /* http://textsnippets.com/posts/show/836 */
1671
1672 Position.Center = function(element, parent) {
1673         var w, h, pw, ph;
1674         var d = Element.getDimensions(element);
1675         w = d.width;
1676         h = d.height;
1677         Position.prepare();
1678         if (!parent) {
1679                 var ws = Position.GetWindowSize();
1680                 pw = ws[0];
1681                 ph = ws[1];
1682         } else {
1683                 pw = parent.offsetWidth;
1684                 ph = parent.offsetHeight;
1685         }
1686         element.style.top = (ph/2) - (h/2) -  Position.deltaY + "px";
1687         element.style.left = (pw/2) - (w/2) -  Position.deltaX + "px";
1688 }
1689
1690
1691 function isCdmMode() {
1692         return !$("headlinesList");
1693 }
1694
1695 function getSelectedArticleIds2() {
1696         var rows = new Array();
1697         var cdm_mode = isCdmMode();
1698
1699         if (cdm_mode) {
1700                 rows = cdmGetSelectedArticles();
1701         } else {        
1702                 rows = getSelectedTableRowIds("headlinesList", "RROW", "RCHK");
1703         }
1704
1705         var ids = new Array();
1706
1707         for (var i = 0; i < rows.length; i++) {
1708                 var chk = $("RCHK-" + rows[i]);
1709                 if (chk && chk.checked) {
1710                         ids.push(rows[i]);
1711                 }
1712         }
1713
1714         return ids;
1715 }
1716
1717 function displayHelpInfobox(topic_id) {
1718
1719         var url = "backend.php?op=help&tid=" + param_escape(topic_id);
1720
1721         var w = window.open(url, "ttrss_help", 
1722                 "status=0,toolbar=0,location=0,width=450,height=500,scrollbars=1,menubar=0");
1723
1724 }
1725
1726 function focus_element(id) {
1727         try {
1728                 var e = $(id);
1729                 if (e) e.focus();
1730         } catch (e) {
1731                 exception_error("focus_element", e);
1732         }
1733         return false;
1734 }
1735
1736 function loading_set_progress(p) {
1737         try {
1738                 if (p < last_progress_point || !Element.visible("overlay")) return;
1739
1740                 console.log("<b>loading_set_progress : " + p + " (" + last_progress_point + ")</b>");
1741
1742                 var o = $("l_progress_i");
1743
1744 //              o.style.width = (p * 2) + "px";
1745
1746                 new Effect.Scale(o, p, { 
1747                         scaleY : false,
1748                         scaleFrom : last_progress_point,
1749                         scaleMode: { originalWidth : 200 },
1750                         queue: { position: 'end', scope: 'LSP-Q', limit: 3 } }); 
1751
1752                 last_progress_point = p;
1753
1754         } catch (e) {
1755                 exception_error("loading_set_progress", e);
1756         }
1757 }
1758
1759 function remove_splash() {
1760         if (Element.visible("overlay")) {
1761                 console.log("about to remove splash, OMG!");
1762                 Element.hide("overlay");
1763                 console.log("removed splash!");
1764         }
1765 }
1766
1767 function getSelectedFeedsFromBrowser() {
1768
1769         var list = $("browseFeedList");
1770
1771         var selected = new Array();
1772         
1773         for (i = 0; i < list.childNodes.length; i++) {
1774                 var child = list.childNodes[i];
1775                 if (child.id && child.id.match("FBROW-")) {
1776                         var id = child.id.replace("FBROW-", "");
1777                         
1778                         var cb = $("FBCHK-" + id);
1779
1780                         if (cb.checked) {
1781                                 selected.push(id);
1782                         }
1783                 }
1784         }
1785
1786         return selected;
1787 }
1788
1789 function updateFeedBrowser() {
1790         try {
1791
1792                 var query = Form.serialize("feed_browser");
1793
1794                 Element.show('feed_browser_spinner');
1795
1796                 new Ajax.Request("backend.php", {
1797                         parameters: query,
1798                         onComplete: function(transport) { 
1799                                 notify('');
1800
1801                                 Element.hide('feed_browser_spinner');
1802
1803                                 var c = $("browseFeedList");
1804                                 var r = transport.responseXML.getElementsByTagName("content")[0];
1805                                 var nr = transport.responseXML.getElementsByTagName("num-results")[0];
1806                                 var mode = transport.responseXML.getElementsByTagName("mode")[0];
1807
1808                                 if (c && r) {
1809                                         c.innerHTML = r.firstChild.nodeValue;
1810                                 }
1811
1812                                 if (parseInt(mode.getAttribute("value")) == 2) {
1813                                         Element.show('feed_archive_remove');
1814                                 } else {
1815                                         Element.hide('feed_archive_remove');
1816                                 }
1817         
1818                         } });
1819
1820         } catch (e) {
1821                 exception_error("updateFeedBrowser", e);
1822         }
1823
1824 }
1825
1826 function transport_error_check(transport) {
1827         try {
1828                 if (transport.responseXML) {
1829                         var error = transport.responseXML.getElementsByTagName("error")[0];
1830
1831                         if (error) {
1832                                 var code = error.getAttribute("error-code");
1833                                 var msg = error.getAttribute("error-msg");
1834                                 if (code != 0) {
1835                                         fatalError(code, msg);
1836                                         return false;
1837                                 }
1838                         }
1839                 }
1840         } catch (e) {
1841                 exception_error("check_for_error_xml", e);
1842         }
1843         return true;
1844 }
1845
1846 function strip_tags(s) {
1847         return s.replace(/<\/?[^>]+(>|$)/g, "");
1848 }
1849
1850 function truncate_string(s, length) {
1851         if (!length) length = 30;
1852         var tmp = s.substring(0, length);
1853         if (s.length > length) tmp += "&hellip;";
1854         return tmp;
1855 }
1856
1857 function hotkey_prefix_timeout() {
1858         try {
1859
1860                 var date = new Date();
1861                 var ts = Math.round(date.getTime() / 1000);
1862
1863                 if (hotkey_prefix_pressed && ts - hotkey_prefix_pressed >= 5) {
1864                         console.log("hotkey_prefix seems to be stuck, aborting");
1865                         hotkey_prefix_pressed = false;
1866                         hotkey_prefix = false;
1867                         Element.hide('cmdline');
1868                 }
1869
1870                 setTimeout("hotkey_prefix_timeout()", 1000);
1871
1872         } catch  (e) {
1873                 exception_error("hotkey_prefix_timeout", e);
1874         }
1875 }
1876
1877 function hideAuxDlg() {
1878         try {
1879                 Element.hide('auxDlg');
1880         } catch (e) {
1881                 exception_error("hideAuxDlg", e);
1882         }
1883 }
1884
1885 function displayNewContentPrompt(id) {
1886         try {
1887
1888                 var msg = "<a href='#' onclick='viewfeed("+id+")'>" +
1889                         __("New articles available in this feed (click to show)") + "</a>";
1890
1891                 msg = msg.replace("%s", getFeedName(id));
1892
1893                 $('auxDlg').innerHTML = msg;
1894
1895                 Element.show('auxDlg');
1896
1897         } catch (e) {
1898                 exception_error("displayNewContentPrompt", e);
1899         }
1900 }
1901
1902 function feedBrowserSubscribe() {
1903         try {
1904
1905                 var selected = getSelectedFeedsFromBrowser();
1906
1907                 var mode = document.forms['feed_browser'].mode;
1908
1909                 mode = mode[mode.selectedIndex].value;
1910
1911                 if (selected.length > 0) {
1912                         closeInfoBox();
1913
1914                         notify_progress("Loading, please wait...", true);
1915
1916                         var query = "?op=rpc&subop=massSubscribe&ids="+
1917                                 param_escape(selected.toString()) + "&mode=" + param_escape(mode);
1918
1919                         new Ajax.Request("backend.php", {
1920                                 parameters: query,
1921                                 onComplete: function(transport) { 
1922
1923                                         var nf = transport.responseXML.getElementsByTagName('num-feeds')[0];
1924                                         var nf_value = nf.getAttribute("value");
1925
1926                                         notify_info(__("Subscribed to %d feed(s).").replace("%d", nf_value));
1927
1928                                         if (inPreferences()) {
1929                                                 updateFeedList();
1930                                         } else {
1931                                                 setTimeout('updateFeedList(false, false)', 50);
1932                                         }
1933                                 } });
1934
1935                 } else {
1936                         alert(__("No feeds are selected."));
1937                 }
1938
1939         } catch (e) {
1940                 exception_error("feedBrowserSubscribe", e);
1941         }
1942 }
1943
1944 function feedArchiveRemove() {
1945         try {
1946
1947                 var selected = getSelectedFeedsFromBrowser();
1948
1949                 if (selected.length > 0) {
1950
1951                         var pr = __("Remove selected feeds from the archive? Feeds with stored articles will not be removed.");
1952
1953                         if (confirm(pr)) {
1954                                 Element.show('feed_browser_spinner');
1955
1956                                 var query = "?op=rpc&subop=remarchived&ids=" + 
1957                                         param_escape(selected.toString());;
1958
1959                                 new Ajax.Request("backend.php", {
1960                                         parameters: query,
1961                                         onComplete: function(transport) { 
1962                                                 updateFeedBrowser();
1963                                         } }); 
1964                         }
1965
1966                 } else {
1967                         alert(__("No feeds are selected."));
1968                 }
1969
1970         } catch (e) {
1971                 exception_error("feedArchiveRemove", e);
1972         }
1973 }
1974
1975 function uploadIconHandler(rc) {
1976         try {
1977                 switch (rc) {
1978                         case 0:
1979                                 notify_info("Upload complete.");
1980                                 if (inPreferences()) {
1981                                         updateFeedList();
1982                                 } else {
1983                                         setTimeout('updateFeedList(false, false)', 50);
1984                                 }
1985                                 break;
1986                         case 1:
1987                                 notify_error("Upload failed: icon is too big.");
1988                                 break;
1989                         case 2:
1990                                 notify_error("Upload failed.");
1991                                 break;
1992                 }
1993
1994         } catch (e) {
1995                 exception_error("uploadIconHandler", e);
1996         }
1997 }
1998
1999 function removeFeedIcon(id) {
2000
2001         try {
2002
2003                 if (confirm(__("Remove stored feed icon?"))) {
2004                         var query = "backend.php?op=pref-feeds&subop=removeicon&feed_id=" + param_escape(id);
2005
2006                         console.log(query);
2007
2008                         notify_progress("Removing feed icon...", true);
2009
2010                         new Ajax.Request("backend.php", {
2011                                 parameters: query,
2012                                 onComplete: function(transport) { 
2013                                         notify_info("Feed icon removed.");
2014                                         if (inPreferences()) {
2015                                                 updateFeedList();
2016                                         } else {
2017                                                 setTimeout('updateFeedList(false, false)', 50);
2018                                         }
2019                                 } }); 
2020                 }
2021
2022                 return false;
2023         } catch (e) {
2024                 exception_error("uploadFeedIcon", e);
2025         }
2026 }
2027
2028 function uploadFeedIcon() {
2029
2030         try {
2031
2032                 var file = $("icon_file");
2033
2034                 if (file.value.length == 0) {
2035                         alert(__("Please select an image file to upload."));
2036                 } else {
2037                         if (confirm(__("Upload new icon for this feed?"))) {
2038                                 notify_progress("Uploading, please wait...", true);
2039                                 return true;
2040                         }
2041                 }
2042
2043                 return false;
2044
2045         } catch (e) {
2046                 exception_error("uploadFeedIcon", e);
2047         }
2048 }
2049
2050 function addLabel() {
2051
2052         try {
2053
2054                 var caption = prompt(__("Please enter label caption:"), "");
2055
2056                 if (caption != undefined) {
2057         
2058                         if (caption == "") {
2059                                 alert(__("Can't create label: missing caption."));
2060                                 return false;
2061                         }
2062
2063                         var query = "?op=pref-labels&subop=add&caption=" + 
2064                                 param_escape(caption);
2065
2066                         notify_progress("Loading, please wait...", true);
2067
2068                         if (inPreferences()) active_tab = "labelConfig";
2069
2070                         new Ajax.Request("backend.php", {
2071                                 parameters: query,
2072                                 onComplete: function(transport) { 
2073                                         if (inPreferences()) {
2074                                                 infobox_submit_callback2(transport);
2075                                         } else {
2076                                                 updateFeedList();
2077                                         }
2078                         } });
2079
2080                 }
2081
2082         } catch (e) {
2083                 exception_error("addLabel", e);
2084         }
2085 }
2086
2087 function quickAddFeed() {
2088         displayDlg('quickAddFeed', '',
2089            function () {$('feed_url').focus();});
2090 }
2091
2092 function quickAddFilter() {
2093         displayDlg('quickAddFilter', '',
2094            function () {document.forms['filter_add_form'].reg_exp.focus();});
2095 }
2096
2097 function unsubscribeFeed(feed_id, title) {
2098
2099         var msg = __("Unsubscribe from %s?").replace("%s", title);
2100
2101         if (title == undefined || confirm(msg)) {
2102                 notify_progress("Removing feed...");
2103
2104                 var query = "?op=pref-feeds&quiet=1&subop=remove&ids=" + feed_id;
2105
2106                 new Ajax.Request("backend.php", {
2107                         parameters: query,
2108                         onComplete: function(transport) {
2109
2110                                         closeInfoBox();
2111
2112                                         if (inPreferences()) {
2113                                                 updateFeedList();                               
2114                                         } else {
2115                                                 dlg_frefresh_callback(transport, feed_id);
2116                                         }
2117
2118                                 } });
2119         }
2120
2121         return false;
2122 }
2123
2124
2125 function backend_sanity_check_callback(transport) {
2126
2127         try {
2128
2129                 if (sanity_check_done) {
2130                         fatalError(11, "Sanity check request received twice. This can indicate "+
2131                       "presence of Firebug or some other disrupting extension. "+
2132                                 "Please disable it and try again.");
2133                         return;
2134                 }
2135
2136                 if (!transport.responseXML) {
2137                         if (!store) {
2138                                 fatalError(3, "Sanity check: Received reply is not XML", 
2139                                         transport.responseText);
2140                                 return;
2141                         } else {
2142                                 init_offline();
2143                                 return;
2144                         }
2145                 }
2146
2147                 if (getURLParam("offline")) {
2148                         return init_offline();
2149                 }
2150
2151                 var reply = transport.responseXML.getElementsByTagName("error")[0];
2152
2153                 if (!reply) {
2154                         fatalError(3, "Sanity check: invalid RPC reply", transport.responseText);
2155                         return;
2156                 }
2157
2158                 var error_code = reply.getAttribute("error-code");
2159         
2160                 if (error_code && error_code != 0) {
2161                         return fatalError(error_code, reply.getAttribute("error-msg"));
2162                 }
2163
2164                 console.log("sanity check ok");
2165
2166                 var params = transport.responseXML.getElementsByTagName("init-params")[0];
2167
2168                 if (params) {
2169                         console.log('reading init-params...');
2170                         //var param = params.firstChild;
2171
2172                         params = JSON.parse(params.firstChild.nodeValue);
2173
2174                         if (params) {
2175                                 for (var i = 0; i < params.length; i++) {
2176         
2177                                         var k = params[i].param;
2178                                         var v = params[i].value;
2179         
2180                                         console.log(k + " => " + v);
2181                                         init_params[k] = v;                                     
2182         
2183                                         if (db) {
2184                                                 db.execute("DELETE FROM init_params WHERE key = ?", [k]);
2185                                                 db.execute("INSERT INTO init_params (key,value) VALUES (?, ?)",
2186                                                         [k, v]);
2187                                         }
2188                                 }
2189                         }
2190                 }
2191
2192                 sanity_check_done = true;
2193
2194                 init_second_stage();
2195
2196         } catch (e) {
2197                 exception_error("backend_sanity_check_callback", e, transport); 
2198         } 
2199 }
2200
2201