]> git.wh0rd.org Git - tt-rss.git/blob - offline.js
offline: tweak syncing
[tt-rss.git] / offline.js
1 var SCHEMA_VERSION = 10;
2
3 var offline_mode = false;
4 var store = false;
5 var localServer = false;
6 var db = false;
7 var articles_synced = 0;
8 var sync_in_progress = false;
9 var sync_timer = false;
10
11 function view_offline(id, feed_id) {
12         try {
13
14                 enableHotkeys();
15                 showArticleInHeadlines(id);
16
17                 db.execute("UPDATE articles SET unread = 0 WHERE id = ?", [id]);
18
19                 var rs = db.execute("SELECT * FROM articles WHERE id = ?", [id]);
20
21                 if (rs.isValidRow()) {
22
23                         var tmp = "<div class=\"postReply\">";
24
25                         tmp += "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\" "+
26                                 "onmouseout=\"enable_resize(false)\">";
27
28                         tmp += "<div class=\"postDate\">"+rs.fieldByName("updated")+"</div>";
29
30                         if (rs.fieldByName("link") != "") {
31                                 tmp += "<div clear='both'><a target=\"_blank\" "+
32                                         "href=\"" + rs.fieldByName("link") + "\">" +
33                                         rs.fieldByName("title") + "</a></div>";
34                         } else {
35                                 tmp += "<div clear='both'>" + rs.fieldByName("title") + "</div>";
36                         }
37
38 /*                      tmp += "<div style='float : right'> "+
39                                 "<img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
40                         tmp += rs.fieldByName("tags");
41                         tmp += "</div>"; */
42
43 /*                      tmp += "<div clear='both'>"+
44                                 "<a target=\"_blank\" "+
45                                         "href=\"" + rs.fieldByName("comments") + "\">" +
46                                         __("comments") + "</a></div>"; */
47
48                         tmp += "</div>";
49
50                         tmp += "<div class=\"postContent\">"
51                         tmp += rs.fieldByName("content");
52                         tmp += "</div>";
53
54                         tmp += "</div>";
55
56                         render_article(tmp);
57                         update_local_feedlist_counters();
58                 }
59
60                 rs.close();
61
62                 return false;
63
64         } catch (e) {
65                 exception_error("view_offline", e);
66         }
67 }
68
69 function viewfeed_offline(feed_id, subop, is_cat, subop_param, skip_history, offset) {
70         try {
71                 notify('');
72
73                 if (!offset) offset = 0;
74
75                 if (offset > 0) {
76                         _feed_cur_page = parseInt(offset);
77                         if (_infscroll_request_sent) {
78                                 return;
79                         }
80                 } else {
81                         _feed_cur_page = 0;
82                         _infscroll_disable = 0;
83                 }
84
85                 if (getActiveFeedId() != feed_id) {
86                         _feed_cur_page = 0;
87                         active_post_id = 0;
88                         _infscroll_disable = 0;
89                 }
90
91                 loading_set_progress(100);
92
93                 clean_feed_selections();
94         
95                 setActiveFeedId(feed_id, is_cat);
96
97                 if (!is_cat) {
98                         var feedr = $("FEEDR-" + feed_id);
99                         if (feedr && !feedr.className.match("Selected")) {      
100                                 feedr.className = feedr.className + "Selected";
101                         } 
102                 } else {
103                         var feedr = $("FCAT-" + feed_id);
104                         if (feedr && !feedr.className.match("Selected")) {      
105                                 feedr.className = feedr.className + "Selected";
106                         } 
107                 }
108
109                 if (subop == "MarkAllRead") {
110                         catchup_local_feed(feed_id, is_cat);
111                 }
112
113                 disableContainerChildren("headlinesToolbar", false);
114                 Form.enable("main_toolbar_form");
115
116                 var f = $("headlines-frame");
117                 try {
118                         if (reply.offset == 0) { 
119                                 debug("resetting headlines scrollTop");
120                                 f.scrollTop = 0; 
121                         }
122                 } catch (e) { };
123
124
125                 var tmp = "";
126                 var feed_title = "";
127
128                 if (is_cat) {
129                         feed_title = get_local_category_title(feed_id);
130                 } else {                
131                         feed_title = get_local_feed_title(feed_id);
132                 }
133
134                 if (feed_title) {
135
136                         if (offset == 0) {
137                                 tmp += "<div id=\"headlinesContainer\">";
138                 
139                                 tmp += "<div class=\"headlinesSubToolbar\">";
140                                 tmp += "<div id=\"subtoolbar_ftitle\">";
141                                 tmp += feed_title;
142                                 tmp += "</div>";
143
144                                 var sel_all_link;
145                                 var sel_unread_link;
146                                 var sel_none_link;
147                                 var sel_inv_link;
148
149                                 var catchup_feed_link = "javascript:catchupCurrentFeed()";
150                                 var catchup_sel_link = "javascript:catchupSelection()";
151
152                                 var tog_unread_link;
153                                 var tog_marked_link;
154
155                                 if ($("content-frame")) {
156                                         sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
157                                         sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
158                                         sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
159                                         sel_inv_link = "javascript:invertHeadlineSelection()";
160
161                                         tog_unread_link = "javascript:selectionToggleUnread()";
162                                         tog_marked_link = "javascript:selectionToggleMarked()";
163
164                                 } else {
165                                         sel_all_link = "javascript:cdmSelectArticles('all')";
166                                         sel_unread_link = "javascript:cdmSelectArticles('unread')";
167                                         sel_none_link = "javascript:cdmSelectArticles('none')";
168                                         sel_inv_link = "javascript:invertHeadlineSelection()";
169
170                                         tog_unread_link = "javascript:selectionToggleUnread(true)";
171                                         tog_marked_link = "javascript:selectionToggleMarked(true)";
172                                 }
173
174                                 tmp += __('Select:')+
175                                         " <a href=\""+sel_all_link+"\">"+__('All')+"</a>, "+
176                                         "<a href=\""+sel_unread_link+"\">"+__('Unread')+"</a>, "+
177                                         "<a href=\""+sel_inv_link+"\">"+__('Invert')+"</a>, "+
178                                         "<a href=\""+sel_none_link+"\">"+__('None')+"</a>";
179         
180                                 tmp += "&nbsp;&nbsp;";
181         
182                                 tmp += "<span onmouseover=\"enable_selection(false)\" "+
183                                         "onmouseout=\"enable_selection(true) \"" +
184                                         "onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">" +
185                                         __("Actions...") + "&nbsp;&nbsp;<img src=\"images/down_arrow.png\">" +
186                                 "</span>";
187
188                                 tmp += "<ul id=\"headlineActionsBody\" style=\"display : none\">";
189
190                                 tmp += "<li class=\"insensitive\">"+__('Selection toggle:')+"</li>"+
191                                 "<li onclick=\""+tog_unread_link+"\">&nbsp;&nbsp;"+__('Unread')+"</li>"+
192                                 "<li onclick=\""+tog_marked_link+"\">&nbsp;&nbsp;"+__('Starred')+"</li>"+
193                                 "<li class=\"insensitive\">"+__('Mark as read:')+"</li>"+
194                                 "<li onclick=\""+catchup_sel_link+"\">&nbsp;&nbsp;"+__('Selection')+"</li>";
195
196                                 tmp += "<li onclick=\""+catchup_feed_link+"\">&nbsp;&nbsp;"+__('Entire feed')+
197                                         "</li>";
198
199                                 tmp += "</ul>";
200
201                                 tmp += "</div>";
202         
203                                 tmp += "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
204                                 if ($("content-frame")) {
205                                         tmp += "<table class=\"headlinesList\" id=\"headlinesList\" cellspacing=\"0\">";
206                                 }
207                         
208                         }
209         
210                         var limit = 30;
211                 
212                         var toolbar_form = document.forms["main_toolbar_form"];
213                         
214                         var limit = toolbar_form.limit[toolbar_form.limit.selectedIndex].value;
215                         var view_mode = toolbar_form.view_mode[toolbar_form.view_mode.selectedIndex].value;
216
217                         var limit_qpart = "";
218                         var strategy_qpart = "";
219                         var mode_qpart = "";
220                         var offset_qpart = "";
221
222                         if (limit != 0) {
223                                 limit_qpart = "LIMIT " + limit;
224                         }
225
226                         if (view_mode == "all_articles") {
227                                 mode_qpart = "1";
228                         } else if (view_mode == "adaptive") {
229                                 if (is_cat && get_local_category_unread(feed_id) ||
230                                         get_local_feed_unread(feed_id) > 0) {
231                                                 mode_qpart = "unread = 1";
232                                 } else {
233                                         mode_qpart = "1";
234                                 }
235                                 
236                         } else if (view_mode == "marked") {
237                                 mode_qpart = "marked = 1";
238                         } else if (view_mode == "unread") {
239                                 mode_qpart = "unread = 1";
240                         } else {
241                                 mode_qpart = "1";
242                         }
243
244                         var ext_tables_qpart = "";
245
246                         if (is_cat) {
247                                 if (feed_id >= 0) {
248                                         strategy_qpart = "cat_id = " + feed_id;
249                                 } else if (feed_id == -2) {
250                                         strategy_qpart = "article_labels.id = articles.id";
251                                         ext_tables_qpart = ",article_labels";
252                                 }
253                         } else if (feed_id > 0) {
254                                 strategy_qpart = "feed_id = " + feed_id;
255                         } else if (feed_id == -1) {
256                                 strategy_qpart = "marked = 1";
257                         } else if (feed_id == -4) {
258                                 strategy_qpart = "1";
259                         } else if (feed_id < -10) {
260                                 var label_id = -11 - feed_id;
261                                 strategy_qpart = "article_labels.id = articles.id AND label_id = " + label_id;
262                                 ext_tables_qpart = ",article_labels";
263                         }
264
265                         if (offset > 0) {
266                                 offset_qpart = "OFFSET " + (offset*30);
267                         } else {
268                                 offset_qpart = "";
269                         }
270
271                         var query = "SELECT *,feeds.title AS feed_title "+
272                                 "FROM articles,feeds,categories"+ext_tables_qpart+" "+
273                                 "WHERE " +
274                                 "cat_id = categories.id AND " +
275                                 "feed_id = feeds.id AND " +
276                                 strategy_qpart +
277                                 " AND " + mode_qpart + 
278                                 " ORDER BY updated DESC "+
279                                 limit_qpart + " " +
280                                 offset_qpart;
281
282                         var rs = db.execute(query);
283
284                         var line_num = offset*30;
285
286                         var real_feed_id = feed_id;
287
288                         while (rs.isValidRow()) {
289
290                                 var id = rs.fieldByName("id");
291                                 var feed_id = rs.fieldByName("feed_id");
292
293                                 var entry_feed_title = false;
294
295                                 if (real_feed_id < 0 || is_cat) {
296                                         entry_feed_title = rs.fieldByName("feed_title");
297                                 }
298
299                                 var marked_pic;
300         
301                                 var row_class = (line_num % 2) ? "even" : "odd";
302
303                                 if (rs.fieldByName("unread") == "1") {
304                                         row_class += "Unread";
305                                 }
306
307                                 var labels = get_local_article_labels(id);
308
309                                 var labels_str = "<span id=\"HLLCTR-"+id+"\">";
310                                 labels_str += format_article_labels(labels, id);
311                                 labels_str += "</span>";
312
313                                 if (rs.fieldByName("marked") == "1") {
314                                         marked_pic = "<img id=\"FMPIC-"+id+"\" "+
315                                                 "src=\"images/mark_set.png\" class=\"markedPic\""+
316                                                 "alt=\"Unstar article\" onclick='javascript:tMark("+id+")'>";
317                                 } else {
318                                         marked_pic = "<img id=\"FMPIC-"+id+"\" "+
319                                                 "src=\"images/mark_unset.png\" class=\"markedPic\""+
320                                                 "alt=\"Star article\" onclick='javascript:tMark("+id+")'>";
321                                 }
322
323                                 var mouseover_attrs = "onmouseover='postMouseIn($id)' "+
324                                         "onmouseout='postMouseOut($id)'";
325
326                                 var content_preview = truncate_string(strip_tags(rs.fieldByName("content")), 
327                                                 100);
328         
329                                 if ($("content-frame")) {
330
331                                         tmp += "<tr class='"+row_class+"' id='RROW-"+id+"' "+mouseover_attrs+">";
332                                         
333                                         tmp += "<td class='hlUpdPic'> </td>";
334         
335                                         tmp += "<td class='hlSelectRow'>"+
336                                                 "<input type=\"checkbox\" onclick=\"tSR(this)\" id=\"RCHK-"+id+"\"></td>";
337                                         
338                                         tmp += "<td class='hlMarkedPic'>"+marked_pic+"</td>";
339                 
340                                         tmp += "<td onclick='view("+id+","+feed_id+")' "+
341                                                 "class='hlContent' valign='middle'>";
342                 
343                                         tmp += "<a target=\"_blank\" id=\"RTITLE-"+id+"\" href=\"" + 
344                                                 rs.fieldByName("link") + "\"" +
345                                                 "onclick=\"return view("+id+","+feed_id+");\">"+
346                                                 rs.fieldByName("title");
347         
348                                         tmp += "<span class=\"contentPreview\"> - "+content_preview+"</span>";
349         
350                                         tmp += "</a>";
351
352                                         tmp += labels_str;
353
354                                         if (entry_feed_title) {
355                                                 tmp += " <span class=\"hlFeed\">"+
356                                                         "(<a href='javascript:viewfeed("+feed_id+
357                                                         ")'>"+entry_feed_title+"</a>)</span>";
358                                         }
359
360                                         tmp += "</td>";
361
362                                         tmp += "<td class=\"hlUpdated\" onclick='view("+id+","+feed_id+")'>"+
363                                                 "<nobr>"+rs.fieldByName("updated").substring(0,16)+
364                                                 "</nobr></td>";
365         
366                                         tmp += "</tr>";
367                                 } else {
368
369                                         var add_class = "";
370
371                                         if (rs.fieldByName("unread") == "1") {
372                                                 add_class = "Unread";                                   
373                                         }
374                                 
375                                         tmp += "<div class=\"cdmArticle"+add_class+"\" id=\"RROW-"+id+"\" "+
376                                                 mouseover_attrs+"'>";
377
378                                         feed_icon_img = "<img class=\"tinyFeedIcon\" src=\""+
379                                                 getInitParam("icons_url")+"/"+feed_id+".ico\" alt=\"\">";
380                                         cdm_feed_icon = "<span style=\"cursor : pointer\" "+
381                                                 "onclick=\"viewfeed("+feed_id+")\">"+feed_icon_img+"</span>";
382
383                                         tmp += "<div class=\"cdmHeader\">";
384                                         tmp += "<div class=\"articleUpdated\">"+
385                                                 rs.fieldByName("updated").substring(0,16)+
386                                                 " "+cdm_feed_icon+"</div>";
387
388                                         tmp += "<span id=\"RTITLE-"+id+"\" class=\"titleWrap\">"+
389                                                 "<a class=\"title\" onclick=\"javascript:toggleUnread("+id+", 0)\""+
390                                                 "target=\"_blank\" href=\""+rs.fieldByName("link")+
391                                                 "\">"+rs.fieldByName("title")+"</a>";
392
393                                         tmp += labels_str;
394
395                                         if (entry_feed_title) {
396                                                 tmp += "&nbsp;(<a href='javascript:viewfeed("+feed_id+
397                                                         ")'>"+entry_feed_title+"</a>)";
398                                         }
399
400                                         tmp += "</span></div>";
401
402                                         tmp += "<div class=\"cdmContent\" onclick=\"cdmClicked("+id+")\""+
403                                                 "id=\"CICD-"+id+"\">";
404                                         tmp += rs.fieldByName("content");
405                                         tmp += "<br clear='both'>"
406                                         tmp += "</div>"; 
407
408                                         tmp += "<div class=\"cdmFooter\"><span class='s0'>";
409                                         tmp += __("Select:")+
410                                                 " <input type=\"checkbox\" "+
411                                                 "onclick=\"toggleSelectRowById(this, 'RROW-"+id+"')\" "+
412                                                 "class=\"feedCheckBox\" id=\"RCHK-"+id+"\">";
413
414                                         tmp += "</span><span class='s1'>"+marked_pic+"</span> ";
415
416 /*                                      tmp += "<span class='s1'>"+
417                                                 "<img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>"+
418                                                 "<span id=\"ATSTR-"+id+"\">"+rs.fieldByName("tags")+"</span>"+
419                                                 "</span>"; */
420
421                                         tmp += "<span class='s2'>Toggle: <a class=\"cdmToggleLink\""+
422                                                 "href=\"javascript:toggleUnread("+id+")\">"+
423                                                 "Unread</a></span>";
424                                         tmp += "</div>";
425
426                                         tmp += "</div>";
427                                 }
428
429                                 rs.next();
430                                 line_num++;
431                         }
432
433                         if (line_num - offset*30 < 30) {
434                                 _infscroll_disable = 1;
435                         }
436
437                         rs.close();
438         
439                         if (offset == 0) {
440                                 tmp += "</table>";
441
442                                 if (line_num - offset*30 == 0) {
443                                         tmp += "<div class='whiteBox'>" +
444                                                 __("No articles found to display.") +
445                                                 "</div>";
446                                 }
447                                 tmp += "</div></div>";
448                         }
449         
450                         if (offset == 0) {
451                                 var container = $("headlines-frame");
452                                 container.innerHTML = tmp;
453                         } else {
454                                 var ids = getSelectedArticleIds2();
455                 
456                                 var container = $("headlinesList");
457                                 container.innerHTML = container.innerHTML + tmp;
458         
459                                 for (var i = 0; i < ids.length; i++) {
460                                         markHeadline(ids[i]);
461                                 }
462                         }
463                 }
464
465                 remove_splash();
466
467                 _infscroll_request_sent = 0;
468
469         } catch (e) {
470                 exception_error("viewfeed_offline", e);
471         }
472 }
473
474 function render_offline_feedlist() {
475         try {
476                 var cats_enabled = getInitParam("enable_feed_cats") == "1";
477
478                 var tmp = "<ul class=\"feedList\" id=\"feedList\">";
479
480                 var unread = get_local_feed_unread(-4);
481
482                 global_unread = unread;
483                 updateTitle();
484
485                 if (cats_enabled) {
486                         tmp += printCategoryHeader(-1, is_local_cat_collapsed(-1), false);
487                 }
488
489                 tmp += printFeedEntry(-4, __("All articles"), "feed", unread,
490                         "images/tag.png");
491
492                 var unread = get_local_feed_unread(-1);
493
494                 tmp += printFeedEntry(-1, __("Starred articles"), "feed", unread,
495                         "images/mark_set.png");
496
497                 if (cats_enabled) {
498                         tmp += "</ul></li>";
499                 } else {
500                         tmp += "<li><hr/></li>";
501                 }
502
503                 if (cats_enabled) {
504                         tmp += printCategoryHeader(-2, is_local_cat_collapsed(-2), false);
505                 }
506
507                 var rs = db.execute("SELECT id,caption "+
508                         "FROM labels "+
509                         "ORDER BY caption");
510
511                 while (rs.isValidRow()) {
512                         var id = -11 - parseInt(rs.field(0));
513                         var caption = rs.field(1);
514                         var unread = get_local_feed_unread(id);
515
516                         tmp += printFeedEntry(id, caption, "feed", unread,
517                                 "images/label.png");
518
519                         rs.next();
520                 }
521
522                 rs.close();
523
524                 if (cats_enabled) {
525                         tmp += "</ul></li>";
526                 } else {
527                         tmp += "<li><hr/></li>";
528                 }
529
530 /*              var rs = db.execute("SELECT feeds.id,feeds.title,has_icon,COUNT(articles.id) "+
531                         "FROM feeds LEFT JOIN articles ON (feed_id = feeds.id) "+
532                         "WHERE unread = 1 OR unread IS NULL GROUP BY feeds.id "+
533                         "ORDER BY feeds.title"); */
534
535                 var order_by = "feeds.title";
536
537                 if (cats_enabled) order_by = "categories.title," + order_by;
538
539                 var rs = db.execute("SELECT "+
540                         "feeds.id,feeds.title,has_icon,cat_id,collapsed "+
541                         "FROM feeds,categories WHERE cat_id = categories.id "+
542                         "ORDER BY "+order_by);
543
544                 var tmp_cat_id = -1;
545
546                 while (rs.isValidRow()) {
547
548                         var id = rs.field(0);
549                         var title = rs.field(1);
550                         var has_icon = rs.field(2);
551                         var unread = get_local_feed_unread(id);
552                         var cat_id = rs.field(3);
553                         var cat_hidden = rs.field(4);
554
555                         if (cat_id != tmp_cat_id && cats_enabled) {
556                                 if (tmp_cat_id != -1) {
557                                         tmp += "</ul></li>";
558                                 }
559                                 tmp += printCategoryHeader(cat_id, cat_hidden, true);
560                                 tmp_cat_id = cat_id;
561                         }
562
563                         var icon = "";
564
565                         if (has_icon) {
566                                 icon = getInitParam("icons_url") + "/" + id + ".ico";
567                         }
568
569                         var feed_icon = "";
570
571                         var row_class = "feed";
572
573                         if (unread > 0) {
574                                 row_class += "Unread";
575                                 fctr_class = "feedCtrHasUnread";
576                         } else {
577                                 fctr_class = "feedCtrNoUnread";
578                         }
579
580                         tmp += printFeedEntry(id, title, "feed", unread, icon);
581
582                         rs.next();
583                 }
584
585                 rs.close();
586
587                 if (cats_enabled) {
588                         tmp += "</ul>";
589                 }
590
591                 tmp += "</ul>";
592
593                 render_feedlist(tmp);
594         } catch (e) {
595                 exception_error("render_offline_feedlist", e);
596         }
597 }
598
599 function init_offline() {
600         try {
601                 offline_mode = true;
602                 store.enabled = true;
603
604                 Element.hide("dispSwitchPrompt");
605                 Element.hide("feedBrowserPrompt");
606
607                 Element.hide("topLinksOnline");
608                 Element.show("topLinksOffline");
609
610                 var tb_form = $("main_toolbar_form");
611                 Element.hide(tb_form.update);
612
613                 var chooser = $("quickMenuChooser");
614                 chooser.disabled = true;
615
616                 var rs = db.execute("SELECT key, value FROM init_params");
617
618                 while (rs.isValidRow()) {
619                         init_params[rs.field(0)] = rs.field(1);
620                         rs.next();
621                 }
622
623                 rs.close();
624
625                 var rs = db.execute("SELECT COUNT(*) FROM feeds");
626
627                 var num_feeds = 0;
628
629                 if (rs.isValidRow()) {
630                         num_feeds = rs.field(0);                        
631                 }
632                 
633                 rs.close();
634
635                 if (num_feeds == 0) {
636                         remove_splash();
637                         return fatalError(0, 
638                                 __("Data for offline browsing has not been downloaded yet."));
639                 }
640
641                 render_offline_feedlist();
642                 init_second_stage();
643                 window.setTimeout("viewfeed(-4)", 50);
644
645         } catch (e) {
646                 exception_error("init_offline", e);
647         }
648 }
649
650 function offline_download_parse(stage, transport) {
651         try {
652                 if (transport.responseXML) {
653
654                         if (!sync_in_progress) return;
655
656                         var sync_ok = transport.responseXML.getElementsByTagName("sync-ok");
657
658                         if (sync_ok.length > 0) {
659                                 for (var i = 0; i < sync_ok.length; i++) {
660                                         var id = sync_ok[i].getAttribute("id");
661                                         if (id) {
662                                                 debug("synced offline info for id " + id);
663                                                 db.execute("UPDATE articles SET modified = '' WHERE id = ?", [id]);
664                                         }
665                                 }
666                         }
667
668                         if (stage == 0) {
669
670                                 $("offlineModeSyncMsg").innerHTML = __("Synchronizing feeds...");
671
672                                 var feeds = transport.responseXML.getElementsByTagName("feed");
673
674                                 if (feeds.length > 0) {
675                                         db.execute("DELETE FROM feeds");
676                                 }
677
678                                 for (var i = 0; i < feeds.length; i++) {
679                                         var id = feeds[i].getAttribute("id");
680                                         var has_icon = feeds[i].getAttribute("has_icon");
681                                         var title = feeds[i].firstChild.nodeValue;
682                                         var cat_id = feeds[i].getAttribute("cat_id");
683
684                                         db.execute("INSERT INTO feeds (id,title,has_icon,cat_id)"+
685                                                 "VALUES (?,?,?,?)",
686                                                 [id, title, has_icon, cat_id]);
687                                 }
688
689                                 $("offlineModeSyncMsg").innerHTML = __("Synchronizing categories...");
690
691                                 var cats = transport.responseXML.getElementsByTagName("category");
692
693                                 if (feeds.length > 0) {
694                                         db.execute("DELETE FROM categories");
695                                 }
696
697                                 for (var i = 0; i < cats.length; i++) {
698                                         var id = cats[i].getAttribute("id");
699                                         var collapsed = cats[i].getAttribute("collapsed");
700                                         var title = cats[i].firstChild.nodeValue;
701
702                                         db.execute("INSERT INTO categories (id,title,collapsed)"+
703                                                 "VALUES (?,?,?)",
704                                                 [id, title, collapsed]);
705                                 }
706
707                                 $("offlineModeSyncMsg").innerHTML = __("Synchronizing labels...");
708
709                                 var labels = transport.responseXML.getElementsByTagName("label");
710
711                                 if (labels.length > 0) {
712                                         db.execute("DELETE FROM labels");
713                                 }
714
715                                 for (var i = 0; i < labels.length; i++) {
716                                         var id = labels[i].getAttribute("id");
717                                         var fg_color = labels[i].getAttribute("fg_color");
718                                         var bg_color = labels[i].getAttribute("bg_color");
719                                         var caption = labels[i].firstChild.nodeValue;
720
721                                         db.execute("INSERT INTO labels (id,caption,fg_color,bg_color)"+
722                                                 "VALUES (?,?,?,?)",
723                                                 [id, caption, fg_color, bg_color]);
724                                 }
725
726                                 $("offlineModeSyncMsg").innerHTML = __("Synchronizing articles...");
727
728                                 sync_timer = window.setTimeout("update_offline_data("+(stage+1)+")", 2*1000);
729                         } else {
730
731                                 var articles = transport.responseXML.getElementsByTagName("article");
732
733                                 var limit = transport.responseXML.getElementsByTagName("limit")[0];
734
735                                 if (limit) {
736                                         limit = limit.getAttribute("value");
737                                 } else {
738                                         limit = 0;
739                                 }
740
741                                 var articles_found = 0;
742
743                                 for (var i = 0; i < articles.length; i++) {                                     
744                                         var a = eval("("+articles[i].firstChild.nodeValue+")");
745                                         articles_found++;
746                                         if (a) {
747
748                                                 db.execute("DELETE FROM articles WHERE id = ?", [a.id]);
749
750                                                 db.execute("INSERT INTO articles "+
751                                                 "(id, feed_id, title, link, guid, updated, content, "+
752                                                         "unread, marked, tags, comments) "+
753                                                 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 
754                                                         [a.id, a.feed_id, a.title, a.link, a.guid, a.updated, 
755                                                                 a.content, a.unread, a.marked, a.tags,
756                                                                 a.comments]);
757
758                                                 if (a.labels.length > 0) {
759                                                         for (var j = 0; j < a.labels.length; j++) {
760                                                                 label_local_add_article(a.id, a.labels[j][0]);
761                                                         }
762                                                 }
763
764                                         }
765                                 }
766
767                                 debug("downloaded articles: " + articles_found + " limit: " + limit);
768
769                                 articles_synced += articles_found;
770
771                                 var msg =__("Synchronizing articles (%d)...").replace("%d", articles_synced);
772
773                                 $("offlineModeSyncMsg").innerHTML = msg;
774
775                                 var has_sync_data = has_local_sync_data();
776
777                                 if (articles_found >= limit || has_sync_data) {
778                                         sync_timer = window.setTimeout("update_offline_data("+(stage+1)+")", 
779                                                 3*1000);
780                                         debug("<b>update_offline_data: done " + stage + " HSD: " + 
781                                                 has_sync_data + "</b>");
782                                 } else {
783                                         window.setTimeout("offlineDownloadStart()", 180*1000);
784                                         debug("update_offline_data: finished");
785
786                                         var pic = $("offlineModePic");
787
788                                         if (pic) { 
789                                                 pic.src = "images/offline.png";
790
791                                                 var rs = db.execute("SELECT value FROM syncdata WHERE key = 'last_online'");
792                                                 var last_sync = "";
793
794                                                 if (rs.isValidRow()) {
795                                                         last_sync = rs.field(0).substring(0,16);
796                                                 }
797                                                 rs.close();
798
799                                                 var msg = __("Last sync: %s").replace("%s", last_sync);
800
801                                                 articles_synced = 0;
802
803                                                 $("offlineModeSyncMsg").innerHTML = msg;                                        
804                                         }                        
805
806                                         offlineSyncShowHideElems(false);
807
808                                         sync_in_progress = false;
809
810                                         db.execute("DELETE FROM articles WHERE "+
811                                                 "updated < DATETIME('NOW', 'localtime', '-31 days')");
812
813                                 }
814                         }
815
816                         update_local_sync_data();
817                 
818
819 //                      notify('');
820
821                 } else {
822                         sync_in_progress = false;
823
824                         var pic = $("offlineModePic");
825
826                         if (pic) { 
827                                 pic.src = "images/offline.png";
828                                 var msg = __("Last sync: Error receiving data.");
829                                 articles_synced = 0;
830                                 $("offlineModeSyncMsg").innerHTML = msg;                                        
831                         }                        
832
833                         offlineSyncShowHideElems(false);
834                 }
835
836         } catch (e) {
837                 exception_error("offline_download_parse", e);
838         }
839 }
840
841 function update_offline_data(stage) {
842         try {
843
844                 if (!stage) stage = 0;
845
846                 if (!db || offline_mode || getInitParam("offline_enabled") != "1") return;
847
848 //              notify_progress("Updating offline data... (" + stage +")", true);
849
850                 var query = "backend.php?op=rpc&subop=download";
851                 
852                 var rs = db.execute("SELECT MAX(id), MIN(id) FROM articles");
853
854                 if (rs.isValidRow() && rs.field(0)) {
855                         var offline_dl_max_id = rs.field(0);
856                         var offline_dl_min_id = rs.field(1);
857
858                         query = query + "&cidt=" + offline_dl_max_id;
859                         query = query + "&cidb=" + offline_dl_min_id;
860
861                         if (stage > 0) stage = 1;
862                 }
863
864                 rs.close();
865
866                 debug("update_offline_data: stage " + stage);
867
868                 query = query + "&stage=" + stage;
869
870                 var to_sync = prepare_local_sync_data();
871
872                 if (to_sync != "") {
873                         to_sync = "?sync=" + param_escape(to_sync);
874                 }
875
876                 debug(query + "/" + to_sync);
877
878                 var pic = $("offlineModePic");
879
880                 if (pic) {
881                         pic.src = "images/offline-sync.gif";
882                         if (articles_synced == 0) {
883                                 $("offlineModeSyncMsg").innerHTML = __("Synchronizing...");
884                         }
885                 }
886
887                 offlineSyncShowHideElems(true);
888                 offlineUpdateStore();
889
890                 sync_in_progress = true;
891
892                 new Ajax.Request(query, {
893                         parameters: to_sync,
894                         onComplete: function(transport) { 
895                                 offline_download_parse(stage, transport);                               
896                         } });
897
898         } catch (e) {
899                 exception_error("initiate_offline_download", e);
900         }
901 }
902
903 function set_feedlist_counter(id, ctr, is_cat) {
904         try {
905
906                 var feedctr = $("FEEDCTR-" + id);
907                 var feedu = $("FEEDU-" + id);
908                 var feedr = $("FEEDR-" + id);
909
910                 if (is_cat) {
911                         var catctr = $("FCATCTR-" + id);
912                         if (catctr) {
913                                 catctr.innerHTML = "(" + ctr + ")";
914                                 if (ctr > 0) {
915                                         catctr.className = "catCtrHasUnread";
916                                 } else {
917                                         catctr.className = "catCtrNoUnread";
918                                 }
919                         }
920                 } else if (feedctr && feedu && feedr) {
921
922                         var row_needs_hl = (ctr > 0 && ctr > parseInt(feedu.innerHTML));
923
924                         feedu.innerHTML = ctr;
925
926                         if (ctr > 0) {                                  
927                                 feedctr.className = "feedCtrHasUnread";
928                                 if (!feedr.className.match("Unread")) {
929                                         var is_selected = feedr.className.match("Selected");
930         
931                                         feedr.className = feedr.className.replace("Selected", "");
932                                         feedr.className = feedr.className.replace("Unread", "");
933         
934                                         feedr.className = feedr.className + "Unread";
935         
936                                         if (is_selected) {
937                                                 feedr.className = feedr.className + "Selected";
938                                         }       
939                                         
940                                 }
941
942                                 if (row_needs_hl) { 
943                                         new Effect.Highlight(feedr, {duration: 1, startcolor: "#fff7d5",
944                                                 queue: { position:'end', scope: 'EFQ-' + id, limit: 1 } } );
945                                 }
946                         } else {
947                                 feedctr.className = "feedCtrNoUnread";
948                                 feedr.className = feedr.className.replace("Unread", "");
949                         }                       
950                 }
951
952         } catch (e) {
953                 exception_error("set_feedlist_counter", e);
954         }
955 }
956
957 function update_local_feedlist_counters() {
958         try {
959                 if (!offline_mode || !db) return;
960
961 /*              var rs = db.execute("SELECT feeds.id,COUNT(articles.id) "+
962                         "FROM feeds LEFT JOIN articles ON (feed_id = feeds.id) "+
963                         "WHERE unread = 1 OR unread IS NULL GROUP BY feeds.id "+
964                         "ORDER BY feeds.title"); */
965
966                 var rs = db.execute("SELECT id FROM feeds "+
967                         "ORDER BY title");
968
969                 while (rs.isValidRow()) {
970                         var id = rs.field(0);
971                         var ctr = get_local_feed_unread(id);
972                         set_feedlist_counter(id, ctr, false);
973                         rs.next();
974                 }
975
976                 rs.close();
977
978                 var rs = db.execute("SELECT cat_id,SUM(unread) "+
979                         "FROM articles, feeds WHERE feeds.id = feed_id GROUP BY cat_id");
980
981                 while (rs.isValidRow()) {
982                         var id = rs.field(0);
983                         var ctr = rs.field(1);
984                         set_feedlist_counter(id, ctr, true);
985                         rs.next();
986                 }
987
988                 rs.close();
989
990                 set_feedlist_counter(-2, get_local_category_unread(-2), true);
991
992                 set_feedlist_counter(-4, get_local_feed_unread(-4));
993                 set_feedlist_counter(-1, get_local_feed_unread(-1));
994
995                 var rs = db.execute("SELECT id FROM labels");
996                         
997                 while (rs.isValidRow()) {
998                         var id = -11 - rs.field(0);
999                         var ctr = get_local_feed_unread(id);
1000                         set_feedlist_counter(id, ctr, false);
1001                         rs.next();              
1002                 }
1003
1004                 rs.close();
1005
1006                 hideOrShowFeeds(getInitParam("hide_read_feeds") == 1);
1007
1008                 global_unread = get_local_feed_unread(-4);
1009                 updateTitle();
1010
1011         } catch (e) {
1012                 exception_error("update_local_feedlist_counters", e);
1013         }
1014 }
1015
1016 function get_local_feed_unread(id) {
1017         try {
1018                 var rs;
1019
1020                 if (id == -4) {
1021                         rs = db.execute("SELECT SUM(unread) FROM articles");
1022                 } else if (id == -1) {
1023                         rs = db.execute("SELECT SUM(unread) FROM articles WHERE marked = 1");
1024                 } else if (id > 0) {
1025                         rs = db.execute("SELECT SUM(unread) FROM articles WHERE feed_id = ?", [id]);
1026                 } else if (id < -10) {
1027                         var label_id = -11 - id;
1028                         rs = db.execute("SELECT SUM(unread) FROM articles,article_labels "+
1029                                 "WHERE article_labels.id = articles.id AND label_id = ?", [label_id]);
1030                 }
1031
1032                 var a = false;
1033
1034                 if (rs.isValidRow()) {
1035                         a = rs.field(0);
1036                 } else {
1037                         a = 0;
1038                 }
1039
1040                 rs.close();
1041
1042                 return a;
1043
1044         } catch (e) {
1045                 exception_error("get_local_feed_unread", e);
1046         }
1047 }
1048
1049 function enable_offline_reading() {
1050         try {
1051
1052                 if (db && getInitParam("offline_enabled") == "1") {
1053                         init_local_sync_data();
1054                         Element.show("offlineModePic");
1055                         offlineDownloadStart();
1056                 }
1057
1058         } catch (e) {
1059                 exception_error("enable_offline_reading", e);
1060         }
1061 }
1062
1063 function init_gears() {
1064         try {
1065
1066                 if (window.google && google.gears) {
1067
1068                         try {
1069                                 localServer = google.gears.factory.create("beta.localserver");
1070                         } catch (e) {
1071                                 return;
1072                         }
1073
1074                         store = localServer.createManagedStore("tt-rss");
1075                         store.manifestUrl = "manifest.json.php";
1076                         store.enabled = false;
1077
1078                         db = google.gears.factory.create('beta.database');
1079                         db.open('tt-rss');
1080
1081                         db.execute("CREATE TABLE IF NOT EXISTS version (schema_version text)");
1082
1083                         var rs = db.execute("SELECT schema_version FROM version");
1084
1085                         var version = "";
1086
1087                         if (rs.isValidRow()) {
1088                                 version = rs.field(0);
1089                         }
1090
1091                         rs.close();
1092
1093                         if (version != SCHEMA_VERSION) {
1094                                 db.execute("DROP TABLE IF EXISTS init_params");
1095                                 db.execute("DROP TABLE IF EXISTS cache");
1096                                 db.execute("DROP TABLE IF EXISTS feeds");
1097                                 db.execute("DROP TABLE IF EXISTS categories");
1098                                 db.execute("DROP TABLE IF EXISTS labels");
1099                                 db.execute("DROP TABLE IF EXISTS article_labels");
1100                                 db.execute("DROP TABLE IF EXISTS articles");
1101                                 db.execute("DROP INDEX IF EXISTS article_labels_label_id_idx");
1102                                 db.execute("DROP INDEX IF EXISTS articles_unread_idx");
1103                                 db.execute("DROP INDEX IF EXISTS articles_feed_id_idx");
1104                                 db.execute("DROP INDEX IF EXISTS articles_id_idx");
1105                                 db.execute("DROP INDEX IF EXISTS article_labels_id_idx");
1106                                 db.execute("DROP TABLE IF EXISTS version");
1107                                 db.execute("DROP TRIGGER IF EXISTS articles_update_unread");
1108                                 db.execute("DROP TRIGGER IF EXISTS articles_update_marked");
1109                                 db.execute("DROP TRIGGER IF EXISTS articles_remove_labelrefs");
1110                                 db.execute("CREATE TABLE IF NOT EXISTS version (schema_version text)");
1111                                 db.execute("DROP TABLE IF EXISTS syncdata");
1112                                 db.execute("INSERT INTO version (schema_version) VALUES (?)", 
1113                                         [SCHEMA_VERSION]);
1114                         }
1115
1116                         db.execute("CREATE TABLE IF NOT EXISTS init_params (key text, value text)");
1117
1118                         db.execute("CREATE TABLE IF NOT EXISTS cache (id integer, article text, param text, added text)");
1119                         db.execute("CREATE TABLE IF NOT EXISTS feeds (id integer, title text, has_icon integer, cat_id integer)");
1120                         db.execute("CREATE TABLE IF NOT EXISTS categories (id integer, title text, collapsed integer)");
1121                         db.execute("CREATE TABLE IF NOT EXISTS labels (id integer, caption text, fg_color text, bg_color text)");
1122                         db.execute("CREATE TABLE IF NOT EXISTS article_labels (id integer, label_id integer)");
1123                         db.execute("CREATE TABLE IF NOT EXISTS articles (id integer, feed_id integer, title text, link text, guid text, updated timestamp, content text, tags text, unread integer, marked integer, added text, modified timestamp, comments text)");
1124         
1125                         db.execute("CREATE INDEX IF NOT EXISTS articles_unread_idx ON articles(unread)");
1126                         db.execute("CREATE INDEX IF NOT EXISTS article_labels_label_id_idx ON article_labels(label_id)");
1127                         db.execute("CREATE INDEX IF NOT EXISTS articles_feed_id_idx ON articles(feed_id)");
1128                         db.execute("CREATE INDEX IF NOT EXISTS articles_id_idx ON articles(id)");
1129                         db.execute("CREATE INDEX IF NOT EXISTS article_labels_id_idx ON article_labels(id)");
1130
1131                         db.execute("CREATE TABLE IF NOT EXISTS syncdata (key integer, value text)");
1132
1133                         db.execute("DELETE FROM cache WHERE id LIKE 'F:%' OR id LIKE 'C:%'");
1134
1135                         db.execute("CREATE TRIGGER IF NOT EXISTS articles_update_unread "+
1136                                 "UPDATE OF unread ON articles "+
1137                                 "BEGIN "+
1138                                 "UPDATE articles SET modified = DATETIME('NOW', 'localtime') "+
1139                                 "WHERE id = OLD.id AND "+
1140                                 "OLD.unread != NEW.unread;"+
1141                                 "END;");
1142
1143                         db.execute("CREATE TRIGGER IF NOT EXISTS articles_update_marked "+
1144                                 "UPDATE OF marked ON articles "+
1145                                 "BEGIN "+
1146                                 "UPDATE articles SET modified = DATETIME('NOW', 'localtime') "+
1147                                 "WHERE id = OLD.id;"+
1148                                 "END;");
1149
1150                         db.execute("CREATE TRIGGER IF NOT EXISTS articles_remove_labelrefs "+
1151                                 "DELETE ON articles "+
1152                                 "BEGIN "+
1153                                 "DELETE FROM article_labels WHERE id = OLD.id; "+
1154                                 "END; ");
1155
1156                 }       
1157         
1158                 cache_expire();
1159
1160         } catch (e) {
1161                 exception_error("init_gears", e);
1162         }
1163 }
1164
1165 function offlineArticlesStored() {
1166
1167         var rs = db.execute("SELECT COUNT(*) FROM articles");
1168         var count = 0;
1169         if (rs.isValidRow()) {
1170                 count = rs.field(0);
1171         }
1172
1173         rs.close();
1174
1175         return count;
1176 }
1177
1178 function gotoOffline() {
1179
1180 //      debug("[Local store] currentVersion = " + store.currentVersion);
1181
1182
1183         if (offlineArticlesStored() == 0) {
1184                 notify_error("You have to synchronize some articles before going into offline mode.");
1185                 return;
1186         }
1187
1188         if (confirm(__("Switch Tiny Tiny RSS into offline mode?"))) {
1189
1190                 store.enabled = true;
1191                 store.checkForUpdate();
1192         
1193                 notify_progress("Preparing offline mode...", true);
1194         
1195                 var timerId = window.setInterval(function() {
1196                         if (store.currentVersion) {
1197                                 window.clearInterval(timerId);
1198                                 debug("[Local store] sync complete: " + store.currentVersion);
1199
1200                                 //window.location.href = "tt-rss.php";
1201
1202                                 offlineDownloadStop();
1203                                 init_offline();
1204
1205                                 notify_info("Tiny Tiny RSS is in offline mode.");
1206
1207                         } else if (store.updateStatus == 3) {
1208                                 debug("[Local store] sync error: " + store.lastErrorMessage);
1209                                 notify_error(store.lastErrorMessage, true);
1210                         } }, 500);
1211         }
1212 }
1213
1214 function gotoOnline() {
1215 //      if (confirm(__("You won't be able to access offline version of Tiny Tiny RSS until you switch it into offline mode again. Go online?"))) {
1216         if (confirm(__("Tiny Tiny RSS will reload. Go online?"))) {
1217                 //localServer.removeManagedStore("tt-rss");
1218                 window.location.href = "tt-rss.php";
1219         }
1220 }
1221
1222 function local_collapse_cat(id) {
1223         try {
1224                 if (db) {
1225                         db.execute("UPDATE categories SET collapsed = NOT collapsed WHERE id = ?",
1226                                 [id]);
1227                 }       
1228         } catch (e) {
1229                 exception_error("local_collapse_cat", e);
1230         }
1231 }
1232
1233 function get_local_category_title(id) {
1234         try {
1235         
1236                 var rs = db.execute("SELECT title FROM categories WHERE id = ?", [id]);
1237                 var tmp = "";
1238
1239                 if (rs.isValidRow()) {
1240                         tmp = rs.field(0);
1241                 }
1242
1243                 rs.close();
1244
1245                 return tmp;
1246
1247         } catch (e) {
1248                 exception_error("get_local_category_title", e);
1249         }
1250 }
1251
1252 function get_local_category_unread(id) {
1253         try {
1254                 var rs = false;
1255
1256                 if (id >= 0) {
1257                         rs = db.execute("SELECT SUM(unread) FROM articles, feeds "+
1258                                 "WHERE feeds.id = feed_id AND cat_id = ?", [id]);
1259                 } else if (id == -2) {
1260                         rs = db.execute("SELECT SUM(unread) FROM article_labels, articles "+
1261                                 "where article_labels.id = articles.id");
1262                 } else {
1263                         return 0;
1264                 }
1265
1266                 var tmp = 0;
1267
1268                 if (rs.isValidRow()) {
1269                         tmp = rs.field(0);
1270                 }
1271
1272                 rs.close();
1273
1274                 return tmp;
1275
1276         } catch (e) {
1277                 exception_error("get_local_category_unread", e);
1278         }
1279 }
1280
1281 function printCategoryHeader(cat_id, hidden, can_browse) {
1282         try {
1283                 if (hidden == undefined) hidden = false;
1284                 if (can_browse == undefined) can_browse = false;
1285
1286                         var tmp_category = get_local_category_title(cat_id);
1287                         var tmp = "";
1288
1289                         var cat_unread = get_local_category_unread(cat_id);
1290
1291                         var holder_style = "";
1292                         var ellipsis = "";
1293
1294                         if (hidden) {
1295                                 holder_style = "display:none;";
1296                                 ellipsis = "…";
1297                         }
1298
1299                         var catctr_class = (cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
1300
1301                         var browse_cat_link = "";
1302                         var inner_title_class = "catTitleNL";
1303
1304                         if (can_browse) {
1305                                 browse_cat_link = "onclick=\"javascript:viewCategory("+cat_id+")\"";
1306                                 inner_title_class = "catTitle";
1307                         }
1308
1309                         var cat_class = "feedCat";
1310
1311                         tmp += "<li class=\""+cat_class+"\" id=\"FCAT-"+cat_id+"\">"+
1312                                 "<img onclick=\"toggleCollapseCat("+cat_id+")\" class=\"catCollapse\""+
1313                                         " title=\""+__('Click to collapse category')+"\""+
1314                                         " src=\"images/cat-collapse.png\"><span class=\""+inner_title_class+"\" "+
1315                                         " id=\"FCATN-"+cat_id+"\" "+browse_cat_link+
1316                                 "\">"+tmp_category+"</span>";
1317
1318                         tmp += "<span id=\"FCAP-"+cat_id+"\">";
1319
1320                         tmp += " <span id=\"FCATCTR-"+cat_id+"\" "+
1321                                 "class=\""+catctr_class+"\">("+cat_unread+")</span> "+ellipsis;
1322
1323                         tmp += "</span>";
1324
1325                         tmp += "<ul class=\"feedCatList\" id=\"FCATLIST-"+cat_id+"\" "+
1326                                 "style='"+holder_style+"'>";
1327
1328                         return tmp;
1329         } catch (e) {
1330                 exception_error("printCategoryHeader", e);
1331         }
1332 }
1333
1334 function is_local_cat_collapsed(id) {
1335         try {
1336
1337                 var rs = db.execute("SELECT collapsed FROM categories WHERE id = ?", [id]);
1338                 var cat_hidden = 0;
1339
1340                 if (rs.isValidRow()) {
1341                         cat_hidden = rs.field(0);
1342                 }
1343
1344                 rs.close();
1345
1346                 return cat_hidden == "1";
1347
1348         } catch (e) {
1349                 exception_error("is_local_cat_collapsed", e);
1350         }
1351 }
1352
1353 function get_local_article_labels(id) {
1354         try {
1355                 var rs = db.execute("SELECT DISTINCT label_id,caption,fg_color,bg_color "+
1356                         "FROM labels, article_labels "+
1357                         "WHERE labels.id = label_id AND article_labels.id = ?", [id]);
1358
1359                 var tmp = new Array();
1360
1361                 while (rs.isValidRow()) {
1362                         var e = new Array();
1363
1364                         e[0] = rs.field(0);
1365                         e[1] = rs.field(1);
1366                         e[2] = rs.field(2);
1367                         e[3] = rs.field(3);
1368
1369                         tmp.push(e);
1370
1371                         rs.next();
1372                 }
1373
1374                 return tmp;
1375
1376         } catch (e) {
1377                 exception_error("get_local_article_labels", e);
1378         }
1379 }
1380
1381 function label_local_add_article(id, label_id) {
1382         try {
1383                 //debug("label_local_add_article " + id + " => " + label_id);
1384
1385                 var rs = db.execute("SELECT COUNT(id) FROM article_labels WHERE "+
1386                         "id = ? AND label_id = ?", [id, label_id]);
1387                 var check = rs.field(0);
1388
1389                 if (rs.isValidRow()) {
1390                         var check = rs.field(0);
1391                 }
1392                 rs.close();
1393
1394                 if (check == 0) {
1395                         db.execute("INSERT INTO article_labels (id, label_id) VALUES "+
1396                                 "(?,?)", [id, label_id]);
1397                 }
1398
1399         } catch (e) {
1400                 exception_error("label_local_add_article", e);
1401         }
1402 }
1403
1404 function get_local_feed_title(id) {
1405         try {
1406
1407                 var feed_title = "Unknown feed: " + id;
1408
1409                 if (id > 0) {
1410                         var rs = db.execute("SELECT title FROM feeds WHERE id = ?", [id]);
1411
1412                         if (rs.isValidRow()) {
1413                                 feed_title = rs.field(0);
1414                         }
1415
1416                         rs.close();
1417                 } else if (id == -1) {
1418                         feed_title = __("Starred articles");
1419                 } else if (id == -4) {
1420                         feed_title = __("All articles");
1421                 } else if (id < -10) {
1422                         
1423                         var label_id = -11 - id;
1424                                 
1425                         var rs = db.execute("SELECT caption FROM labels WHERE id = ?", [label_id]);
1426
1427                         if (rs.isValidRow()) {
1428                                 feed_title = rs.field(0);
1429                         }
1430
1431                         rs.close();
1432                 }
1433
1434                 return feed_title;
1435
1436         } catch (e) {
1437                 exception_error("get_local_feed_title", e);
1438         }
1439 }
1440
1441 function format_article_labels(labels, id) {
1442         try {
1443
1444                 var labels_str = "";
1445
1446                 if (!labels) return "";
1447
1448                 for (var i = 0; i < labels.length; i++) {
1449                         var l = labels[i];
1450
1451                         labels_str += "<span class='hlLabelRef' "+
1452                                 "style='color : "+l[2]+"; background-color : "+l[3]+"'>"+l[1]+"</span>";
1453                 }
1454
1455                 return labels_str;
1456
1457         } catch (e) {
1458                 exception_error("format_article_labels", e);
1459         }
1460 }
1461
1462 function init_local_sync_data() {
1463         try {
1464
1465                 if (!db) return;
1466
1467                 var rs = db.execute("SELECT COUNT(*) FROM syncdata WHERE key = 'last_online'");
1468                 var has_last_online = 0;
1469
1470                 if (rs.isValidRow()) {
1471                         has_last_online = rs.field(0);
1472                 }
1473
1474                 rs.close();
1475
1476                 if (!has_last_online) {
1477                         db.execute("INSERT INTO syncdata (key, value) VALUES ('last_online', '')");
1478                 }
1479
1480         } catch (e) {
1481                 exception_error("init_local_sync_data", e);
1482
1483         }
1484 }
1485
1486 function has_local_sync_data() {
1487         try {
1488
1489                 var rs = db.execute("SELECT id FROM articles "+
1490                         "WHERE modified > (SELECT value FROM syncdata WHERE key = 'last_online') "+
1491                         "LIMIT 1");
1492
1493                 var tmp = 0;
1494
1495                 if (rs.isValidRow()) {
1496                         tmp = rs.field(0);
1497                 }
1498
1499                 rs.close();
1500
1501                 return tmp != 0;
1502
1503         } catch (e) {
1504                 exception_error("has_local_sync_data", e);
1505         }
1506 }
1507
1508 function prepare_local_sync_data() {
1509         try {
1510                 var rs = db.execute("SELECT value FROM syncdata WHERE key = 'last_online'");
1511
1512                 var last_online = "";
1513                 
1514                 if (rs.isValidRow()) {
1515                         last_online = rs.field(0);
1516                 }
1517
1518                 rs.close();
1519
1520                 var rs = db.execute("SELECT id,unread,marked FROM articles "+
1521                         "WHERE modified > ? LIMIT 200", [last_online]);
1522
1523                 var tmp = last_online + ";";
1524
1525                 var entries = 0;
1526
1527                 while (rs.isValidRow()) {
1528                         var e = new Array();
1529
1530                         tmp = tmp + rs.field(0) + "," + rs.field(1) + "," + rs.field(2) + ";";
1531                         entries++;
1532
1533                         rs.next();
1534                 }
1535
1536                 rs.close();
1537
1538                 if (entries > 0) {
1539                         return tmp;
1540                 } else {
1541                         return '';
1542                 }
1543
1544         } catch (e) {
1545                 exception_error("prepare_local_sync_data", e);
1546         }
1547 }
1548
1549 function update_local_sync_data() {
1550         try {
1551                 if (db && !offline_mode) {
1552
1553                         var rs = db.execute("SELECT id FROM articles "+
1554                                 "WHERE modified > (SELECT value FROM syncdata WHERE "+
1555                                         "key = 'last_online') LIMIT 1")
1556
1557                         var f_id = 0;
1558
1559                         if (rs.isValidRow()) {
1560                                 f_id = rs.field(0);
1561                         }
1562
1563                         rs.close();
1564
1565                         /* no pending articles to sync */
1566
1567                         if (f_id == 0) {
1568                                 db.execute("UPDATE syncdata SET value = DATETIME('NOW', 'localtime') "+
1569                                         "WHERE key = 'last_online'");
1570                         }
1571
1572                 }
1573         } catch (e) {
1574                 exception_error("update_local_sync_data", e);
1575         }
1576 }
1577
1578 function catchup_local_feed(id, is_cat) {
1579         try {
1580                 if (!db) return;
1581
1582                 if (!is_cat) {
1583                         if (id >= 0) {
1584                                 db.execute("UPDATE articles SET unread = 0 WHERE feed_id = ?", [id]);
1585                         } else if (id == -1) {
1586                                 db.execute("UPDATE articles SET unread = 0 WHERE marked = 1");
1587                         } else if (id == -4) {
1588                                 db.execute("UPDATE articles SET unread = 0");
1589                         } else if (id < -10) {
1590                                 var label_id = -11-id;
1591
1592                                 db.execute("UPDATE articles SET unread = 0 WHERE "+
1593                                         "(SELECT COUNT(*) FROM article_labels WHERE "+
1594                                         "article_labels.id = articles.id AND label_id = ?) > 0", [label_id]);
1595                         }
1596                 }
1597
1598                 update_local_feedlist_counters();
1599
1600         } catch (e) {
1601                 exception_error("catchup_local_feed", e);
1602         }
1603 }
1604
1605 function toggleOfflineModeInfo() {
1606         try {
1607                 var e = $('offlineModeDrop');
1608                 var p = $('offlineModePic');
1609                 
1610                 if (Element.visible(e)) {
1611                         Element.hide(e);
1612                 } else {
1613                         Element.show(e);
1614                 }
1615
1616         } catch (e) {
1617                 exception_error("toggleOfflineModeInfo", e);
1618         }
1619 }
1620
1621 function offlineDownloadStart(stage) {
1622         try {
1623                 if (!stage) stage = 0;
1624
1625                 if (db && !sync_in_progress && getInitParam("offline_enabled") == "1") {
1626                         window.setTimeout("update_offline_data("+stage+")", 100);
1627                 }
1628         } catch (e) {
1629                 exception_error("offlineDownloadStart", e);
1630         }
1631 }
1632
1633 function offlineDownloadStop() {
1634         try {
1635                 if (db && sync_in_progress && getInitParam("offline_enabled") == "1") {
1636
1637                         sync_in_progress = false;
1638
1639                         if (sync_timer) {
1640                                 window.clearTimeout(sync_timer);
1641                                 sync_timer = false;
1642                         }
1643
1644                         var pic = $("offlineModePic");
1645         
1646                         if (pic) { 
1647                                 pic.src = "images/offline.png";
1648                                 var msg = __("Last sync: Cancelled.");
1649                                 articles_synced = 0;
1650                                 $("offlineModeSyncMsg").innerHTML = msg;                                        
1651                         }                        
1652
1653                         offlineSyncShowHideElems(false);
1654
1655                 }
1656         } catch (e) {
1657                 exception_error("offlineDownloadStart", e);
1658         }
1659 }
1660
1661 function offlineClearData() {
1662         try {
1663                 if (db) {
1664
1665                         if (confirm(__("This will remove all offline data stored by Tiny Tiny RSS on this computer. Continue?"))) {
1666
1667                                 notify_progress("Removing offline data...");
1668
1669                                 localServer.removeManagedStore("tt-rss");
1670
1671                                 db.execute("DELETE FROM articles");
1672                                 db.execute("DELETE FROM article_labels");
1673                                 db.execute("DELETE FROM labels");
1674                                 db.execute("DELETE FROM feeds");
1675                                 db.execute("DELETE FROM cache");
1676
1677                                 notify_info("Local data removed.");
1678                         }
1679                 }
1680         } catch (e) {
1681                 exception_error("offlineClearData", e);
1682         }
1683 }
1684
1685 function offlineUpdateStore() {
1686         try {
1687                 if (offline_mode || !store) return;
1688
1689                 store.checkForUpdate();
1690         
1691                 var timerId = window.setInterval(function() {
1692                         if (store.currentVersion) {
1693                                 window.clearInterval(timerId);
1694                                 debug("[Local store] sync complete: " + store.currentVersion);
1695                         } else if (store.updateStatus == 3) {
1696                                 debug("[Local store] sync error: " + store.lastErrorMessage);
1697                         } }, 500);
1698
1699         } catch (e) {
1700                 exception_error("offlineUpdateStore", e);
1701         }
1702 }
1703
1704 function offlineSyncShowHideElems(syncing) {
1705         try {
1706
1707                 var elems = $$("div.hideWhenSyncing");
1708         
1709                 for (var j = 0; j < elems.length; j++) {
1710                         if (syncing) {
1711                                 Element.hide(elems[j]);
1712                         } else {
1713                                 Element.show(elems[j]);
1714                         }
1715                 }
1716
1717                 var elems = $$("div.showWhenSyncing");
1718         
1719                 for (var j = 0; j < elems.length; j++) {
1720                         if (syncing) {
1721                                 Element.show(elems[j]);
1722                         } else {
1723                                 Element.hide(elems[j]);
1724                         }
1725                 }
1726
1727         } catch (e) {
1728                 exception_error("offlineSyncShowHideElems", e);
1729         }
1730 }
1731
1732 function offlineConfirmModeChange() {
1733         try {
1734                 
1735                 if (db && getInitParam("offline_enabled") == "1" && offlineArticlesStored() > 0) {
1736                         var ok = confirm(__("Tiny Tiny RSS has trouble accessing its server. Would you like to go offline?")); 
1737
1738                         if (ok) {
1739                                 init_offline();
1740                         }
1741                 }
1742
1743         } catch (e) {
1744                 exception_error("offlineConfirmModeChange", e);
1745         }
1746 }