Bug 30223: Move book cover image upload JS to a separate file
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / upload-images.js
1 /* global __ interface theme biblionumber */
2
3 $(document).ready(function(){
4     $("html").on("drop", function(e) {
5         e.preventDefault();
6         e.stopPropagation();
7     });
8
9     $("#zipfile").on("click", function(){
10         $("biblionumber_entry").hide();
11     });
12
13     $("#image").on("click", function(){
14         $("#biblionumber_entry").show();
15     });
16
17     $("#uploadfile").validate({
18         submitHandler: function() {
19             StartUpload();
20             return false;
21         }
22     });
23
24     $("#filedrag").on("click", ".cancel_image", function(){
25         $("#click_to_select").show();
26         $("#messages").html("");
27         $("#fileToUpload").prop( "disabled", false );
28         $("#process_images, #fileuploadstatus").hide();
29         return false;
30     }).on("click", ".save_image", function(e){
31         e.preventDefault();
32         $("#processfile").submit();
33     });
34
35     $("html").on("drop", function(e) {
36         /* Prevent the default browser action when image is dropped */
37         /* i.e. don't navigate to a view of the local image */
38         e.preventDefault();
39         e.stopPropagation();
40     });
41
42     $('#filedrag').on('dragenter dragover dragleave', function (e) {
43         /* Handle various drag and drop events in "Drop files" area */
44         /* If event type is "dragover," add the "hover" class */
45         /* otherwise set no class name */
46         e.stopPropagation();
47         e.preventDefault();
48         e.target.className = (e.type == "dragover" ? "hover" : "");
49     });
50
51     $("#filedrag").on("click", function(){
52         /* Capture a click inside the drag and drop area */
53         /* Trigger the <input type="file"> action */
54         $("#fileToUpload").click();
55     });
56
57     // Drop
58     $('#filedrag').on('drop', function (e) {
59         e.stopPropagation();
60         e.preventDefault();
61         prepUpLoad(e);
62     });
63
64     // file selected
65     $("#fileToUpload").on("change", function(){
66         prepUpLoad();
67     });
68
69     $('.thumbnails .remove').on("click", function(e) {
70         e.preventDefault();
71         var result = confirm(__("Are you sure you want to delete this cover image?"));
72         var imagenumber = $(this).data("coverimg");
73         if ( result == true ) {
74             removeLocalImage(imagenumber);
75         }
76     });
77 });
78
79 function prepUpLoad( event ){
80     $("#click_to_select,#upload_results").hide();
81     $("#messages").html("");
82     var file;
83     if( event ){
84         file = event.originalEvent.dataTransfer.files[0];
85     } else {
86         file = $('#fileToUpload')[0].files[0];
87     }
88
89     $("#fileuploadstatus, #upload_options").show();
90     var fd = new FormData();
91     fd.append('file', file);
92     if( ParseFile( file ) ){
93         StartUpload( fd );
94     }
95 }
96
97 function StartUpload( fd ) {
98     $('#uploadform button.submit').prop('disabled',true);
99     $("#uploadedfileid").val('');
100     AjaxUpload( fd, $('#fileuploadprogress'), 'temp=1', cbUpload );
101 }
102
103 function cbUpload( status, fileid, errors ) {
104     if( status=='done' ) {
105         $("#uploadedfileid").val( fileid );
106         $('#fileToUpload').prop('disabled',true);
107         $("#process_images").show();
108     } else {
109         var errMsgs = [ __("Error code 0 not used"), __("File already exists"), __("Directory is not writeable"), __("Root directory for uploads not defined"), __("Temporary directory for uploads not defined") ];
110         var errCode = errors[$('#fileToUpload').prop('files')[0].name].code;
111         $("#fileuploadstatus").hide();
112         $("#fileuploadfailed").show();
113         $("#fileuploadfailed").text( __("Upload status: ") +
114             ( status=='failed'? __("Failed") + " - (" + errCode + ") " + errMsgs[errCode]:
115                 ( status=='denied'? __("Denied"): status ))
116         );
117         $("#processfile").hide();
118     }
119 }
120
121 function AjaxUpload ( formData, progressbar, xtra, callback ) {
122     var xhr= new XMLHttpRequest();
123     var url= '/cgi-bin/koha/tools/upload-file.pl?' + xtra;
124     progressbar.val( 0 );
125     progressbar.next('.fileuploadpercent').text( '0' );
126     xhr.open('POST', url, true);
127     xhr.upload.onprogress = function (e) {
128         var p = Math.round( (e.loaded/e.total) * 100 );
129         progressbar.val( p );
130         progressbar.next('.fileuploadpercent').text( p );
131     };
132     xhr.onload = function () {
133         var data = JSON.parse( xhr.responseText );
134         if( data.status == 'done' ) {
135             progressbar.val( 100 );
136             progressbar.next('.fileuploadpercent').text( '100' );
137         }
138         callback( data.status, data.fileid, data.errors );
139     };
140     xhr.onerror = function () {
141         // Probably only fires for network failure
142         alert(__("An error occurred while uploading.") );
143     };
144     xhr.send( formData );
145     return xhr;
146 }
147
148 // output file information
149 function ParseFile(file) {
150     var valid = true;
151     if (file.type.indexOf("image") == 0) {
152         /* If the uploaded file is an image, show it */
153         var reader = new FileReader();
154         reader.onload = function(e) {
155             Output(
156                 '<p><img class="cover_preview" src="' + e.target.result + '" /></p>'
157             );
158         };
159         $("#biblionumber_entry").show().find("input,label").addClass("required").prop("required", true );
160         $("#image").prop("checked", true ).change();
161         $("#zipfile").prop("checked", false );
162         reader.readAsDataURL(file);
163     } else if( file.type.indexOf("zip") > 0) {
164         Output(
165             '<p><i class="fa fa-file-archive-o" aria-hidden="true"></i></p>'
166         );
167         $("#biblionumber_entry").hide();
168         $("#image").prop("checked", false );
169         $("#zipfile").prop("checked", true );
170     } else {
171         Output(
172             '<div class="dialog alert"><strong>' + __("Error:") + ' </strong> ' + __("This tool only accepts ZIP files or GIF, JPEG, PNG, or XPM images.") + '</div>'
173         );
174         valid = false;
175         resetForm();
176     }
177
178     Output(
179         "<p>" + __("File name:") + " <strong>" + file.name + "</strong><br />" +
180             __("File type:") + " <strong>" + file.type + "</strong><br />" +
181             __("File size:") + " <strong>" + convertSize( file.size ) + "</strong>"
182     );
183     return valid;
184 }
185
186 // output information
187 function Output(msg) {
188     var m = document.getElementById("messages");
189     m.innerHTML = msg + m.innerHTML;
190 }
191
192 // Bytes conversion
193 function convertSize(size) {
194     var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
195     if (size == 0) return '0 Byte';
196     var i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
197     return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
198 }
199
200 function removeLocalImage(imagenumber) {
201     var thumbnail = $("#imagenumber-" + imagenumber );
202     var copy = thumbnail.html();
203     thumbnail.find("img").css("opacity", ".2");
204     thumbnail.find("a.remove").html("<img style='display:inline-block' src='" + interface + "/" + theme + "/img/spinner-small.gif' alt='' />");
205
206     $.ajax({
207         url: "/cgi-bin/koha/svc/cover_images?action=delete&biblionumber=" + biblionumber + "&imagenumber=" + imagenumber,
208         success: function(data) {
209             $(data).each( function() {
210                 if ( this.deleted == 1 ) {
211                     location.href="/cgi-bin/koha/tools/upload-cover-image.pl?biblionumber=" + biblionumber;
212                 } else {
213                     thumbnail.html( copy );
214                     alert(__("An error occurred on deleting this image"));
215                 }
216             });
217         },
218         error: function() {
219             thumbnail.html( copy );
220             alert(__("An error occurred on deleting this image"));
221         }
222     });
223 }
224
225 function resetForm(){
226     $("#uploadpanel,#upload_options,#process_images").hide();
227     $("#click_to_select").show();
228 }