Bug 27944: Add "requested" stage in article request process
[koha.git] / koha-tmpl / opac-tmpl / bootstrap / js / openlibrary.js
1 if (typeof KOHA == "undefined" || !KOHA) {
2     var KOHA = {};
3 }
4
5 /**
6  * A namespace for OpenLibrary related functions.
7  */
8 KOHA.OpenLibrary = new function() {
9
10     /**
11      * Search all:
12      *    <div title="biblionumber" id="isbn" class="openlibrary-thumbnail"></div>
13      * or
14      *    <div title="biblionumber" id="isbn" class="openlibrary-thumbnail-preview"></div>
15      * and run a search with all collected isbns to Open Library Book Search.
16      * The result is asynchronously returned by OpenLibrary and catched by
17      * olCallBack().
18      */
19     this.GetCoverFromIsbn = function() {
20         var bibkeys = [];
21         $("[id^=openlibrary-thumbnail]").each(function(i) {
22             bibkeys.push("ISBN:" + $(this).attr("class")); // id=isbn
23         });
24         bibkeys = bibkeys.join(',');
25         var scriptElement = document.createElement("script");
26         scriptElement.setAttribute("id", "jsonScript");
27         scriptElement.setAttribute("src",
28             "https://openlibrary.org/api/books?bibkeys=" + escape(bibkeys) +
29             "&callback=KOHA.OpenLibrary.olCallBack&jscmd=data");
30         scriptElement.setAttribute("type", "text/javascript");
31         document.documentElement.firstChild.appendChild(scriptElement);
32     }
33
34     /**
35      * Add cover pages <div
36      * and link to preview if div id is gbs-thumbnail-preview
37      */
38     this.olCallBack = function(booksInfo) {
39         for (id in booksInfo) {
40             var book = booksInfo[id];
41             var isbn = id.substring(5);
42             $("[id^=openlibrary-thumbnail]."+isbn).each(function() {
43                 var is_opacdetail = /openlibrary-thumbnail-preview/.exec($(this).attr("id"));
44                 var a = document.createElement("a");
45                 a.href = booksInfo.url;
46                 if (book.cover) {
47                     var img = document.createElement("img");
48                     if (is_opacdetail) {
49                         img.src = book.cover.medium;
50                         $(this).empty().append(img);
51                     } else {
52                         img.src = book.cover.medium;
53                         img.height = '110';
54                         $(this).append(img);
55                     }
56                 } else {
57                     var message =  document.createElement("span");
58                     $(message).attr("class","no-image");
59                     $(message).html(NO_OL_JACKET);
60                     $(this).append(message);
61                 }
62             });
63         }
64     }
65
66     var search_url = 'https://openlibrary.org/search?';
67     this.searchUrl = function( q ) {
68         var params = {q: q};
69         return search_url + $.param(params);
70     };
71
72     var search_url_json = 'https://openlibrary.org/search.json';
73     this.search = function( q, page_no, callback ) {
74         var params = {q: q};
75         if (page_no) {
76             params.page = page_no;
77         }
78         $.ajax( {
79             type: 'GET',
80             url: search_url_json,
81             dataType: 'json',
82             data: params,
83             error: function( xhr, error ) {
84                 try {
85                     callback( JSON.parse( xhr.responseText ));
86                 } catch ( e ) {
87                     callback( {error: xhr.responseText || true} );
88                 }
89             },
90             success: callback
91         } );
92     };
93 };
94 /* readapi_automator.js */
95
96 /*
97 This script helps to put readable links to Open Library books into
98 online book catalogs.
99 When loaded, it searches the DOM for <div> elements with class
100 "ol_readapi_book", extracts book identifiers from them (e.g. isbn,
101 lccn, etc.) and puts those into an asynchronous call to the Read API.
102 When the call returns, the results are used to add clickable links
103 to the "ol_readapi_book" elements found earlier.
104 A demonstration use of this script is available here:
105 http://internetarchive.github.com/read_api_extras/readapi_demo.html
106 */
107
108 var ol_readapi_automator =
109 (function () { // open anonymous scope for tidiness
110
111 // 'constants'
112 var readapi_bibids = ['isbn', 'lccn', 'oclc', 'olid', 'iaid', 'bibkeys'];
113 var magic_classname = 'ol_readapi_book';
114 var ol_readapi_books = $("." + magic_classname );
115 var result;
116
117 // added to book divs to correlate with API results
118 var magic_bookid = 'ol_bookid';
119 var ol_button_classname = 'ol_readapi_button';
120
121 // Find all book divs and concatenate ids from them to create a read
122 // API query url
123 function create_query() {
124     var q = 'https://openlibrary.org/api/volumes/brief/json/';
125
126     function add_el(i, el) {
127         // tag with number found so it's easy to discover later
128         // (necessary?  just go by index?)
129         // (choose better name?)
130         $(el).attr(magic_bookid, i);
131
132         if (i > 0) {
133             q += '|';
134         }
135         q += 'id:' + i;
136
137         for (bi in readapi_bibids) {
138             bibid = readapi_bibids[bi];
139             if ($(el).attr(bibid)) {
140                 q += ';' + bibid + ':' + $(el).attr(bibid);
141             }
142         }
143     }
144
145     $('.' + magic_classname).each(add_el);
146     return q;
147 }
148
149 function make_read_button(bookdata) {
150     buttons = {
151         'full access':
152         "https://openlibrary.org/images/button-read-open-library.png",
153         'lendable':
154         "https://openlibrary.org/images/button-borrow-open-library.png",
155         'checked out':
156         "https://openlibrary.org/images/button-checked-out-open-library.png"
157     };
158     if (bookdata.items.length == 0) {
159         return false;
160     }
161     first = bookdata.items[0];
162     if (!(first.status in buttons)) {
163         return false;
164     }
165     result = '<a target="_blank" href="' + first.itemURL + '">' +
166       '<img class="' + ol_button_classname +
167       '" src="' + buttons[first.status] + '"/></a>';
168     console.log( result );
169     return result;
170 }
171
172 // Default function for decorating document elements with read API data
173 function default_decorate_el_fn(el, bookdata) {
174     // Note that 'bookdata' may be undefined, if the Read API call
175     // didn't return results for this book
176     var decoration;
177     if (bookdata) {
178         decoration = make_read_button(bookdata);
179     }
180     if (decoration) {
181         el.innerHTML += decoration;
182         el.style.display = 'block'
183     } else {
184         el.style.display = 'none';
185     }
186 }
187
188 function do_query(q, decorate_el_fn) {
189     if (!decorate_el_fn) {
190         decorate_el_fn = default_decorate_el_fn;
191     }
192     var starttime = (new Date()).getTime();
193
194     // Call a function on each <div class="ol_readapi_book"> element
195     // with the target element and the data found for that element.
196     // Use decorate_el_fn if supplied, falling back to
197     // default_decorate_el_fn, above.
198     function query_callback(data, textStatus, jqXHR) {
199         var endtime = (new Date()).getTime();
200         var duration = (endtime - starttime) / 1000;
201         // console.log('took ' + duration + ' seconds');
202
203         $('.' + magic_classname).each(function(i, el) {
204                 var bookid = $(el).attr(magic_bookid);
205                 if (bookid && bookid in data) {
206                     decorate_el_fn(el, data[bookid]);
207                 } else {
208                     decorate_el_fn(el);
209                 }
210             });
211     }
212
213     // console.log('calling ' + q);
214     $.ajax({ url: q,
215                 data: { 'show_all_items': 'true' },
216                 dataType: 'jsonp',
217                 success: query_callback
218                 });
219 }
220
221 if( ol_readapi_books.length > 0 ){
222     // Do stuff
223     var q = create_query();
224     do_query(q);
225
226     result = {
227         do_query: do_query,
228         create_query: create_query,
229         make_read_button: make_read_button
230     };
231 }
232
233 return result;
234 })(); // close anonymous scope
235
236 /*
237 Possible futures:
238 * Support alternate query targets, e.g. Hathi
239 * show_all_items
240 * show_inlibrary
241 * ezproxy prefix (implies show_inlibrary?)
242 * console debug output? (check all console.log)
243 */