+function OLAuth() {
+ this.authUrl = 'http://openlibrary.org/ia_auth/' + br.bookId;
+ this.olConnect = false;
+ return this;
+}
+
+OLAuth.prototype.init = function() {
+ var htmlStr = '<p style="text-align:center;"><b>Authenticating in-browser loan with openlibrary.org!</b></p>';
+ htmlStr += '<p>Please wait...</p>';
+
+ this.showPopup("#ddd", "#000", htmlStr);
+ $.ajax({url:this.authUrl, dataType:'jsonp', jsonpCallback:'olAuth.initCallback'});
+}
+
+OLAuth.prototype.showPopup = function(bgColor, textColor, msg) {
+ this.popup = document.createElement("div");
+ $(this.popup).css({
+ position: 'absolute',
+ top: '20px',
+ left: ($('#BookReader').attr('clientWidth')-400)/2 + 'px',
+ width: '400px',
+ padding: "20px",
+ border: "3px double #999999",
+ zIndex: 3,
+ backgroundColor: bgColor,
+ color: textColor
+ }).appendTo('#BookReader');
+
+ this.popup.innerHTML = msg;
+
+}
+
+OLAuth.prototype.initCallback = function(obj) {
+ if (false == obj.success) {
+ $(this.popup).css({
+ backgroundColor: "#f00",
+ color: "#fff"
+ });
+
+ this.popup.innerHTML = obj.msg;
+ return;
+ }
+
+ //user is authenticated
+ this.setCookie(obj.token);
+ this.olConnect = true;
+ this.startPolling();
+ br.init();
+}
+
+OLAuth.prototype.callback = function(obj) {
+ if (false == obj.success) {
+ this.showPopup("#f00", "#fff", obj.msg);
+ clearInterval(this.poller);
+ this.ttsPoller = null;
+ } else {
+ this.olConnect = true;
+ this.setCookie(obj.token);
+ }
+}
+
+OLAuth.prototype.setCookie = function(value) {
+ var date = new Date();
+ date.setTime(date.getTime()+(24*60*60*1000)); //one day expiry
+ var expiry = date.toGMTString();
+ var cookie = 'loan-'+br.bookId+'='+value;
+ cookie += '; expires='+expiry;
+ cookie += '; path=/; domain=.archive.org;';
+ document.cookie = cookie;
+}
+
+OLAuth.prototype.startPolling = function () {
+ var self = this;
+ this.poller=setInterval(function(){
+ if (!self.olConnect) {
+ self.showPopup("#f00", "#fff", 'Cound not connect to Open Library for authentication. Please check to see if you are still connected to the Internet, and then reload this web page.');
+ clearInterval(self.poller);
+ self.ttsPoller = null;
+ } else {
+ self.olConnect = false;
+ //be sure to add random param to authUrl to avoid stale cache
+ $.ajax({url:self.authUrl+'?rand='+Math.random(), dataType:'jsonp', jsonpCallback:'olAuth.callback'});
+ }
+ },300000);
+}
+
+br.cleanupMetadata();
+if (br.olAuth) {
+ var olAuth = new OLAuth();
+ olAuth.init();
+} else {
+ br.init();
+}