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