# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ class MediumClass constructor: (@dropbox_element='.dropbox') -> @filesForUpload = new Array @all_files = 0 @uploaded_files = 0 @dropbox = $(@dropbox_element) initializeBindings: (dragdrop=document) -> @unBinds() @doBinds() # # first unbind clicks unBinds: () -> $(document.body).unbind('click.media_start') $(document.body).unbind('click.media_delete') $(document.body).unbind('drop.media') $(document.body).unbind('click.media_pick') # draggable $(document.body).unbind("dragleave.media") $(document.body).unbind("dragover.media") $(document.body).unbind("drop.media") $(document.body).unbind("drag.media") $(document.body).unbind("dragenter.media") $(document.body).unbind('change.media') $(document.body).unbind('click.preventDefaultClick') $(document.body).unbind('click.cropFile') $(document.body).unbind('click.uploadFile') $(document.body).unbind('click.deleteFile') $(document.body).unbind('click.toggleCardReveal') $(document.body).unbind('click.clickMediumInput') # @dropbox.unbind('click.media_cancel') # $(document.body).unbind('click.cancelFile') # # bind clicks doBinds: () -> $(document.body).on 'click.media_show', '.edit_link', @show_media $(document.body).on 'click.media_start', 'span.btn.hover_green.start', @uploadFile $(document.body).on 'click.media_delete', 'span.btn.delete', @deleteFile $(document.body).on 'click.clickMediumInput', '.fileinput-button', @clickMediumInput $(document.body).on 'click.preventDefaultClick', '.fileinput-button, a.file-upload', @preventDefaultClick $(document.body).on 'click.cropFile', 'a.edit_link.file-upload', @cropFile $(document.body).on 'click.uploadFile', 'a.start.file-upload', @uploadFile $(document.body).on 'click.deleteFile', 'a.delete.file-upload', @deleteFile $(document.body).on 'click.toggleCardReveal', '.card_properties', @toggleCardReveal $(document.body).on "drag.media", @dropbox_element, @dragMedia $(document.body).on "dragenter.media", @dropbox_element, @dragEnterMedia $(document.body).on "dragleave.media", @dropbox_element, @dragLeaveMedia $(document.body).on "dragover.media", @dropbox_element, @dragOverMedia $(document.body).on "drop.media", @dropbox_element, @dropMedia $(document.body).on 'change.media', '#medium_medium', @updateSelectedFiles # $(document.body).on 'click.cancelFile', 'a.cancel.file-upload', @cancelFile # $(document.body).on 'click.media_cancel', 'span.btn.hover_yellow.cancel', @cancelUploading preventDefaultClick: (e) -> e.preventDefault() e.stopPropagation() toggleCardReveal: (e) => @preventDefaultClick(e) $(e.currentTarget).closest('.card').find('.card-reveal').toggle() clickMediumInput: (e) => @preventDefaultClick() $('#medium_medium').click() dragEnterMedia: (e) => @preventDefaultClick(e) dragMedia: (e) => @preventDefaultClick(e) # ev.dataTransfer.setData("text", ev.target.id); dragOverMedia: (e) => @preventDefaultClick(e) $(@dropbox_element).addClass('drop-ready') dragLeaveMedia: (e) => @preventDefaultClick(e) $(@dropbox_element).removeClass('drop-ready') # # dropMedia handles the 'drop' event # dropMedia: (e) => @preventDefaultClick(e) # ev.preventDefault(); # var data = ev.dataTransfer.getData("text"); # ev.target.appendChild(document.getElementById(data)); $(e.currentTarget).removeClass('drop-ready') dt = e.originalEvent.dataTransfer files = dt.files @handleFiles(files) # # show_media opens a modal window and presents the images # show_media: (e) => @preventDefaultClick(e) $elem = $(e.currentTarget).closest('a') _id = $elem.data('id') url = $elem.attr('href') + '/crop.js' $.ajax url: url, type: "get", dataType: 'html' .done (r) -> $modal = $('#modal1') $modal.find('.modal-content').html(r) $modal.openModal ready: () -> $('a.close-modal').on 'click', (e) -> e.preventDefault() e.stopPropagation() jqxhr = $.ajax url: '/media/' + _id + '/update_crop.js' method: 'POST' dataType: 'html' data: id: _id, medium: medium_crop_x: $('#medium_medium_crop_x').val(), medium_crop_y: $('#medium_medium_crop_y').val(), medium_crop_w: $('#medium_medium_crop_w').val(), medium_crop_h: $('#medium_medium_crop_h').val() .fail (r) -> console.log r .done (r) -> $elem.closest('.card').find('.card-image').html(r) $modal.closeModal() new CarrierWaveCropper() # statusCode: # 200: (response,textStatus,jqXHR) -> # $modal = $('#modal1') # $modal.find('.modal-content').html(response.responseText) # $modal.attr('task_id', _id) # $modal.openModal() # set_close_event(elem) # 401: () -> # alert 'Du har ikke lov at se denne opgave!?!' # delete all files ready for upload - or if non exists - delete all # media attached to this object # deleteFile: (elem='all') => deleteAllFiles = elem == 'all' if deleteAllFiles elem = $($(@dropbox_element).find('.card.new_upload')) if elem.length==0 $('.sweet-overlay').show() elem = swal title: "Ingen filer der skal overføres?", text: "Vil du istedet slette alle tilknyttede medier, vist herunder permanent! Du vil ikke kunne hente dem frem igen!", type: "warning", html: true, showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Ja, slet dem!", cancelButtonText: "Nej - jeg har fortrudt!" closeOnConfirm: false, closeOnCancel: false, (confirmed) -> if confirmed elem= $('#media').find('.delete_link:visible') elem.push(e) for e in $('.files').find('.delete_link:visible') for f in elem deletePost $(f) f.remove() else elem = [] closeSweetAlert() elem else for f in elem f.remove() @filesForUpload = new Array else elem = elem.currentTarget elem = $(elem).closest('.card')[0] img = $(elem).find('img')[0] if img for card in $('.files .new_upload') #$($(@dropbox_element).find('.card.new_upload')) if card==elem tmp = @filesForUpload.slice() for f in tmp if ''+f.id == ''+img.id @filesForUpload.splice( @filesForUpload.indexOf(f),1) elem.remove() showProgress: (card,percent,direction) -> card.find(".progress.fileupload-progress").show() card.find(".progress.fileupload-progress .determinate").css('width',percent) # prepare upload for one file # setup eventListeners # before, during and after upload has completed # ajx: (_card, formData) => deferred = $.Deferred() jqxhr = $.ajax url : '/media.js' type : 'POST' data : formData processData: false contentType: false dataType: 'html' beforeSend: (req) => _card.find('.progress').show() xhr: () => xhr = new window.XMLHttpRequest() # Upload progress xhr.upload.addEventListener "progress", (e) => # console.log 'progressing with upload' if e.lengthComputable percent = Math.round( e.loaded * 100 / e.total) + '%' @showProgress _card,percent,'uploaded' # console.log( percent + ' uploaded') # Download progress xhr.addEventListener "progress", (e) => # console.log 'progressing with download' if (e.lengthComputable) percent = (e.loaded * 100 / e.total) + '%' @showProgress _card,percent,'downloaded' # console.log( percent + ' downloaded') xhr .done (r) => $.when _card.remove() .done () => @uploaded_files += 1 percent = Math.round( @uploaded_files * 100 / @all_files ) + '%' @showProgress $('.fileupload-buttonbar'), percent, 'uploaded' $('#media').prepend r .then () => console.log 'ajx resolved ---' deferred.resolve() .fail (e,msg) => swal "Fejl!", "Der opstod desværre en fejl - beskrivelsen er:\n" + msg, "error" deferred.resolve() deferred.promise() # # collect and prepare all files ready for upload # defer xfer files # xfer: (formData,img,uploadAllFiles) => deferred = $.Deferred() _processes = [] if uploadAllFiles @uploaded_files = 0 @all_files = $('.files .new_upload').length while @filesForUpload.length>0 try f = @filesForUpload.pop() _card = $($('#'+ f.id).closest('.card:visible')) if _card formData.append 'medium[medium]', f _processes.push( @ajx(_card,formData)) catch err console.log err $.when.apply $, _processes .done () -> console.log 'xfer resolved ---' deferred.resolve() else @all_files = 1 console.log 'filesForUpload: ' + @filesForUpload tmp = @filesForUpload.slice() console.log '# of files: ' + tmp.length console.log 'tmp: ' + tmp while tmp.length > 0 f = tmp.pop() console.log 'f: ' + f try if (''+f.id)==(''+img.id) console.log 'hit: ' + f @filesForUpload.splice( @filesForUpload.indexOf(f),1) console.log '# of filesForUpload: ' + @filesForUpload.length _card = $($('#'+ f.id).closest('.card')) formData.append 'medium[medium]', f _processes.push( @ajx(_card,formData)) catch err console.log f console.log img $.when.apply $, _processes .done () -> deferred.resolve() deferred.promise() uploadFile: (elem='all') => formData = new FormData() uploadAllFiles = elem == 'all' if uploadAllFiles elem = $('.files .new_upload') return if $('.files .new_upload').length < 1 else $elem = $(elem.currentTarget) img = $elem.closest('.card').find('img')[0] _id = $elem.closest(@dropbox_element).find('#medium_imageable_id').val() _type = $elem.closest(@dropbox_element).find('#medium_imageable_type').val() if img formData.append 'medium[imageable_id]', _id formData.append 'medium[imageable_type]', _type $.when @xfer(formData,img,uploadAllFiles) .done () => # console.log 'uploadFile will move on --' $('.fileupload-buttonbar .fileupload-progress').hide() updateSelectedFiles: (elem) => # nBytes = 0 elem = e.currentTarget oFiles = $(elem)[0].files console.log oFiles # nFiles = oFiles.length # nBytes += v.size for v in oFiles # # sOutput = nBytes + " bytes" # nApprox = nBytes / 1024 # aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] # nMultiple = 0 # nApprox /= 1024 # nMultiple = while nApprox > 1.0 # console.log nApprox + ' ' + nMultiple # nApprox /= 1024 # nMultiple += 1 # # sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)" # # $(".fileNum").html nFiles + ' filer' # $(".fileSize").html sOutput # $('.files').html tmpl('uploads',data) @handleFiles(oFiles) lazyGetTemplate: (name) => deferred = $.Deferred() if $.templates[name] deferred.resolve() else $.get "/assets/templates/" + name + ".html" .fail (r,msg) -> if r.status==200 $.templates(name,r.responseText) deferred.resolve() else swal 'Fejl', 'Der opstod en fejl! Ordlyden er:\n ' + msg + '\n' + r.status + ': ' + r.statusText + '\n kontakt ALCO på tlf: 9791 1470!', "error" .done (r) -> $.templates(name,r) if $.templates[name] deferred.resolve() else swal "Fejl", "Der opstod en fejl under hentningen af en skabelon til billed visning! Kontakt ALCO på tlf: 9791 1470", "error" deferred.reject() return deferred.promise() handleFiles: (f) => $.when( @lazyGetTemplate('selected_files')) .done () => for file in f imageType = /^image\// # if (!imageType.test(file.type)) # continue file.id = Date.now() $.when $('.files').prepend $.templates.selected_files.render(file) .done () -> img = $('#'+file.id) img.file = file if (!imageType.test(file.type)) src = switch when /application.*pdf/.exec file.type then '/assets/2.jpg' when /mp4/.exec file.type then '/assets/2.jpg' when /applica.*sql/.exec file.type then '/assets/2.jpg' when /applica.*zip/.exec file.type then '/assets/2.jpg' when /applica.*csv/.exec file.type then '/assets/2.jpg' when /applica.*sheet/.exec file.type then '/assets/2.jpg' when /applica.*document/.exec file.type then '/assets/2.jpg' else "#{ image_url('logo.png') }" console.log 'src: ' + src $(img).attr('src', src ) else reader = new FileReader() reader.onload = (e) -> $(img).attr('src', e.target.result) reader.readAsDataURL(file) @filesForUpload.push(file) freshImageSrcPattern = /// ^ data .* ///i cropFile: (e) => @preventDefaultClick(e) $elem = $(e.currentTarget) img = $elem.closest('.card').find('img')[0] if $(img).attr('src').match freshImageSrcPattern $('#medium_medium_cropbox').attr('src',$(img).attr('src')) $modal = $('#modal1') $modal.openModal new CarrierWaveCropper() else # _edit = "/crop" # _id = "0" # url = '/media/' + _id + _edit + '.js' jqxhr = $.ajax url: $(elem).attr('href') + '/edit.js', type: "get", data: id: _id, dataType: 'html' .fail (r) -> console.log r .done (r) -> $modal = $('#modal1') $('.modal-content').html(r) $modal.openModal ready: () -> $('.close-modal').on 'click', (e) -> e.preventDefault() $.ajax url: '/media/' + _id + '/update_crop.js' method: 'POST' data: id: _id, medium: medium_crop_x: $('#medium_medium_crop_x').val(), medium_crop_y: $('#medium_medium_crop_y').val(), medium_crop_w: $('#medium_medium_crop_w').val(), medium_crop_h: $('#medium_medium_crop_h').val() .fail (r) -> console.log r .done (r) -> $modal.closeModal() new CarrierWaveCropper() @Medium = MediumClass