]> git.wh0rd.org Git - tt-rss.git/blob - viewfeed.js
viewfeed: try to prevent dupe headlines from being loaded in the buffer
[tt-rss.git] / viewfeed.js
1 var active_post_id = false;
2
3 var article_cache = new Array();
4
5 var vgroup_last_feed = false;
6 var post_under_pointer = false;
7
8 var last_requested_article = false;
9
10 var catchup_id_batch = [];
11 var catchup_timeout_id = false;
12 var feed_precache_timeout_id = false;
13 var precache_idle_timeout_id = false;
14
15 var cids_requested = [];
16
17 var has_storage = 'sessionStorage' in window && window['sessionStorage'] !== null;
18
19 function headlines_callback2(transport, offset, background) {
20         try {
21                 handle_rpc_json(transport);
22
23                 loading_set_progress(25);
24
25                 console.log("headlines_callback2 [offset=" + offset + "] B:" + background);
26
27                 var is_cat = false;
28                 var feed_id = false;
29
30                 var reply;
31
32                 try {
33                         reply = JSON.parse(transport.responseText);
34                 } catch (e) {
35                         console.error(e);
36                 }
37
38                 if (reply) {
39
40                         is_cat = reply['headlines']['is_cat'];
41                         feed_id = reply['headlines']['id'];
42
43                         if (background) {
44                                 cache_headlines(feed_id, is_cat, reply['headlines']['toolbar'], reply['headlines']['content']);
45                                 return;
46                         }
47
48                         setActiveFeedId(feed_id, is_cat);
49
50                         try {
51                                 if (offset == 0) {
52                                         $("headlines-frame").scrollTop = 0;
53                                 }
54                         } catch (e) { };
55
56                         var headlines_count = reply['headlines-info']['count'];
57
58                         vgroup_last_feed = reply['headlines-info']['vgroup_last_feed'];
59
60                         if (parseInt(headlines_count) < getInitParam("default_article_limit")) {
61                                 _infscroll_disable = 1;
62                         } else {
63                                 _infscroll_disable = 0;
64                         }
65
66                         var counters = reply['counters'];
67                         var articles = reply['articles'];
68                         var runtime_info = reply['runtime-info'];
69
70                         if (offset == 0) {
71                                 dijit.byId("headlines-frame").attr('content',
72                                         reply['headlines']['content']);
73
74                                 dijit.byId("headlines-toolbar").attr('content',
75                                         reply['headlines']['toolbar']);
76
77                                 var hsp = $("headlines-spacer");
78                                 if (!hsp) hsp = new Element("DIV", {"id": "headlines-spacer"});
79
80                                 dijit.byId('headlines-frame').domNode.appendChild(hsp);
81
82                                 initHeadlinesMenu();
83
84                         } else {
85                                 if (headlines_count > 0) {
86                                         console.log("adding some more headlines...");
87
88                                         var c = dijit.byId("headlines-frame");
89                                         var ids = getSelectedArticleIds2();
90
91                                         $("headlines-tmp").innerHTML = reply['headlines']['content'];
92
93                                         var hsp = $("headlines-spacer");
94
95                                         if (hsp)
96                                                 c.domNode.removeChild(hsp);
97
98                                         $$("#headlines-tmp > div").each(function(row) {
99                                                 if ($$("#headlines-frame DIV[id="+row.id+"]").length == 0) {
100                                                         row.style.display = 'none';
101                                                         c.domNode.appendChild(row);
102                                                 }
103                                         });
104
105                                         if (!hsp) hsp = new Element("DIV", {"id": "headlines-spacer"});
106
107                                         fixHeadlinesOrder(getLoadedArticleIds());
108
109                                         c.domNode.appendChild(hsp);
110
111                                         console.log("restore selected ids: " + ids);
112
113                                         for (var i = 0; i < ids.length; i++) {
114                                                 markHeadline(ids[i]);
115                                         }
116
117                                         initHeadlinesMenu();
118
119                                         $$("#headlines-frame > div[id*=RROW]").each(
120                                         function(child) {
121                                                 if (!Element.visible(child))
122                                                         new Effect.Appear(child, { duration : 0.5 });
123                                         });
124
125                                 } else {
126                                         console.log("no new headlines received");
127
128                                         var hsp = $("headlines-spacer");
129
130                                         if (hsp) hsp.innerHTML = "";
131                                 }
132                         }
133
134                         if (headlines_count > 0)
135                                 cache_headlines(feed_id, is_cat, reply['headlines']['toolbar'], $("headlines-frame").innerHTML);
136
137                         if (articles) {
138                                 for (var i = 0; i < articles.length; i++) {
139                                         var a_id = articles[i]['id'];
140                                         cache_set("article:" + a_id, articles[i]['content']);
141                                 }
142                         } else {
143                                 console.log("no cached articles received");
144                         }
145
146                         // do not precache stuff after fresh feed
147                         if (feed_id != -3)
148                                 precache_headlines();
149
150                         if (counters)
151                                 parse_counters(counters);
152                         else
153                                 request_counters();
154
155                 } else {
156                         console.warn("headlines_callback: returned no XML object");
157                         dijit.byId("headlines-frame").attr('content', "<div class='whiteBox'>" +
158                                         __('Could not update headlines (invalid object received)') + "</div>");
159                 }
160
161                 _infscroll_request_sent = 0;
162
163                 notify("");
164
165         } catch (e) {
166                 exception_error("headlines_callback2", e, transport);
167         }
168 }
169
170 function render_article(article) {
171         try {
172                 dijit.byId("headlines-wrap-inner").addChild(
173                                 dijit.byId("content-insert"));
174
175                 var c = dijit.byId("content-insert");
176
177                 try {
178                         c.domNode.scrollTop = 0;
179                 } catch (e) { };
180
181                 c.attr('content', article);
182
183                 correctHeadlinesOffset(getActiveArticleId());
184
185                 try {
186                         c.focus();
187                 } catch (e) { };
188
189         } catch (e) {
190                 exception_error("render_article", e);
191         }
192 }
193
194 function showArticleInHeadlines(id) {
195
196         try {
197
198                 selectArticles("none");
199
200                 var crow = $("RROW-" + id);
201
202                 if (!crow) return;
203
204                 var article_is_unread = crow.hasClassName("Unread");
205
206                 crow.removeClassName("Unread");
207
208                 selectArticles('none');
209
210                 var upd_img_pic = $("FUPDPIC-" + id);
211
212                 var view_mode = false;
213
214                 try {
215                         view_mode = document.forms['main_toolbar_form'].view_mode;
216                         view_mode = view_mode[view_mode.selectedIndex].value;
217                 } catch (e) {
218                         //
219                 }
220
221                 if (upd_img_pic && (upd_img_pic.src.match("updated.png") ||
222                                         upd_img_pic.src.match("fresh_sign.png"))) {
223
224                         upd_img_pic.src = "images/blank_icon.gif";
225
226                         cache_headlines(getActiveFeedId(), activeFeedIsCat(), null, $("headlines-frame").innerHTML);
227
228                 } else if (article_is_unread && view_mode == "all_articles") {
229                         cache_headlines(getActiveFeedId(), activeFeedIsCat(), null, $("headlines-frame").innerHTML);
230                 }
231
232                 markHeadline(id);
233
234                 if (article_is_unread)
235                         _force_scheduled_update = true;
236
237         } catch (e) {
238                 exception_error("showArticleInHeadlines", e);
239         }
240 }
241
242 function article_callback2(transport, id) {
243         try {
244                 console.log("article_callback2 " + id);
245
246                 handle_rpc_json(transport);
247
248                 var reply = JSON.parse(transport.responseText);
249
250                 if (reply) {
251
252                         var upic = $('FUPDPIC-' + id);
253
254                         if (upic) upic.src = 'images/blank_icon.gif';
255
256                         reply.each(function(article) {
257                                 if (active_post_id == article['id']) {
258                                         render_article(article['content']);
259                                 }
260                                 cids_requested.remove(article['id']);
261
262                                 cache_set("article:" + article['id'], article['content']);
263                         });
264
265 //                      if (id != last_requested_article) {
266 //                              console.log("requested article id is out of sequence, aborting");
267 //                              return;
268 //                      }
269
270                 } else {
271                         console.warn("article_callback: returned invalid data");
272
273                         render_article("<div class='whiteBox'>" +
274                                         __('Could not display article (invalid data received)') + "</div>");
275                 }
276
277                 request_counters();
278
279                 try {
280                         if (!_infscroll_disable &&
281                                         $$("#headlines-frame > div[id*=RROW]").last().hasClassName("Selected")) {
282
283                                 loadMoreHeadlines();
284                         }
285                 } catch (e) {
286                         console.warn(e);
287                 }
288
289                 notify("");
290         } catch (e) {
291                 exception_error("article_callback2", e, transport);
292         }
293 }
294
295 function view(id) {
296         try {
297                 console.log("loading article: " + id);
298
299                 var cached_article = cache_get("article:" + id);
300
301                 console.log("cache check result: " + (cached_article != false));
302
303                 hideAuxDlg();
304
305                 var query = "?op=view&id=" + param_escape(id);
306
307                 var neighbor_ids = getRelativePostIds(id);
308
309                 /* only request uncached articles */
310
311                 var cids_to_request = [];
312
313                 for (var i = 0; i < neighbor_ids.length; i++) {
314                         if (cids_requested.indexOf(neighbor_ids[i]) == -1)
315                                 if (!cache_get("article:" + neighbor_ids[i])) {
316                                         cids_to_request.push(neighbor_ids[i]);
317                                         cids_requested.push(neighbor_ids[i]);
318                                 }
319                 }
320
321                 console.log("additional ids: " + cids_to_request.toString());
322
323                 query = query + "&cids=" + cids_to_request.toString();
324
325                 var crow = $("RROW-" + id);
326                 var article_is_unread = crow.hasClassName("Unread");
327
328                 active_post_id = id;
329                 showArticleInHeadlines(id);
330
331                 precache_headlines();
332
333                 if (!cached_article) {
334
335                         var upic = $('FUPDPIC-' + id);
336
337                         if (upic) {
338                                 upic.src = getInitParam("sign_progress");
339                         }
340
341                 } else if (cached_article && article_is_unread) {
342
343                         query = query + "&mode=prefetch";
344
345                         render_article(cached_article);
346
347                 } else if (cached_article) {
348
349                         query = query + "&mode=prefetch_old";
350                         render_article(cached_article);
351
352                         // if we don't need to request any relative ids, we might as well skip
353                         // the server roundtrip altogether
354                         if (cids_to_request.length == 0) {
355
356                                 try {
357                                         if (!_infscroll_disable &&
358                                                 $$("#headlines-frame > div[id*=RROW]").last().hasClassName("Selected")) {
359
360                                                         loadMoreHeadlines();
361                                         }
362                                 } catch (e) {
363                                         console.warn(e);
364                                 }
365
366                                 return;
367                         }
368                 }
369
370                 last_requested_article = id;
371
372                 console.log(query);
373
374                 new Ajax.Request("backend.php", {
375                         parameters: query,
376                         onComplete: function(transport) {
377                                 article_callback2(transport, id);
378                         } });
379
380                 return false;
381
382         } catch (e) {
383                 exception_error("view", e);
384         }
385 }
386
387 function tMark(id) {
388         return toggleMark(id);
389 }
390
391 function tPub(id) {
392         return togglePub(id);
393 }
394
395 function toggleMark(id, client_only) {
396         try {
397                 var query = "?op=rpc&id=" + id + "&subop=mark";
398
399                 var img = $("FMPIC-" + id);
400
401                 if (!img) return;
402
403                 if (img.src.match("mark_unset")) {
404                         img.src = img.src.replace("mark_unset", "mark_set");
405                         img.alt = __("Unstar article");
406                         query = query + "&mark=1";
407
408                 } else {
409                         img.src = img.src.replace("mark_set", "mark_unset");
410                         img.alt = __("Star article");
411                         query = query + "&mark=0";
412                 }
413
414                 cache_headlines(getActiveFeedId(), activeFeedIsCat(), null, $("headlines-frame").innerHTML);
415
416                 if (!client_only) {
417                         new Ajax.Request("backend.php", {
418                                 parameters: query,
419                                 onComplete: function(transport) {
420                                         handle_rpc_json(transport);
421                                 } });
422                 }
423
424         } catch (e) {
425                 exception_error("toggleMark", e);
426         }
427 }
428
429 function togglePub(id, client_only, no_effects, note) {
430         try {
431                 var query = "?op=rpc&id=" + id + "&subop=publ";
432
433                 if (note != undefined) {
434                         query = query + "&note=" + param_escape(note);
435                 } else {
436                         query = query + "&note=undefined";
437                 }
438
439                 var img = $("FPPIC-" + id);
440
441                 if (!img) return;
442
443                 if (img.src.match("pub_unset") || note != undefined) {
444                         img.src = img.src.replace("pub_unset", "pub_set");
445                         img.alt = __("Unpublish article");
446                         query = query + "&pub=1";
447
448                 } else {
449                         img.src = img.src.replace("pub_set", "pub_unset");
450                         img.alt = __("Publish article");
451
452                         query = query + "&pub=0";
453                 }
454
455                 cache_headlines(getActiveFeedId(), activeFeedIsCat(), null, $("headlines-frame").innerHTML);
456
457                 if (!client_only) {
458                         new Ajax.Request("backend.php", {
459                                 parameters: query,
460                                 onComplete: function(transport) {
461                                         handle_rpc_json(transport);
462                                 } });
463                 }
464
465         } catch (e) {
466                 exception_error("togglePub", e);
467         }
468 }
469
470 function moveToPost(mode) {
471
472         try {
473
474                 var rows = getVisibleArticleIds();
475
476                 var prev_id = false;
477                 var next_id = false;
478
479                 if (!$('RROW-' + active_post_id)) {
480                         active_post_id = false;
481                 }
482
483                 if (active_post_id == false) {
484                         next_id = getFirstVisibleHeadlineId();
485                         prev_id = getLastVisibleHeadlineId();
486                 } else {
487                         for (var i = 0; i < rows.length; i++) {
488                                 if (rows[i] == active_post_id) {
489                                         prev_id = rows[i-1];
490                                         next_id = rows[i+1];
491                                 }
492                         }
493                 }
494
495                 if (mode == "next") {
496                         if (next_id) {
497                                 if (isCdmMode()) {
498
499                                         cdmExpandArticle(next_id);
500                                         cdmScrollToArticleId(next_id);
501
502                                 } else {
503                                         correctHeadlinesOffset(next_id);
504                                         view(next_id, getActiveFeedId());
505                                 }
506                         }
507                 }
508
509                 if (mode == "prev") {
510                         if (prev_id) {
511                                 if (isCdmMode()) {
512                                         cdmExpandArticle(prev_id);
513                                         cdmScrollToArticleId(prev_id);
514                                 } else {
515                                         correctHeadlinesOffset(prev_id);
516                                         view(prev_id, getActiveFeedId());
517                                 }
518                         }
519                 }
520
521         } catch (e) {
522                 exception_error("moveToPost", e);
523         }
524 }
525
526 function toggleSelected(id, force_on) {
527         try {
528
529                 var cb = $("RCHK-" + id);
530                 var row = $("RROW-" + id);
531
532                 if (row) {
533                         if (row.hasClassName('Selected') && !force_on) {
534                                 row.removeClassName('Selected');
535                                 if (cb) cb.checked = false;
536                         } else {
537                                 row.addClassName('Selected');
538                                 if (cb) cb.checked = true;
539                         }
540                 }
541         } catch (e) {
542                 exception_error("toggleSelected", e);
543         }
544 }
545
546 function toggleUnread_afh(effect) {
547         try {
548
549                 var elem = effect.element;
550                 elem.style.backgroundColor = "";
551
552         } catch (e) {
553                 exception_error("toggleUnread_afh", e);
554         }
555 }
556
557 function toggleUnread(id, cmode, effect) {
558         try {
559
560                 var row = $("RROW-" + id);
561                 if (row) {
562                         if (cmode == undefined || cmode == 2) {
563                                 if (row.hasClassName("Unread")) {
564                                         row.removeClassName("Unread");
565
566                                         if (effect) {
567                                                 new Effect.Highlight(row, {duration: 1, startcolor: "#fff7d5",
568                                                         afterFinish: toggleUnread_afh,
569                                                         queue: { position:'end', scope: 'TMRQ-' + id, limit: 1 } } );
570                                         }
571
572                                 } else {
573                                         row.addClassName("Unread");
574                                 }
575
576                         } else if (cmode == 0) {
577
578                                 row.removeClassName("Unread");
579
580                                 if (effect) {
581                                         new Effect.Highlight(row, {duration: 1, startcolor: "#fff7d5",
582                                                 afterFinish: toggleUnread_afh,
583                                                 queue: { position:'end', scope: 'TMRQ-' + id, limit: 1 } } );
584                                 }
585
586                         } else if (cmode == 1) {
587                                 row.addClassName("Unread");
588                         }
589
590                         if (cmode == undefined) cmode = 2;
591
592                         var query = "?op=rpc&subop=catchupSelected" +
593                                 "&cmode=" + param_escape(cmode) + "&ids=" + param_escape(id);
594
595 //                      notify_progress("Loading, please wait...");
596
597                         new Ajax.Request("backend.php", {
598                                 parameters: query,
599                                 onComplete: function(transport) {
600                                         handle_rpc_json(transport);
601                                 } });
602
603                 }
604
605         } catch (e) {
606                 exception_error("toggleUnread", e);
607         }
608 }
609
610 function selectionRemoveLabel(id, ids) {
611         try {
612
613                 if (!ids) var ids = getSelectedArticleIds2();
614
615                 if (ids.length == 0) {
616                         alert(__("No articles are selected."));
617                         return;
618                 }
619
620                 var query = "?op=rpc&subop=removeFromLabel&ids=" +
621                         param_escape(ids.toString()) + "&lid=" + param_escape(id);
622
623                 console.log(query);
624
625                 new Ajax.Request("backend.php", {
626                         parameters: query,
627                         onComplete: function(transport) {
628                                 handle_rpc_json(transport);
629                                 show_labels_in_headlines(transport);
630                         } });
631
632         } catch (e) {
633                 exception_error("selectionAssignLabel", e);
634
635         }
636 }
637
638 function selectionAssignLabel(id, ids) {
639         try {
640
641                 if (!ids) ids = getSelectedArticleIds2();
642
643                 if (ids.length == 0) {
644                         alert(__("No articles are selected."));
645                         return;
646                 }
647
648                 var query = "?op=rpc&subop=assignToLabel&ids=" +
649                         param_escape(ids.toString()) + "&lid=" + param_escape(id);
650
651                 console.log(query);
652
653                 new Ajax.Request("backend.php", {
654                         parameters: query,
655                         onComplete: function(transport) {
656                                 handle_rpc_json(transport);
657                                 show_labels_in_headlines(transport);
658                         } });
659
660         } catch (e) {
661                 exception_error("selectionAssignLabel", e);
662
663         }
664 }
665
666 function selectionToggleUnread(set_state, callback, no_error) {
667         try {
668                 var rows = getSelectedArticleIds2();
669
670                 if (rows.length == 0 && !no_error) {
671                         alert(__("No articles are selected."));
672                         return;
673                 }
674
675                 for (i = 0; i < rows.length; i++) {
676                         var row = $("RROW-" + rows[i]);
677                         if (row) {
678                                 if (set_state == undefined) {
679                                         if (row.hasClassName("Unread")) {
680                                                 row.removeClassName("Unread");
681                                         } else {
682                                                 row.addClassName("Unread");
683                                         }
684                                 }
685
686                                 if (set_state == false) {
687                                         row.removeClassName("Unread");
688                                 }
689
690                                 if (set_state == true) {
691                                         row.addClassName("Unread");
692                                 }
693                         }
694                 }
695
696                 if (rows.length > 0) {
697
698                         var cmode = "";
699
700                         if (set_state == undefined) {
701                                 cmode = "2";
702                         } else if (set_state == true) {
703                                 cmode = "1";
704                         } else if (set_state == false) {
705                                 cmode = "0";
706                         }
707
708                         var query = "?op=rpc&subop=catchupSelected" +
709                                 "&cmode=" + cmode + "&ids=" + param_escape(rows.toString());
710
711                         notify_progress("Loading, please wait...");
712
713                         new Ajax.Request("backend.php", {
714                                 parameters: query,
715                                 onComplete: function(transport) {
716                                         handle_rpc_json(transport);
717                                         if (callback) callback(transport);
718                                 } });
719
720                 }
721
722         } catch (e) {
723                 exception_error("selectionToggleUnread", e);
724         }
725 }
726
727 function selectionToggleMarked() {
728         try {
729
730                 var rows = getSelectedArticleIds2();
731
732                 if (rows.length == 0) {
733                         alert(__("No articles are selected."));
734                         return;
735                 }
736
737                 for (i = 0; i < rows.length; i++) {
738                         toggleMark(rows[i], true, true);
739                 }
740
741                 if (rows.length > 0) {
742
743                         var query = "?op=rpc&subop=markSelected&ids=" +
744                                 param_escape(rows.toString()) + "&cmode=2";
745
746                         new Ajax.Request("backend.php", {
747                                 parameters: query,
748                                 onComplete: function(transport) {
749                                         handle_rpc_json(transport);
750                                 } });
751
752                 }
753
754         } catch (e) {
755                 exception_error("selectionToggleMarked", e);
756         }
757 }
758
759 function selectionTogglePublished() {
760         try {
761
762                 var rows = getSelectedArticleIds2();
763
764                 if (rows.length == 0) {
765                         alert(__("No articles are selected."));
766                         return;
767                 }
768
769                 for (i = 0; i < rows.length; i++) {
770                         togglePub(rows[i], true, true);
771                 }
772
773                 if (rows.length > 0) {
774
775                         var query = "?op=rpc&subop=publishSelected&ids=" +
776                                 param_escape(rows.toString()) + "&cmode=2";
777
778                         new Ajax.Request("backend.php", {
779                                 parameters: query,
780                                 onComplete: function(transport) {
781                                         handle_rpc_json(transport);
782                                 } });
783
784                 }
785
786         } catch (e) {
787                 exception_error("selectionToggleMarked", e);
788         }
789 }
790
791 function getSelectedArticleIds2() {
792
793         var rv = [];
794
795         $$("#headlines-frame > div[id*=RROW][class*=Selected]").each(
796                 function(child) {
797                         rv.push(child.id.replace("RROW-", ""));
798                 });
799
800         return rv;
801 }
802
803 function getLoadedArticleIds() {
804         var rv = [];
805
806         var children = $$("#headlines-frame > div[id*=RROW-]");
807
808         children.each(function(child) {
809                         rv.push(child.id.replace("RROW-", ""));
810                 });
811
812         return rv;
813
814 }
815
816 // mode = all,none,unread,invert
817 function selectArticles(mode) {
818         try {
819
820                 var children = $$("#headlines-frame > div[id*=RROW]");
821
822                 children.each(function(child) {
823                         var id = child.id.replace("RROW-", "");
824                         var cb = $("RCHK-" + id);
825
826                         if (mode == "all") {
827                                 child.addClassName("Selected");
828                                 cb.checked = true;
829                         } else if (mode == "unread") {
830                                 if (child.hasClassName("Unread")) {
831                                         child.addClassName("Selected");
832                                         cb.checked = true;
833                                 } else {
834                                         child.removeClassName("Selected");
835                                         cb.checked = false;
836                                 }
837                         } else if (mode == "invert") {
838                                 if (child.hasClassName("Selected")) {
839                                         child.removeClassName("Selected");
840                                         cb.checked = false;
841                                 } else {
842                                         child.addClassName("Selected");
843                                         cb.checked = true;
844                                 }
845
846                         } else {
847                                 child.removeClassName("Selected");
848                                 cb.checked = false;
849                         }
850                 });
851
852         } catch (e) {
853                 exception_error("selectArticles", e);
854         }
855 }
856
857 function catchupPage() {
858
859         var fn = getFeedName(getActiveFeedId(), activeFeedIsCat());
860
861         var str = __("Mark all visible articles in %s as read?");
862
863         str = str.replace("%s", fn);
864
865         if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) {
866                 return;
867         }
868
869         selectArticles('all');
870         selectionToggleUnread(false, 'viewCurrentFeed()', true)
871         selectArticles('none');
872 }
873
874 function deleteSelection() {
875
876         try {
877
878                 var rows = getSelectedArticleIds2();
879
880                 if (rows.length == 0) {
881                         alert(__("No articles are selected."));
882                         return;
883                 }
884
885                 var fn = getFeedName(getActiveFeedId(), activeFeedIsCat());
886                 var str;
887                 var op;
888
889                 if (getActiveFeedId() != 0) {
890                         str = __("Delete %d selected articles in %s?");
891                 } else {
892                         str = __("Delete %d selected articles?");
893                 }
894
895                 str = str.replace("%d", rows.length);
896                 str = str.replace("%s", fn);
897
898                 if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) {
899                         return;
900                 }
901
902                 query = "?op=rpc&subop=delete&ids=" + param_escape(rows);
903
904                 console.log(query);
905
906                 new Ajax.Request("backend.php", {
907                         parameters: query,
908                         onComplete: function(transport) {
909                                         handle_rpc_json(transport);
910                                         viewCurrentFeed();
911                                 } });
912
913         } catch (e) {
914                 exception_error("deleteSelection", e);
915         }
916 }
917
918 function archiveSelection() {
919
920         try {
921
922                 var rows = getSelectedArticleIds2();
923
924                 if (rows.length == 0) {
925                         alert(__("No articles are selected."));
926                         return;
927                 }
928
929                 var fn = getFeedName(getActiveFeedId(), activeFeedIsCat());
930                 var str;
931                 var op;
932
933                 if (getActiveFeedId() != 0) {
934                         str = __("Archive %d selected articles in %s?");
935                         op = "archive";
936                 } else {
937                         str = __("Move %d archived articles back?");
938                         op = "unarchive";
939                 }
940
941                 str = str.replace("%d", rows.length);
942                 str = str.replace("%s", fn);
943
944                 if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) {
945                         return;
946                 }
947
948                 query = "?op=rpc&subop="+op+"&ids=" + param_escape(rows);
949
950                 console.log(query);
951
952                 for (var i = 0; i < rows.length; i++) {
953                         cache_delete("article:" + rows[i]);
954                 }
955
956                 new Ajax.Request("backend.php", {
957                         parameters: query,
958                         onComplete: function(transport) {
959                                         handle_rpc_json(transport);
960                                         viewCurrentFeed();
961                                 } });
962
963         } catch (e) {
964                 exception_error("archiveSelection", e);
965         }
966 }
967
968 function catchupSelection() {
969
970         try {
971
972                 var rows = getSelectedArticleIds2();
973
974                 if (rows.length == 0) {
975                         alert(__("No articles are selected."));
976                         return;
977                 }
978
979                 var fn = getFeedName(getActiveFeedId(), activeFeedIsCat());
980
981                 var str = __("Mark %d selected articles in %s as read?");
982
983                 str = str.replace("%d", rows.length);
984                 str = str.replace("%s", fn);
985
986                 if (getInitParam("confirm_feed_catchup") == 1 && !confirm(str)) {
987                         return;
988                 }
989
990                 selectionToggleUnread(false, 'viewCurrentFeed()', true)
991
992         } catch (e) {
993                 exception_error("catchupSelection", e);
994         }
995 }
996
997 function editArticleTags(id) {
998                 var query = "backend.php?op=dlg&id=editArticleTags&param=" + param_escape(id);
999
1000                 if (dijit.byId("editTagsDlg"))
1001                         dijit.byId("editTagsDlg").destroyRecursive();
1002
1003                 dialog = new dijit.Dialog({
1004                         id: "editTagsDlg",
1005                         title: __("Edit article Tags"),
1006                         style: "width: 600px",
1007                         execute: function() {
1008                                 if (this.validate()) {
1009                                         var query = dojo.objectToQuery(this.attr('value'));
1010
1011                                         notify_progress("Saving article tags...", true);
1012
1013                                         new Ajax.Request("backend.php", {
1014                                         parameters: query,
1015                                         onComplete: function(transport) {
1016                                                 notify('');
1017                                                 dialog.hide();
1018
1019                                                 var data = JSON.parse(transport.responseText);
1020
1021                                                 if (data) {
1022                                                         var tags_str = article.tags;
1023                                                         var id = tags_str.id;
1024
1025                                                         var tags = $("ATSTR-" + id);
1026                                                         var tooltip = dijit.byId("ATSTRTIP-" + id);
1027
1028                                                         if (tags) tags.innerHTML = tags_str.content;
1029                                                         if (tooltip) tooltip.attr('label', tags_str.content_full);
1030
1031                                                         cache_delete("article:" + id);
1032                                                 }
1033
1034                                         }});
1035                                 }
1036                         },
1037                         href: query,
1038                 });
1039
1040                 var tmph = dojo.connect(dialog, 'onLoad', function() {
1041                 dojo.disconnect(tmph);
1042
1043                         new Ajax.Autocompleter('tags_str', 'tags_choices',
1044                            "backend.php?op=rpc&subop=completeTags",
1045                            { tokens: ',', paramName: "search" });
1046                 });
1047
1048                 dialog.show();
1049
1050 }
1051
1052 function cdmScrollToArticleId(id) {
1053         try {
1054                 var ctr = $("headlines-frame");
1055                 var e = $("RROW-" + id);
1056
1057                 if (!e || !ctr) return;
1058
1059                 ctr.scrollTop = e.offsetTop;
1060
1061         } catch (e) {
1062                 exception_error("cdmScrollToArticleId", e);
1063         }
1064 }
1065
1066 function getActiveArticleId() {
1067         return active_post_id;
1068 }
1069
1070 function postMouseIn(id) {
1071         post_under_pointer = id;
1072 }
1073
1074 function postMouseOut(id) {
1075         post_under_pointer = false;
1076 }
1077
1078 function headlines_scroll_handler(e) {
1079         try {
1080                 var hsp = $("headlines-spacer");
1081
1082                 if (!_infscroll_disable) {
1083                         if (hsp && (e.scrollTop + e.offsetHeight > hsp.offsetTop) ||
1084                                         e.scrollTop + e.offsetHeight > e.scrollHeight - 100) {
1085
1086                                 hsp.innerHTML = "<img src='images/indicator_tiny.gif'> " +
1087                                         __("Loading, please wait...");
1088
1089                                 loadMoreHeadlines();
1090
1091                                 //viewNextFeedPage();
1092                         }
1093                 } else {
1094                         if (hsp) hsp.innerHTML = "";
1095                 }
1096
1097                 if (getInitParam("cdm_auto_catchup") == 1) {
1098
1099                         $$("#headlines-frame > div[id*=RROW][class*=Unread]").each(
1100                                 function(child) {
1101                                         if ($("headlines-frame").scrollTop >
1102                                                         (child.offsetTop + child.offsetHeight/2)) {
1103
1104                                                 var id = child.id.replace("RROW-", "");
1105
1106                                                 if (catchup_id_batch.indexOf(id) == -1)
1107                                                         catchup_id_batch.push(id);
1108                                         }
1109                                 });
1110
1111                         if (catchup_id_batch.length > 0 && !_infscroll_request_sent) {
1112                                 window.clearTimeout(catchup_timeout_id);
1113                                 catchup_timeout_id = window.setTimeout('catchupBatchedArticles()',
1114                                                 1000);
1115                         }
1116                 }
1117
1118         } catch (e) {
1119                 console.warn("headlines_scroll_handler: " + e);
1120         }
1121 }
1122
1123 function catchupBatchedArticles() {
1124         try {
1125                 if (catchup_id_batch.length > 0 && !_infscroll_request_sent) {
1126
1127                         var query = "?op=rpc&subop=catchupSelected" +
1128                                 "&cmode=0&ids=" + param_escape(catchup_id_batch.toString());
1129
1130                         new Ajax.Request("backend.php", {
1131                                 parameters: query,
1132                                 onComplete: function(transport) {
1133                                         handle_rpc_json(transport);
1134
1135                                         catchup_id_batch.each(function(id) {
1136                                                 var elem = $("RROW-" + id);
1137                                                 if (elem) elem.removeClassName("Unread");
1138                                         });
1139
1140                                         catchup_id_batch = [];
1141                                 } });
1142                 }
1143
1144         } catch (e) {
1145                 exception_error("catchupBatchedArticles", e);
1146         }
1147 }
1148
1149 function catchupRelativeToArticle(below) {
1150
1151         try {
1152
1153
1154                 if (!getActiveArticleId()) {
1155                         alert(__("No article is selected."));
1156                         return;
1157                 }
1158
1159                 var visible_ids = getVisibleArticleIds();
1160
1161                 var ids_to_mark = new Array();
1162
1163                 if (!below) {
1164                         for (var i = 0; i < visible_ids.length; i++) {
1165                                 if (visible_ids[i] != getActiveArticleId()) {
1166                                         var e = $("RROW-" + visible_ids[i]);
1167
1168                                         if (e && e.hasClassName("Unread")) {
1169                                                 ids_to_mark.push(visible_ids[i]);
1170                                         }
1171                                 } else {
1172                                         break;
1173                                 }
1174                         }
1175                 } else {
1176                         for (var i = visible_ids.length-1; i >= 0; i--) {
1177                                 if (visible_ids[i] != getActiveArticleId()) {
1178                                         var e = $("RROW-" + visible_ids[i]);
1179
1180                                         if (e && e.hasClassName("Unread")) {
1181                                                 ids_to_mark.push(visible_ids[i]);
1182                                         }
1183                                 } else {
1184                                         break;
1185                                 }
1186                         }
1187                 }
1188
1189                 if (ids_to_mark.length == 0) {
1190                         alert(__("No articles found to mark"));
1191                 } else {
1192                         var msg = __("Mark %d article(s) as read?").replace("%d", ids_to_mark.length);
1193
1194                         if (getInitParam("confirm_feed_catchup") != 1 || confirm(msg)) {
1195
1196                                 for (var i = 0; i < ids_to_mark.length; i++) {
1197                                         var e = $("RROW-" + ids_to_mark[i]);
1198                                         e.removeClassName("Unread");
1199                                 }
1200
1201                                 var query = "?op=rpc&subop=catchupSelected" +
1202                                         "&cmode=0" + "&ids=" + param_escape(ids_to_mark.toString());
1203
1204                                 new Ajax.Request("backend.php", {
1205                                         parameters: query,
1206                                         onComplete: function(transport) {
1207                                                 handle_rpc_json(transport);
1208                                         } });
1209
1210                         }
1211                 }
1212
1213         } catch (e) {
1214                 exception_error("catchupRelativeToArticle", e);
1215         }
1216 }
1217
1218 function cdmExpandArticle(id) {
1219         try {
1220
1221                 hideAuxDlg();
1222
1223                 var elem = $("CICD-" + active_post_id);
1224
1225                 var upd_img_pic = $("FUPDPIC-" + id);
1226
1227                 if (upd_img_pic && (upd_img_pic.src.match("updated.png") ||
1228                                 upd_img_pic.src.match("fresh_sign.png"))) {
1229
1230                         upd_img_pic.src = "images/blank_icon.gif";
1231                 }
1232
1233                 if (id == active_post_id && Element.visible(elem))
1234                         return true;
1235
1236                 selectArticles("none");
1237
1238                 var old_offset = $("RROW-" + id).offsetTop;
1239
1240                 if (active_post_id && elem && !getInitParam("cdm_expanded")) {
1241                         Element.hide(elem);
1242                         Element.show("CEXC-" + active_post_id);
1243                 }
1244
1245                 active_post_id = id;
1246
1247                 elem = $("CICD-" + id);
1248
1249                 if (!Element.visible(elem)) {
1250                         Element.show(elem);
1251                         Element.hide("CEXC-" + id);
1252
1253                         if ($("CWRAP-" + id).innerHTML == "") {
1254
1255                                 $("FUPDPIC-" + id).src = "images/indicator_tiny.gif";
1256
1257                                 $("CWRAP-" + id).innerHTML = "<div class=\"insensitive\">" +
1258                                         __("Loading, please wait...") + "</div>";
1259
1260                                 var query = "?op=rpc&subop=cdmGetArticle&id=" + param_escape(id);
1261
1262                                 var neighbor_ids = getRelativePostIds(id);
1263
1264                                 /* only request uncached articles */
1265                                 var cids_to_request = [];
1266
1267                                 for (var i = 0; i < neighbor_ids.length; i++) {
1268                                         if (cids_requested.indexOf(neighbor_ids[i]) == -1)
1269                                                 if ($("CWRAP-" + neighbor_ids[i]).innerHTML == "") {
1270                                                         cids_to_request.push(neighbor_ids[i]);
1271                                                         cids_requested.push(neighbor_ids[i]);
1272                                                 }
1273                                 }
1274
1275                                 console.log("additional ids: " + cids_to_request.toString());
1276
1277                                 query = query + "&cids=" + cids_to_request.toString();
1278
1279                                 console.log(query);
1280
1281                                 new Ajax.Request("backend.php", {
1282                                         parameters: query,
1283                                         onComplete: function(transport) {
1284
1285                                                 $("FUPDPIC-" + id).src = 'images/blank_icon.gif';
1286
1287                                                 handle_rpc_json(transport);
1288
1289                                                 var reply = JSON.parse(transport.responseText);
1290
1291                                                 reply.each(function(article) {
1292                                                         $("CWRAP-" + article['id']).innerHTML = article['content']
1293                                                         cids_requested.remove(article['id']);
1294                                                 });
1295                                 }});
1296
1297                         }
1298                 }
1299
1300                 var new_offset = $("RROW-" + id).offsetTop;
1301
1302                 $("headlines-frame").scrollTop += (new_offset-old_offset);
1303
1304                 if ($("RROW-" + id).offsetTop != old_offset)
1305                         $("headlines-frame").scrollTop = new_offset;
1306
1307                 toggleUnread(id, 0, true);
1308                 toggleSelected(id);
1309
1310         } catch (e) {
1311                 exception_error("cdmExpandArticle", e);
1312         }
1313
1314         return false;
1315 }
1316
1317 function fixHeadlinesOrder(ids) {
1318         try {
1319                 for (var i = 0; i < ids.length; i++) {
1320                         var e = $("RROW-" + ids[i]);
1321
1322                         if (e) {
1323                                 if (i % 2 == 0) {
1324                                         e.removeClassName("even");
1325                                         e.addClassName("odd");
1326                                 } else {
1327                                         e.removeClassName("odd");
1328                                         e.addClassName("even");
1329                                 }
1330                         }
1331                 }
1332         } catch (e) {
1333                 exception_error("fixHeadlinesOrder", e);
1334         }
1335 }
1336
1337 function getArticleUnderPointer() {
1338         return post_under_pointer;
1339 }
1340
1341 function zoomToArticle(event, id) {
1342         try {
1343                 var cached_article = cache_get("article: " + id);
1344
1345                 if (dijit.byId("ATAB-" + id))
1346                         if (!event || !event.shiftKey)
1347                                 return dijit.byId("content-tabs").selectChild(dijit.byId("ATAB-" + id));
1348
1349                 if (dijit.byId("ATSTRTIP-" + id))
1350                         dijit.byId("ATSTRTIP-" + id).destroyRecursive();
1351
1352                 if (cached_article) {
1353                         //closeArticlePanel();
1354
1355                         var article_pane = new dijit.layout.ContentPane({
1356                                 title: __("Loading...") , content: cached_article,
1357                                 style: 'padding : 0px;',
1358                                 id: 'ATAB-' + id,
1359                                 closable: true });
1360
1361                         dijit.byId("content-tabs").addChild(article_pane);
1362
1363                         if (!event || !event.shiftKey)
1364                                 dijit.byId("content-tabs").selectChild(article_pane);
1365
1366                         if ($("PTITLE-" + id))
1367                                 article_pane.attr('title', $("PTITLE-" + id).innerHTML);
1368
1369                 } else {
1370
1371                         var query = "?op=rpc&subop=getArticles&ids=" + param_escape(id);
1372
1373                         notify_progress("Loading, please wait...", true);
1374
1375                         new Ajax.Request("backend.php", {
1376                                 parameters: query,
1377                                 onComplete: function(transport) {
1378                                         notify('');
1379
1380                                         var reply = JSON.parse(transport.responseText);
1381
1382                                         if (reply) {
1383                                                 //closeArticlePanel();
1384
1385                                                 var content = reply[0]['content'];
1386
1387                                                 var article_pane = new dijit.layout.ContentPane({
1388                                                         title: "article-" + id , content: content,
1389                                                         style: 'padding : 0px;',
1390                                                         id: 'ATAB-' + id,
1391                                                         closable: true });
1392
1393                                                 dijit.byId("content-tabs").addChild(article_pane);
1394
1395                                                 if (!event || !event.shiftKey)
1396                                                         dijit.byId("content-tabs").selectChild(article_pane);
1397
1398                                                 if ($("PTITLE-" + id))
1399                                                         article_pane.attr('title', $("PTITLE-" + id).innerHTML);
1400                                         }
1401
1402                                 } });
1403                         }
1404
1405         } catch (e) {
1406                 exception_error("zoomToArticle", e);
1407         }
1408 }
1409
1410 function scrollArticle(offset) {
1411         try {
1412                 if (!isCdmMode()) {
1413                         var ci = $("content-insert");
1414                         if (ci) {
1415                                 ci.scrollTop += offset;
1416                         }
1417                 } else {
1418                         var hi = $("headlines-frame");
1419                         if (hi) {
1420                                 hi.scrollTop += offset;
1421                         }
1422
1423                 }
1424         } catch (e) {
1425                 exception_error("scrollArticle", e);
1426         }
1427 }
1428
1429 function show_labels_in_headlines(transport) {
1430         try {
1431                 var data = JSON.parse(transport.responseText);
1432
1433                 if (data) {
1434                         data['info-for-headlines'].each(function(elem) {
1435                                 var ctr = $("HLLCTR-" + elem.id);
1436
1437                                 if (ctr) ctr.innerHTML = elem.labels;
1438                         });
1439
1440                         cache_headlines(getActiveFeedId(), activeFeedIsCat(), null, $("headlines-frame").innerHTML);
1441
1442                 }
1443         } catch (e) {
1444                 exception_error("show_labels_in_headlines", e);
1445         }
1446 }
1447
1448 /* function toggleHeadlineActions() {
1449         try {
1450                 var e = $("headlineActionsBody");
1451                 var p = $("headlineActionsDrop");
1452
1453                 if (!Element.visible(e)) {
1454                         Element.show(e);
1455                 } else {
1456                         Element.hide(e);
1457                 }
1458
1459                 e.scrollTop = 0;
1460                 e.style.left = (p.offsetLeft + 1) + "px";
1461                 e.style.top = (p.offsetTop + p.offsetHeight + 2) + "px";
1462
1463         } catch (e) {
1464                 exception_error("toggleHeadlineActions", e);
1465         }
1466 } */
1467
1468 /* function publishWithNote(id, def_note) {
1469         try {
1470                 if (!def_note) def_note = '';
1471
1472                 var note = prompt(__("Please enter a note for this article:"), def_note);
1473
1474                 if (note != undefined) {
1475                         togglePub(id, false, false, note);
1476                 }
1477
1478         } catch (e) {
1479                 exception_error("publishWithNote", e);
1480         }
1481 } */
1482
1483 function emailArticle(id) {
1484         try {
1485                 if (!id) {
1486                         var ids = getSelectedArticleIds2();
1487
1488                         if (ids.length == 0) {
1489                                 alert(__("No articles are selected."));
1490                                 return;
1491                         }
1492
1493                         id = ids.toString();
1494                 }
1495
1496                 if (dijit.byId("emailArticleDlg"))
1497                         dijit.byId("emailArticleDlg").destroyRecursive();
1498
1499                 var query = "backend.php?op=dlg&id=emailArticle&param=" + param_escape(id);
1500
1501                 dialog = new dijit.Dialog({
1502                         id: "emailArticleDlg",
1503                         title: __("Forward article by email"),
1504                         style: "width: 600px",
1505                         execute: function() {
1506                                 if (this.validate()) {
1507
1508                                         new Ajax.Request("backend.php", {
1509                                                 parameters: dojo.objectToQuery(this.attr('value')),
1510                                                 onComplete: function(transport) {
1511
1512                                                         var reply = JSON.parse(transport.responseText);
1513
1514                                                         var error = reply['error'];
1515
1516                                                         if (error) {
1517                                                                 alert(__('Error sending email:') + ' ' + error);
1518                                                         } else {
1519                                                                 notify_info('Your message has been sent.');
1520                                                                 dialog.hide();
1521                                                         }
1522
1523                                         } });
1524                                 }
1525                         },
1526                         href: query});
1527
1528                 var tmph = dojo.connect(dialog, 'onLoad', function() {
1529                 dojo.disconnect(tmph);
1530
1531                    new Ajax.Autocompleter('emailArticleDlg_destination', 'emailArticleDlg_dst_choices',
1532                            "backend.php?op=rpc&subop=completeEmails",
1533                            { tokens: '', paramName: "search" });
1534                 });
1535
1536                 dialog.show();
1537
1538                 /* displayDlg('emailArticle', id,
1539                    function () {
1540                                 document.forms['article_email_form'].destination.focus();
1541
1542                            new Ajax.Autocompleter('destination', 'destination_choices',
1543                                    "backend.php?op=rpc&subop=completeEmails",
1544                                    { tokens: '', paramName: "search" });
1545
1546                         }); */
1547
1548         } catch (e) {
1549                 exception_error("emailArticle", e);
1550         }
1551 }
1552
1553 function dismissArticle(id) {
1554         try {
1555                 var elem = $("RROW-" + id);
1556
1557                 toggleUnread(id, 0, true);
1558
1559                 new Effect.Fade(elem, {duration : 0.5});
1560
1561                 active_post_id = false;
1562
1563         } catch (e) {
1564                 exception_error("dismissArticle", e);
1565         }
1566 }
1567
1568 function dismissSelectedArticles() {
1569         try {
1570
1571                 var ids = getVisibleArticleIds();
1572                 var tmp = [];
1573                 var sel = [];
1574
1575                 for (var i = 0; i < ids.length; i++) {
1576                         var elem = $("RROW-" + ids[i]);
1577
1578                         if (elem.className && elem.hasClassName("Selected") &&
1579                                         ids[i] != active_post_id) {
1580                                 new Effect.Fade(elem, {duration : 0.5});
1581                                 sel.push(ids[i]);
1582                         } else {
1583                                 tmp.push(ids[i]);
1584                         }
1585                 }
1586
1587                 if (sel.length > 0)
1588                         selectionToggleUnread(false);
1589
1590                 fixHeadlinesOrder(tmp);
1591
1592         } catch (e) {
1593                 exception_error("dismissSelectedArticles", e);
1594         }
1595 }
1596
1597 function dismissReadArticles() {
1598         try {
1599
1600                 var ids = getVisibleArticleIds();
1601                 var tmp = [];
1602
1603                 for (var i = 0; i < ids.length; i++) {
1604                         var elem = $("RROW-" + ids[i]);
1605
1606                         if (elem.className && !elem.hasClassName("Unread") &&
1607                                         !elem.hasClassName("Selected")) {
1608
1609                                 new Effect.Fade(elem, {duration : 0.5});
1610                         } else {
1611                                 tmp.push(ids[i]);
1612                         }
1613                 }
1614
1615                 fixHeadlinesOrder(tmp);
1616
1617         } catch (e) {
1618                 exception_error("dismissSelectedArticles", e);
1619         }
1620 }
1621
1622 function getVisibleArticleIds() {
1623         var ids = [];
1624
1625         try {
1626
1627                 getLoadedArticleIds().each(function(id) {
1628                         var elem = $("RROW-" + id);
1629                         if (elem && Element.visible(elem))
1630                                 ids.push(id);
1631                         });
1632
1633         } catch (e) {
1634                 exception_error("getVisibleArticleIds", e);
1635         }
1636
1637         return ids;
1638 }
1639
1640 function cdmClicked(event, id) {
1641         try {
1642                 var shift_key = event.shiftKey;
1643
1644                 hideAuxDlg();
1645
1646                 if (!event.ctrlKey) {
1647
1648                         if (!getInitParam("cdm_expanded")) {
1649                                 return cdmExpandArticle(id);
1650                         } else {
1651
1652                                 selectArticles("none");
1653                                 toggleSelected(id);
1654
1655                                 var elem = $("RROW-" + id);
1656
1657                                 if (elem)
1658                                         elem.removeClassName("Unread");
1659
1660                                 var upd_img_pic = $("FUPDPIC-" + id);
1661
1662                                 if (upd_img_pic && (upd_img_pic.src.match("updated.png") ||
1663                                                 upd_img_pic.src.match("fresh_sign.png"))) {
1664
1665                                         upd_img_pic.src = "images/blank_icon.gif";
1666                                 }
1667
1668                                 active_post_id = id;
1669
1670                                 var query = "?op=rpc&subop=catchupSelected" +
1671                                         "&cmode=0&ids=" + param_escape(id);
1672
1673                                 new Ajax.Request("backend.php", {
1674                                         parameters: query,
1675                                         onComplete: function(transport) {
1676                                                 handle_rpc_json(transport);
1677                                         } });
1678
1679                                 return true;
1680                         }
1681
1682                 } else {
1683                         toggleSelected(id, true);
1684                         toggleUnread(id, 0, false);
1685                         zoomToArticle(event, id);
1686                 }
1687
1688         } catch (e) {
1689                 exception_error("cdmClicked");
1690         }
1691
1692         return false;
1693 }
1694
1695 function postClicked(event, id) {
1696         try {
1697
1698                 if (!event.ctrlKey) {
1699                         return true;
1700                 } else {
1701                         postOpenInNewTab(event, id);
1702                         return false;
1703                 }
1704
1705         } catch (e) {
1706                 exception_error("postClicked");
1707         }
1708 }
1709
1710 function hlOpenInNewTab(event, id) {
1711         toggleUnread(id, 0, false);
1712         zoomToArticle(event, id);
1713 }
1714
1715 function postOpenInNewTab(event, id) {
1716         closeArticlePanel(id);
1717         zoomToArticle(event, id);
1718 }
1719
1720 function hlClicked(event, id) {
1721         try {
1722                 if (event.which == 2) {
1723                         view(id);
1724                         return true;
1725                 } else if (event.altKey) {
1726                         openArticleInNewWindow(id);
1727                 } else if (!event.ctrlKey) {
1728                         view(id);
1729                         return false;
1730                 } else {
1731                         toggleSelected(id);
1732                         toggleUnread(id, 0, false);
1733                         zoomToArticle(event, id);
1734                         return false;
1735                 }
1736
1737         } catch (e) {
1738                 exception_error("hlClicked");
1739         }
1740 }
1741
1742 function getFirstVisibleHeadlineId() {
1743         var rows = getVisibleArticleIds();
1744         return rows[0];
1745
1746 }
1747
1748 function getLastVisibleHeadlineId() {
1749         var rows = getVisibleArticleIds();
1750         return rows[rows.length-1];
1751 }
1752
1753 function openArticleInNewWindow(id) {
1754         toggleUnread(id, 0, false);
1755         window.open("backend.php?op=la&id=" + id);
1756 }
1757
1758 function isCdmMode() {
1759         return getInitParam("combined_display_mode");
1760 }
1761
1762 function markHeadline(id) {
1763         var row = $("RROW-" + id);
1764         if (row) {
1765                 var check = $("RCHK-" + id);
1766
1767                 if (check) {
1768                         check.checked = true;
1769                 }
1770
1771                 row.addClassName("Selected");
1772         }
1773 }
1774
1775 function getRelativePostIds(id, limit) {
1776
1777         var tmp = [];
1778
1779         try {
1780
1781                 if (!limit) limit = 6; //3
1782
1783                 var ids = getVisibleArticleIds();
1784
1785                 for (var i = 0; i < ids.length; i++) {
1786                         if (ids[i] == id) {
1787                                 for (var k = 1; k <= limit; k++) {
1788                                         //if (i > k-1) tmp.push(ids[i-k]);
1789                                         if (i < ids.length-k) tmp.push(ids[i+k]);
1790                                 }
1791                                 break;
1792                         }
1793                 }
1794
1795         } catch (e) {
1796                 exception_error("getRelativePostIds", e);
1797         }
1798
1799         return tmp;
1800 }
1801
1802 function correctHeadlinesOffset(id) {
1803
1804         try {
1805
1806                 var container = $("headlines-frame");
1807                 var row = $("RROW-" + id);
1808
1809                 var viewport = container.offsetHeight;
1810
1811                 var rel_offset_top = row.offsetTop - container.scrollTop;
1812                 var rel_offset_bottom = row.offsetTop + row.offsetHeight - container.scrollTop;
1813
1814                 //console.log("Rtop: " + rel_offset_top + " Rbtm: " + rel_offset_bottom);
1815                 //console.log("Vport: " + viewport);
1816
1817                 if (rel_offset_top <= 0 || rel_offset_top > viewport) {
1818                         container.scrollTop = row.offsetTop;
1819                 } else if (rel_offset_bottom > viewport) {
1820
1821                         /* doesn't properly work with Opera in some cases because
1822                                 Opera fucks up element scrolling */
1823
1824                         container.scrollTop = row.offsetTop + row.offsetHeight - viewport;
1825                 }
1826
1827         } catch (e) {
1828                 exception_error("correctHeadlinesOffset", e);
1829         }
1830
1831 }
1832
1833 function headlineActionsChange(elem) {
1834         try {
1835                 eval(elem.value);
1836                 elem.attr('value', 'false');
1837         } catch (e) {
1838                 exception_error("headlineActionsChange", e);
1839         }
1840 }
1841
1842 function closeArticlePanel() {
1843
1844         var tabs = dijit.byId("content-tabs");
1845         var child = tabs.selectedChildWidget;
1846
1847         if (child && tabs.getIndexOfChild(child) > 0) {
1848                 tabs.removeChild(child);
1849                 child.destroy();
1850         } else {
1851                 if (dijit.byId("content-insert"))
1852                         dijit.byId("headlines-wrap-inner").removeChild(
1853                                 dijit.byId("content-insert"));
1854         }
1855 }
1856
1857 function initHeadlinesMenu() {
1858         try {
1859                 if (dijit.byId("headlinesMenu"))
1860                         dijit.byId("headlinesMenu").destroyRecursive();
1861
1862                 var ids = [];
1863
1864                 if (!isCdmMode()) {
1865                         nodes = $$("#headlines-frame > div[id*=RROW]");
1866                 } else {
1867                         nodes = $$("#headlines-frame span[id*=RTITLE]");
1868                 }
1869
1870                 nodes.each(function(node) {
1871                         ids.push(node.id);
1872                 });
1873
1874                 var menu = new dijit.Menu({
1875                         id: "headlinesMenu",
1876                         targetNodeIds: ids,
1877                 });
1878
1879                 var tmph = dojo.connect(menu, '_openMyself', function (event) {
1880                         var callerNode = event.target, match = null, tries = 0;
1881
1882                         while (match == null && callerNode && tries <= 3) {
1883                                 match = callerNode.id.match("^[A-Z]+[-]([0-9]+)$");
1884                                 callerNode = callerNode.parentNode;
1885                                 ++tries;
1886                         }
1887
1888                         if (match) this.callerRowId = parseInt(match[1]);
1889
1890                 });
1891
1892 /*              if (!isCdmMode())
1893                         menu.addChild(new dijit.MenuItem({
1894                                 label: __("View article"),
1895                                 onClick: function(event) {
1896                                         view(this.getParent().callerRowId);
1897                                 }})); */
1898
1899                 menu.addChild(new dijit.MenuItem({
1900                         label: __("Open original article"),
1901                         onClick: function(event) {
1902                                 openArticleInNewWindow(this.getParent().callerRowId);
1903                         }}));
1904
1905                 menu.addChild(new dijit.MenuItem({
1906                         label: __("View in a tt-rss tab"),
1907                         onClick: function(event) {
1908                                 hlOpenInNewTab(event, this.getParent().callerRowId);
1909                                 }}));
1910
1911 //              menu.addChild(new dijit.MenuSeparator());
1912
1913                 var labels = dijit.byId("feedTree").model.getItemsInCategory(-2);
1914
1915                 if (labels) {
1916
1917                         menu.addChild(new dijit.MenuSeparator());
1918
1919                         var labelAddMenu = new dijit.Menu({ownerMenu: menu});
1920                         var labelDelMenu = new dijit.Menu({ownerMenu: menu});
1921
1922                         labels.each(function(label) {
1923                                 var id = label.id[0];
1924                                 var bare_id = id.substr(id.indexOf(":")+1);
1925                                 var name = label.name[0];
1926
1927                                 bare_id = -11-bare_id;
1928
1929                                 labelAddMenu.addChild(new dijit.MenuItem({
1930                                         label: name,
1931                                         labelId: bare_id,
1932                                         onClick: function(event) {
1933                                                 selectionAssignLabel(this.labelId,
1934                                                         [this.getParent().ownerMenu.callerRowId]);
1935                                 }}));
1936
1937                                 labelDelMenu.addChild(new dijit.MenuItem({
1938                                         label: name,
1939                                         labelId: bare_id,
1940                                         onClick: function(event) {
1941                                                 selectionRemoveLabel(this.labelId,
1942                                                         [this.getParent().ownerMenu.callerRowId]);
1943                                 }}));
1944
1945                         });
1946
1947                         menu.addChild(new dijit.PopupMenuItem({
1948                                 label: __("Assign label"),
1949                                 popup: labelAddMenu,
1950                         }));
1951
1952                         menu.addChild(new dijit.PopupMenuItem({
1953                                 label: __("Remove label"),
1954                                 popup: labelDelMenu,
1955                         }));
1956
1957                 }
1958
1959                 menu.startup();
1960
1961         } catch (e) {
1962                 exception_error("initHeadlinesMenu", e);
1963         }
1964 }
1965
1966 function tweetArticle(id) {
1967         try {
1968                 var query = "?op=rpc&subop=getTweetInfo&id=" + param_escape(id);
1969
1970                 console.log(query);
1971
1972                 var d = new Date();
1973       var ts = d.getTime();
1974
1975                 var w = window.open('backend.php?op=loading', 'ttrss_tweet',
1976                         "status=0,toolbar=0,location=0,width=500,height=400,scrollbars=1,menubar=0");
1977
1978                 new Ajax.Request("backend.php", {
1979                         parameters: query,
1980                         onComplete: function(transport) {
1981                                 var ti = JSON.parse(transport.responseText);
1982
1983                                 var share_url = "http://twitter.com/share?_=" + ts +
1984                                         "&text=" + param_escape(ti.title) +
1985                                         "&url=" + param_escape(ti.link);
1986
1987                                 w.location.href = share_url;
1988
1989                         } });
1990
1991
1992         } catch (e) {
1993                 exception_error("tweetArticle", e);
1994         }
1995 }
1996
1997 function editArticleNote(id) {
1998         try {
1999
2000                 var query = "backend.php?op=dlg&id=editArticleNote&param=" + param_escape(id);
2001
2002                 if (dijit.byId("editNoteDlg"))
2003                         dijit.byId("editNoteDlg").destroyRecursive();
2004
2005                 dialog = new dijit.Dialog({
2006                         id: "editNoteDlg",
2007                         title: __("Edit article note"),
2008                         style: "width: 600px",
2009                         execute: function() {
2010                                 if (this.validate()) {
2011                                         var query = dojo.objectToQuery(this.attr('value'));
2012
2013                                         notify_progress("Saving article note...", true);
2014
2015                                         new Ajax.Request("backend.php", {
2016                                         parameters: query,
2017                                         onComplete: function(transport) {
2018                                                 notify('');
2019                                                 dialog.hide();
2020
2021                                                 var reply = JSON.parse(transport.responseText);
2022
2023                                                 cache_delete("article:" + id);
2024
2025                                                 var elem = $("POSTNOTE-" + id);
2026
2027                                                 if (elem) {
2028                                                         Element.hide(elem);
2029                                                         elem.innerHTML = reply.note;
2030
2031                                                         if (reply.raw_length != 0)
2032                                                                 new Effect.Appear(elem);
2033                                                 }
2034
2035                                         }});
2036                                 }
2037                         },
2038                         href: query,
2039                 });
2040
2041                 dialog.show();
2042
2043         } catch (e) {
2044                 exception_error("editArticleNote", e);
2045         }
2046 }
2047
2048 function player(elem) {
2049         var aid = elem.getAttribute("audio-id");
2050         var status = elem.getAttribute("status");
2051
2052         var audio = $(aid);
2053
2054         if (audio) {
2055                 if (status == 0) {
2056                         audio.play();
2057                         status = 1;
2058                         elem.innerHTML = __("Playing...");
2059                         elem.title = __("Click to pause");
2060                         elem.addClassName("playing");
2061                 } else {
2062                         audio.pause();
2063                         status = 0;
2064                         elem.innerHTML = __("Play");
2065                         elem.title = __("Click to play");
2066                         elem.removeClassName("playing");
2067                 }
2068
2069                 elem.setAttribute("status", status);
2070         } else {
2071                 alert("Your browser doesn't seem to support HTML5 audio.");
2072         }
2073 }
2074
2075 function cache_set(id, obj) {
2076         //console.log("cache_set: " + id);
2077         if (has_storage)
2078                 try {
2079                         sessionStorage[id] = obj;
2080                 } catch (e) {
2081                         sessionStorage.clear();
2082                 }
2083 }
2084
2085 function cache_get(id) {
2086         if (has_storage)
2087                 return sessionStorage[id];
2088 }
2089
2090 function cache_clear() {
2091         if (has_storage)
2092                 sessionStorage.clear();
2093 }
2094
2095 function cache_delete(id) {
2096         if (has_storage)
2097                 sessionStorage.removeItem(id);
2098 }
2099
2100 function cache_headlines(feed, is_cat, toolbar_obj, content_obj) {
2101         if (toolbar_obj && content_obj) {
2102                 cache_set("feed:" + feed + ":" + is_cat,
2103                         JSON.stringify({toolbar: toolbar_obj, content: content_obj}));
2104         } else {
2105                 try {
2106                         obj =   cache_get("feed:" + feed + ":" + is_cat);
2107
2108                         if (obj) {
2109                                 obj = JSON.parse(obj);
2110
2111                                 if (toolbar_obj) obj.toolbar = toolbar_obj;
2112                                 if (content_obj) obj.content = content_obj;
2113
2114                                 cache_set("feed:" + feed + ":" + is_cat, JSON.stringify(obj));
2115                         }
2116
2117                 } catch (e) {
2118                         console.warn("cache_headlines failed: " + e);
2119                 }
2120         }
2121 }
2122
2123 function render_local_headlines(feed, is_cat, obj) {
2124         try {
2125
2126                 dijit.byId("headlines-toolbar").attr('content',
2127                         obj.toolbar);
2128
2129                 dijit.byId("headlines-frame").attr('content',
2130                         obj.content);
2131
2132                 dojo.parser.parse('headlines-toolbar');
2133
2134                 $("headlines-frame").scrollTop = 0;
2135                 selectArticles('none');
2136                 setActiveFeedId(feed, is_cat);
2137                 initHeadlinesMenu();
2138
2139                 precache_headlines();
2140
2141         } catch (e) {
2142                 exception_error("render_local_headlines", e);
2143         }
2144 }
2145
2146 function precache_headlines_idle() {
2147         try {
2148                 if (!feed_precache_timeout_id) {
2149                         var feeds = dijit.byId("feedTree").getVisibleUnreadFeeds();
2150                         var uncached = [];
2151
2152                         feeds.each(function(item) {
2153                                 if (parseInt(item[0]) > 0 && !cache_get("feed:" + item[0] + ":" + item[1]))
2154                                         uncached.push(item);
2155                         });
2156
2157                         if (uncached.length > 0) {
2158                                 var rf = uncached[Math.floor(Math.random()*uncached.length)];
2159                                 viewfeed(rf[0], '', rf[1], 0, true);
2160                         }
2161                 }
2162                 precache_idle_timeout_id = setTimeout("precache_headlines_idle()", 5000);
2163
2164         } catch (e) {
2165                 exception_error("precache_headlines_idle", e);
2166         }
2167 }
2168
2169 function precache_headlines() {
2170         try {
2171
2172                 if (!feed_precache_timeout_id) {
2173                         feed_precache_timeout_id = window.setTimeout(function() {
2174                                 var nuf = getNextUnreadFeed(getActiveFeedId(), activeFeedIsCat());
2175                                 var nf = dijit.byId("feedTree").getNextFeed(getActiveFeedId(), activeFeedIsCat());
2176
2177                                 if (nuf && !cache_get("feed:" + nuf + ":" + activeFeedIsCat()))
2178                                         viewfeed(nuf, '', activeFeedIsCat(), 0, true);
2179
2180                                 if (nf != nuf && nf && !cache_get("feed:" + nf[0] + ":" + nf[1]))
2181                                         viewfeed(nf[0], '', nf[1], 0, true);
2182
2183                                 window.setTimeout(function() {
2184                                         feed_precache_timeout_id = false;
2185                                         }, 3000);
2186
2187                         }, 1000);
2188                 }
2189
2190         } catch (e) {
2191                 exception_error("precache_headlines", e);
2192         }
2193 }