summaryrefslogtreecommitdiff
path: root/read.html
blob: f0354226ae32091cdafab280e43e8590d2cb4140 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link href="lib/bootstrap/v3/css/bootstrap.min.css" rel="stylesheet" media="screen">
	<link href="lib/bootstrap/v3/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<script src="lib/bootstrap/v3/js/jquery.js"></script>
	<script src="lib/bootstrap/v3/js/bootstrap.min.js"></script>

	<script src="lib/promise.js"></script>
	<script src="lib/fetch.js"></script>

	<script src="lib/zip.min.js"></script>
	<script src="lib/localforage.min.js"></script>
	<script src="lib/epub.js"></script>
	<script src="js/read.js"></script>
	<script src="js/common.js"></script>

	<link id="favicon" rel="shortcut icon" type="image/png" href="img/favicon.png" />
	<link type="text/css" rel="stylesheet" media="screen" href="css/read.css" />

	<link type="text/css" rel="stylesheet" media="screen" href="themes/default.css" id="theme_css" />
</head>
<body>

<div class="modal fade" id="settings-modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Settings</h4>
      </div>
      <div class="modal-body">
			<form name="settings-form" onsubmit="return false" class="form-horizontal">

				<div class="form-group">
					<label class="col-sm-3 control-label">Font</label>
					<div class="col-sm-9">
						<select class="font_family form-control" onchange="apply_font(this)">
							<option>Arial</option>
						 	<option>Times New Roman</option>
							<option>Georgia</option>
							<option>Courier New</option>
						</select>
					</div>
  				</div>

				<div class="form-group">
					<label class="col-sm-3 control-label">Text size</label>
					<div class="col-sm-9">
						<select class="font_size form-control" onchange="apply_font_size(this)"></select>
					</div>
  				</div>

				<div class="form-group">
					<label class="col-sm-3 control-label">Line height</label>
					<div class="col-sm-9">
						<select class="line_height form-control" onchange="apply_line_height(this)"></select>
					</div>
  				</div>

				<div class="form-group">
					<label class="col-sm-3 control-label">Theme</label>
					<div class="col-sm-9">
						<select class="theme_name form-control" onchange="change_theme(this)">
							<option value="default">Default</option>
						 	<option value="gray">Gray</option>
							<option value="mocca">Mocca</option>
						 	<option value="night">Night</option>
						 	<option value="plan9">Plan9</option>
						</select>
					</div>
  				</div>

				<div class="form-group">
					<label class="col-sm-3 control-label"></label>
					<div class="col-sm-9">
						<!-- <div class="text-muted">Options take effect after reload:</div> -->

						<div class="checkbox">
							<label>
								<input class="keep_ui_checkbox"
									type="checkbox"> Keep UI when turning pages
							</label>
						</div>
					</div>
  				</div>

				<hr/>

				<div class="form-group">
					<label class="col-sm-3 control-label">Progress</label>
					<div class="col-sm-9">

						<div class="input-group">
							<input type="numeric" disabled="disabled" class="form-control lastread_input">
							<span class="input-group-btn">
								<button class="btn btn-danger" type="button" onclick="clear_lastread()">Clear</button>
							</span>
						</div>
					</div>
  				</div>

				<div class="form-group">
					<label class="col-sm-3 control-label"></label>
					<div class="col-sm-9">
						<button class="btn btn-default" type="button" onclick="open_lastread()">Open last read page</button>
						<button class="btn btn-primary" type="button" onclick="mark_as_read()">Mark as read</button>
					</div>
  				</div>

			</form>
      </div>
      <div class="modal-footer">
             <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="dict-modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Dictionary Lookup</h4>
      </div>
		<input type="hidden" class="dict_query" value=""/>
      <div class="modal-body">
			<div class="dict_result"> </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="dict_search_btn btn-default btn">Google</button>
        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="toc-modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Table of Contents</h4>
      </div>
      <div class="modal-body">
			<ul class="toc_list list-unstyled"> </ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="search-modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Search</h4>
      </div>
      <div class="modal-body">

			<form class="form-horizontal" onsubmit="return false;">
				<div class="form-group">
					<label class="col-sm-4 control-label">Search query</label>
					<div class="col-sm-8">
						<input type="search" class="form-control search_input">
					</div>
  				</div>

				<ul class="search_results list-unstyled"> </ul>

			</form>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="search()">Search</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div class="container">
<div class="header">
	<span>
		<a href="#" onclick="save_and_close()">&laquo;&nbsp;Exit</a>
		<span class="title"></span>
	</span>
	<span class="toolbar">

		<span class="prev_location_btn"
			onclick="open_previous_location(this)" style="display : none">
			<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
		</span>

		<span data-toggle="modal" data-target="#search-modal">
			<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
		</span>

		<span onclick="toggle_fullscreen()">
			<span class="glyphicon glyphicon-fullscreen" aria-hidden="true"></span>
		</span>

		<span data-toggle="modal" data-target="#settings-modal">
			<span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>
		</span>

	</span>
</div>

<div class="footer">
	<div class="chapter" data-toggle="modal" data-target="#toc-modal"></div>
	<div class="location">
		<span id="cur_page">?</span> / <span id="total_pages">?</span>
		(<span id="page_pct">?</span>)
	</div>
</div>

<div id="left"></div>
<div id="right"></div>

<div id="reader"></div>

<div class="loading">
	<div class="loading_message">
		Opening book...
	</div>
</div>
</div>

<script type='text/javascript'>
	'use strict';

	var _pagination_stored = 0;
	var _last_position_sync = 0;

	var _is_ios = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
	var _res_data = [];

	const DEFAULT_FONT_SIZE = 16;
	const DEFAULT_FONT_FAMILY = "Georgia";
	const DEFAULT_LINE_HEIGHT = 140;

	function cacheId(suffix) {
		return "epube-book." + $.urlParam("b") + (suffix ? "." + suffix : "");
	}

	$(document).ready(function() {
		if ('serviceWorker' in navigator) {
 			 navigator.serviceWorker
           .register('worker.js')
           .then(function() {
					console.log("service worker registered");

					init_loader();
				});
		}
	});

	function init_loader() {
		// we need to preload resources for reader iframe because it can't utilize our
		// service worker because while offline it is created outside our base server context
		var res_names = [ "lib/bootstrap/v3/js/jquery.js", "lib/jquery.mobile.custom.js",
			"css/transitions.css",
			"js/reader.js", "css/reader.css", "js/dict.js",
			"themes/default.css", "themes/mocca.css", "themes/night.css",
			"themes/plan9.css", "themes/gray.css" ];

		for (var i = 0; i < res_names.length; i++) {
			fetch(res_names[i], {credentials: 'same-origin'}).then(function(resp) {
				if (resp.status == 200) resp.text().then(function(data) {
					_res_data[resp.url] = data;
				});
			});
		}

		check_resource_load(res_names, _res_data, 0);
	}

	function check_resource_load(res_names, res_data, attempt) {
		console.log("check_resource_load", attempt, res_names.length, Object.keys(res_data).length);

		if (attempt == 5) {
			$(".loading_message").html("Unable to load resources.");
			return;
		}

		if (res_names.length != Object.keys(res_data).length) {
			window.setTimeout(function() {
				check_resource_load(res_names, res_data, attempt+1);
			}, 250);
		} else {
			init_reader();
		}
	}

	function init_reader() {
		apply_theme();

		$(window).on('online', function() {
			console.log("we're online, storing lastread");

			var currentCfi = book.rendition.currentLocation().start.cfi;
			var currentPage = parseInt(book.locations.percentageFromCfi(currentCfi) * 100);

			$.post("backend.php", { op: "storelastread", id: $.urlParam("id"), page: currentPage,
				cfi: currentCfi }, function(data) {

					if (data.cfi) {
						_last_position_sync = new Date().getTime()/1000;
					}
				})
				.fail(function(e) {
					if (e && e.status == 401) {
						window.location = "index.php";
					}
				});
		});

		localforage.getItem(cacheId("book")).then(function(item) {

			// ios doesn't work with FileReader for whatever reason
			if (/*!_is_ios &&*/ item) {

				console.log("loading from local storage");

				var fileReader = new FileReader();

				fileReader.onload = function(evt) {
					try {
						book.open(this.result);
					} catch (e) {
						$(".loading_message").html("Unable to load book (local).");
						console.log(e);
					}
				};

				fileReader.readAsArrayBuffer(item);

			} else {

				console.log("loading from network");

				if (navigator.onLine) {
					var book_url = "backend.php?op=download&id=" + $.urlParam("id");

					fetch(book_url, {credentials: 'same-origin'}).then(function(resp) {

						if (resp.status == 200) {
							var bookId = $.urlParam("b");

							// let's store this for later
							localforage.setItem(cacheId('book'), resp.clone().blob());

							// if there's no base information cached yet, let's do that too
							localforage.getItem(cacheId()).then(function(info) {
								if (!info) {
									$.post("backend.php", {op: "getinfo", id: bookId }, function(data) {
										if (data) {
											localforage.setItem(cacheId(), data);

											if (data.has_cover) {
												fetch("backend.php?op=cover&id=" + bookId, {credentials: 'same-origin'}).then(function(resp) {
													if (resp.status == 200) {
														localforage.setItem(cacheId('cover'), resp.blob());
													}
												});
											}
										}
									});
								}
							});

							resp.blob().then(function(blob) {

								var fileReader = new FileReader();

								fileReader.onload = function() {
									book.open(this.result);
								};

								fileReader.readAsArrayBuffer(blob);

							});
						} else {
							$(".loading_message").html("Unable to download book: " + resp.status + ".");
						}
					}).catch(function(err) {
						console.warn(err);

						if ($(".loading").is(":visible")) {
							$(".loading_message").html("Unable to load book (remote).");
						}
					});

				} else {
					$(".loading_message").html("This book is not available offline.");
				}
			}
		});

		var book = ePub();

		window.book = book;

		var rendition = book.renderTo("reader", {
			width: '100%',
			height: '100%',
			minSpreadWidth: 961
		});

		var displayed = rendition.display();

		var fontSize;
		var fontFamily;
		var lineHeight;
		var themeName;

		Promise.all([
			localforage.getItem("epube.fontSize"),
			localforage.getItem("epube.fontFamily"),
			localforage.getItem("epube.lineHeight"),
			localforage.getItem("epube.theme")
		]).then(function(res) {
			fontSize = res[0] ? res[0] + "px" : DEFAULT_FONT_SIZE + "px";
			fontFamily = res[1] ? res[1] : DEFAULT_FONT_FAMILY;
			lineHeight = res[2] ? res[2] + "%" : DEFAULT_LINE_HEIGHT + "%";
			themeName = res[3] ? res[3] : 'default';

			rendition.themes.default({
				html: {
					'font-size': fontSize,
					'font-family': fontFamily,
					'line-height': lineHeight,
					'text-align': 'justify'
				}
			});

		});

		rendition.hooks.content.register(function(contents) {

			contents.on("linkClicked", function(href) {
				console.log('linkClicked', href);

				if (href.indexOf("://") == -1) {
					$(".prev_location_btn")
						.attr("data-location-cfi", book.rendition.currentLocation().start.cfi)
						.show();

					window.setTimeout(function() {
						show_ui(true);
					}, 50);
				}

			});

			var base_url = window.location.href.match(/^.*\//)[0];
			var res_names = [ "lib/bootstrap/v3/js/jquery.js", "lib/jquery.mobile.custom.js",
				"js/reader.js", "js/dict.js" ];
			var doc = contents.document;

			for (var i = 0; i < res_names.length; i++) {

				// we need to create script element with proper context, that is inside the iframe
				var elem = doc.createElement("script");
				elem.type = 'text/javascript';
				elem.text = _res_data[base_url + res_names[i]];

				doc.head.appendChild(elem);
			}

			$(contents.document.head)
				.append($("<style type='text/css'>")
				.text(_res_data[base_url + 'css/reader.css']));

			/*localforage.getItem("epube.disable-transitions").then(function(notransitions) {
				if (!notransitions) {
					$(contents.document.head)
						.append($("<style type='text/css'>")
						.text(_res_data[base_url + 'css/transitions.css']));

					// TODO: fix transitions somehow

					EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){
			 			this.docEl.style[this.transform] = 'translate('+ (-leftPos) + 'px, 0)';
					}
				}
			}); */

			return localforage.getItem("epube.theme").then(function(theme) {

				if (!theme) theme = 'default';

				var theme_url = base_url + 'themes/' + theme + '.css';

				$(contents.document.head)
					.append($("<style type='text/css' id='theme_css'>")
					.text(_res_data[theme_url]));
			});

		});

		$('#settings-modal').on('shown.bs.modal', function() {

			localforage.getItem(cacheId("lastread")).then((item) => {
				if (item && item.cfi) {
					$(".lastread_input").val(item.page + '%');
				}

				$.post("backend.php", { op: "getlastread", id: $.urlParam("id") }, function(data) {
					$(".lastread_input").val(data.page + '%');
				});

			});

			/*localforage.getItem("epube.disable-transitions").then(function(disable) {
				$(".transition_checkbox")
					.attr("checked", disable)
					.on("click", function() {
						localforage.setItem("epube.disable-transitions", this.checked);
					});
			});*/

			localforage.getItem("epube.keep-ui-visible").then(function(keep) {
				$(".keep_ui_checkbox")
					.attr("checked", keep)
					.on("click", function() {
						localforage.setItem("epube.keep-ui-visible", this.checked);
					});
			});

			localforage.getItem("epube.fontFamily").then(function(font) {
				if (!font) font = DEFAULT_FONT_FAMILY;

				$(".font_family").val(font);
			});

			localforage.getItem("epube.theme").then(function(theme) {
				$(".theme_name").val(theme);
			});

			localforage.getItem("epube.fontSize").then(function(size) {

				if (!size) size = DEFAULT_FONT_SIZE;

				var zoom = $(".font_size").html("");

				for (var i = 10; i <= 32; i++) {
					var opt = $("<option>").val(i).html(i + " px");

					if (i == size) opt.attr("selected", "1");

					zoom.append(opt);
				}

			});

			localforage.getItem("epube.lineHeight").then(function(height) {

				if (!height) height = DEFAULT_LINE_HEIGHT;

				var zoom = $(".line_height").html("");

				for (var i = 100; i <= 220; i += 10) {
					var opt = $("<option>").val(i).html(i + "%");

					if (i == height) opt.attr("selected", "1");

					zoom.append(opt);
				}

			});
		})

		$('#dict-modal').on('shown.bs.modal', function() {
			$(".dict_result").scrollTop(0);
		})

		$(".dict_search_btn").on("click", function() {
			$("#dict-modal").modal('hide');
			window.open("https://google.com/search?q=" + $(".dict_query").val());
		});

		$('#toc-modal').on('shown.bs.modal', function() {
			function toc_loc_msg(href) {
				try {
					var cfiBase = book.spine.get(href).cfiBase;

					var loc = book.locations._locations.find(function(k) {
						return k.indexOf(cfiBase) != -1
						});

					return window.book.locations.locationFromCfi(loc);

				} catch (e) {
					console.warn(e);
				}

				return "";
			}

			function process_toc_sublist(row, list, nest) {

				if (nest == 3) return false;

				if (row.subitems) {

					var sublist = $("<ul class='toc_sublist list-unstyled'>");

					$.each(row.subitems, function(i, row) {

						var a = $("<a>")
							.attr('href', '#')
							.html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
							.attr('data-href', row.href)
							.click(function() {
								book.rendition.display(a.attr('data-href'));
							});

						sublist.append($("<li>").append(a));

						process_toc_sublist(row, sublist, nest + 1);

					});

					list.append(sublist);
				}
			}

				var toc = book.navigation.toc;

				var list = $(".toc_list");
				list.html("");

				$.each(toc, function(i, row) {

					// if anything fails here the toc entry is likely useless anyway (i.e. no cfi)
					try {
						var a = $("<a>")
							.attr('href', '#')
							.html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
							.attr('data-href', row.href)
							.click(function() {
								book.rendition.display(a.attr('data-href'));
							});

						list.append($("<li>").append(a));

						process_toc_sublist(row, list, 0);

					} catch (e) {
						console.warn(e);
					}
				});

				// well the toc didn't work out, might as well generate one
				if (list.children().length <= 1) {

					list.html("");

					$.each(book.spine.items, function (i, row) {

						var a = $("<a>")
							.attr('href', '#')
							.attr('title', row.url)
							.html("Section " + (i+1))
							.attr('data-href', row.href)
							.click(function() {
								book.rendition.display(a.attr('data-href'));
							});

						list.append($("<li>").append(a));

					});
				}

			});

		book.ready.then(function() {

			var meta = book.package.metadata;

			document.title = meta.title + " – " + meta.creator;
			$(".title").html("<b>" + meta.title + "</b> - " + meta.creator);

			return localforage.getItem(cacheId("locations")).then(function(locations) {

				// legacy format is array of objects {cfi: ..., page: ...}
				if (locations && typeof locations[0] == "string") {
					_pagination_stored = 1;
					return book.locations.load(locations);
				} else {
					var url = "backend.php?op=getpagination&id=" + encodeURIComponent($.urlParam("id"));

					return fetch(url, {credentials:'same-origin'}).then(function(resp) {

						if (resp.ok) {
							return resp.json().then(function(locations) {
								if (locations && typeof locations[0] == "string") {
									_pagination_stored = 1;
									return book.locations.load(locations);
								} else {
									return book.locations.generate(1600);
								}
							});
						} else {
							return book.locations.generate(1600);
						}
					}).catch(function() {
						return book.locations.generate(1600);
					});
				}

			});

		}).then(function(locations) {

			if (locations && !_pagination_stored) {
				if (navigator.onLine) {
					$.post("backend.php", { op: "storepagination", id: $.urlParam("id"),
						payload: JSON.stringify(locations), total: 100});
				}

				localforage.setItem(cacheId("locations"), locations);

			}

			$(".location").click(function() {
				var current = book.rendition.currentLocation().start.location;
				var total = book.locations.length();

				var page = prompt("Jump to location [1-" + total + "]", current);

				if (page) {
					book.rendition.display(book.locations._locations[page]);
				}
			});

			open_lastread();

			window.setTimeout(function() {
				open_lastread();

				$(".loading").hide();
			}, 250);
		});

		rendition.on("keyup", hotkey_handler);

		rendition.on('resized', function() {
			console.log('resized');

			$(".loading").show();
			$(".loading_message").html("Opening chapter...");

			window.setTimeout(function() {
				open_lastread();

				$(".loading").hide();
			}, 250);
		});

		rendition.on('rendered', function(chapter) {
			$(".chapter").html($("<span>").addClass("glyphicon glyphicon-th-list"));

			resize_side_columns();

			try {
				var location = book.rendition.currentLocation();

				if (location.start) {
					var cur_href = book.canonical(location.start.href);
					var toc_entry = false;

					function iterate_sublist(row, nest) {
						if (nest == 3) return false;

						if (row.subitems) {
							$.each(row.subitems, function (i, r) {

								if (book.spine.get(r.href).canonical == cur_href) {
									toc_entry = r;
									return true;
								}

								if (iterate_sublist(r, nest + 1))
									return true;
							});
						}

						return false;
					}

					$.each(book.navigation.toc, function(i, a) {
						if (book.spine.get(a.href).canonical == cur_href) {
							toc_entry = a;
							return;
						}

						if (iterate_sublist(a, 0)) return;

					});

					if (toc_entry && toc_entry.label.trim())
						$(".chapter").append("&nbsp;" + toc_entry.label);
				}

			} catch (e) {
				console.warn(e);
			}
		});

		rendition.on('relocated', function(location) {

			// locations not generated yet
			if (book.locations.length() == 0)
				return;

			var currentCfi = location.start.cfi;
			var currentPage = parseInt(book.locations.percentageFromCfi(currentCfi) * 100);
			var pct = book.locations.percentageFromCfi(currentCfi);

			$("#cur_page").html(location.start.location);
			$("#total_pages").html(book.locations.length());

			$("#page_pct").html(parseInt(pct*100) + '%');

			if (_store_position && new Date().getTime()/1000 - _last_position_sync > 15) {
				console.log("storing lastread", currentPage, currentCfi);

				if (navigator.onLine) {

					$.post("backend.php", { op: "storelastread", id: $.urlParam("id"), page: currentPage,
						cfi: currentCfi }, function(data) {

						if (data.cfi) {
							_last_position_sync = new Date().getTime()/1000;
						}

					})
					.fail(function(e) {
						if (e && e.status == 401) {
							window.location = "index.php";
						}
					});

					_store_position = 0;
				} else {
					_last_position_sync = 0;
				}

				localforage.setItem(cacheId("lastread"),
					{cfi: currentCfi, page: currentPage, total: 100});

			}
		});

	}
</script>

</body>
</html>