/*! bootstrap-fileinput v5.0.4 http://plugins.krajee.com/file-input Author: Kartik Visweswaran Copyright: 2014 - 2019, Kartik Visweswaran, Krajee.com Licensed under the BSD-3-Clause https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md */(function(factory){'use strict';if(typeof define==='function'&&define.amd){define(['jquery'],factory);}else{if(typeof module==='object'&&module.exports){module.exports=factory(require('jquery'));}else{factory(window.jQuery);}}}(function($){'use strict';$.fn.fileinputLocales={};$.fn.fileinputThemes={};String.prototype.setTokens=function(replacePairs){var str=this.toString(),key,re;for(key in replacePairs){if(replacePairs.hasOwnProperty(key)){re=new RegExp('\{'+key+'\}','g');str=str.replace(re,replacePairs[key]);}}return str;};var $h,FileInput;$h={FRAMES:'.kv-preview-thumb',SORT_CSS:'file-sortable',OBJECT_PARAMS:'\n'+'\n'+'\n'+'\n'+'\n'+'\n',DEFAULT_PREVIEW:'
\n'+'{previewFileIcon}\n'+'
',MODAL_ID:'kvFileinputModal',MODAL_EVENTS:['show','shown','hide','hidden','loaded'],logMessages:{ajaxError:'{status}: {error}. Error Details: {text}.',badDroppedFiles:'Error scanning dropped files!',badExifParser:'Error loading the piexif.js library. {details}',badInputType:'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',exifWarning:'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded '+'the "piexif.js" library correctly on your page before the "fileinput.js" script.',invalidChunkSize:'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',invalidThumb:'Invalid thumb frame with id: "{id}".',noResumableSupport:'The browser does not support resumable or chunk uploads.',noUploadUrl:'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',retryStatus:'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.'},objUrl:window.URL||window.webkitURL,now:function(){return new Date();},round:function(num){num=parseFloat(num);return isNaN(num)?0:Math.floor(Math.round(num));},getFileRelativePath:function(file){return String(file.relativePath||file.webkitRelativePath||$h.getFileName(file)||null);},getFileId:function(file,generateFileId){var relativePath=$h.getFileRelativePath(file);if(typeof generateFileId==='function'){return generateFileId(file);}if(!file){return null;}if(!relativePath){return null;}return(file.size+'_'+relativePath.replace(/\s/img,'_'));},getElapsed:function(seconds){var delta=seconds,out='',result={},structure={year:31536000,month:2592000,week:604800,day:86400,hour:3600,minute:60,second:1};Object.keys(structure).forEach(function(key){result[key]=Math.floor(delta/structure[key]);delta-=result[key]*structure[key];});$.each(result,function(key,value){if(value>0){out+=(out?' ':'')+value+key.substring(0,1);}});return out;},debounce:function(func,delay){var inDebounce;return function(){var args=arguments,context=this;clearTimeout(inDebounce);inDebounce=setTimeout(function(){func.apply(context,args);},delay);};},stopEvent:function(e){e.stopPropagation();e.preventDefault();},getFileName:function(file){return file?(file.fileName||file.name||''):'';},createObjectURL:function(data){if($h.objUrl&&$h.objUrl.createObjectURL&&data){return $h.objUrl.createObjectURL(data);}return'';},revokeObjectURL:function(data){if($h.objUrl&&$h.objUrl.revokeObjectURL&&data){$h.objUrl.revokeObjectURL(data);}},compare:function(input,str,exact){return input!==undefined&&(exact?input===str:input.match(str));},isIE:function(ver){var div,status;if(navigator.appName!=='Microsoft Internet Explorer'){return false;}if(ver===10){return new RegExp('msie\\s'+ver,'i').test(navigator.userAgent);}div=document.createElement('div');div.innerHTML='';status=div.getElementsByTagName('i').length;document.body.appendChild(div);div.parentNode.removeChild(div);return status;},canAssignFilesToInput:function(){var input=document.createElement('input');try{input.type='file';input.files=null;return true;}catch(err){return false;}},getDragDropFolders:function(items){var i,item,len=items?items.length:0,folders=0;if(len>0&&items[0].webkitGetAsEntry()){for(i=0;i=0){byteStr=atob(dataURI.split(',')[1]);}else{byteStr=decodeURIComponent(dataURI.split(',')[1]);}arrayBuffer=new ArrayBuffer(byteStr.length);intArray=new Uint8Array(arrayBuffer);for(i=0;i>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:out+=String.fromCharCode(c);break;case 12:case 13:char2=array[i++];out+=String.fromCharCode(((c&0x1F)<<6)|(char2&0x3F));break;case 14:char2=array[i++];char3=array[i++];out+=String.fromCharCode(((c&0x0F)<<12)|((char2&0x3F)<<6)|((char3&0x3F)<<0));break;}}return out;},isHtml:function(str){var a=document.createElement('div');a.innerHTML=str;for(var c=a.childNodes,i=c.length;i--;){if(c[i].nodeType===1){return true;}}return false;},isSvg:function(str){return str.match(/^\s*<\?xml/i)&&(str.match(//g,'>').replace(/"/g,'"').replace(/'/g,''');},replaceTags:function(str,tags){var out=str;if(!tags){return out;}$.each(tags,function(key,value){if(typeof value==='function'){value=value();}out=out.split(key).join(value);});return out;},cleanMemory:function($thumb){var data=$thumb.is('img')?$thumb.attr('src'):$thumb.find('source').attr('src');$h.revokeObjectURL(data);},findFileName:function(filePath){var sepIndex=filePath.lastIndexOf('/');if(sepIndex===-1){sepIndex=filePath.lastIndexOf('\\');}return filePath.split(filePath.substring(sepIndex,sepIndex+1)).pop();},checkFullScreen:function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement;},toggleFullScreen:function(maximize){var doc=document,de=doc.documentElement;if(de&&maximize&&!$h.checkFullScreen()){if(de.requestFullscreen){de.requestFullscreen();}else{if(de.msRequestFullscreen){de.msRequestFullscreen();}else{if(de.mozRequestFullScreen){de.mozRequestFullScreen();}else{if(de.webkitRequestFullscreen){de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);}}}}}else{if(doc.exitFullscreen){doc.exitFullscreen();}else{if(doc.msExitFullscreen){doc.msExitFullscreen();}else{if(doc.mozCancelFullScreen){doc.mozCancelFullScreen();}else{if(doc.webkitExitFullscreen){doc.webkitExitFullscreen();}}}}}},moveArray:function(arr,oldIndex,newIndex,reverseOrder){var newArr=$.extend(true,[],arr);if(reverseOrder){newArr.reverse();}if(newIndex>=newArr.length){var k=newIndex-newArr.length;while((k--)+1){newArr.push(undefined);}}newArr.splice(newIndex,0,newArr.splice(oldIndex,1)[0]);if(reverseOrder){newArr.reverse();}return newArr;},cleanZoomCache:function($el){var $cache=$el.closest('.kv-zoom-cache-theme');if(!$cache.length){$cache=$el.closest('.kv-zoom-cache');}$cache.remove();},closeButton:function(css){css=css?'close '+css:'close';return'';},getRotation:function(value){switch(value){case 2:return'rotateY(180deg)';case 3:return'rotate(180deg)';case 4:return'rotate(180deg) rotateY(180deg)';case 5:return'rotate(270deg) rotateY(180deg)';case 6:return'rotate(90deg)';case 7:return'rotate(90deg) rotateY(180deg)';case 8:return'rotate(270deg)';default:return'';}},setTransform:function(el,val){if(!el){return;}el.style.transform=val;el.style.webkitTransform=val;el.style['-moz-transform']=val;el.style['-ms-transform']=val;el.style['-o-transform']=val;}};FileInput=function(element,options){var self=this;self.$element=$(element);self.$parent=self.$element.parent();if(!self._validate()){return;}self.isPreviewable=$h.hasFileAPISupport();self.isIE9=$h.isIE(9);self.isIE10=$h.isIE(10);if(self.isPreviewable||self.isIE9){self._init(options);self._listen();}self.$element.removeClass('file-loading');};FileInput.prototype={constructor:FileInput,_cleanup:function(){var self=this;self.reader=null;self.clearFileStack();self.fileBatchCompleted=true;self.isError=false;self.cancelling=false;self.paused=false;self.lastProgress=0;self._initAjax();},_initAjax:function(){var self=this;self.ajaxQueue=[];self.ajaxRequests=[];self.ajaxQueueIntervalId=null;self.ajaxCurrentThreads=0;self.ajaxAborted=false;},_init:function(options,refreshMode){var self=this,f,$el=self.$element,$cont,t,tmp;self.options=options;$.each(options,function(key,value){switch(key){case'minFileCount':case'maxFileCount':case'minFileSize':case'maxFileSize':case'maxFilePreviewSize':case'resizeImageQuality':case'resizeIfSizeMoreThan':case'progressUploadThreshold':case'initialPreviewCount':case'zoomModalHeight':case'minImageHeight':case'maxImageHeight':case'minImageWidth':case'maxImageWidth':self[key]=$h.getNum(value);break;default:self[key]=value;break;}});if(self.rtl){tmp=self.previewZoomButtonIcons.prev;self.previewZoomButtonIcons.prev=self.previewZoomButtonIcons.next;self.previewZoomButtonIcons.next=tmp;}if(!isNaN(self.maxAjaxThreads)&&self.maxAjaxThreadsrm.file.size?rm.file.size:size;},getTotalChunks:function(){var rm=self.resumableManager,chunkSize=parseFloat(rm.chunkSize);if(!isNaN(chunkSize)&&chunkSize>0){return Math.ceil(rm.file.size/chunkSize);}return 0;},getProgress:function(){var rm=self.resumableManager,processed=rm.processedResumables(),total=rm.chunkCount;if(total===0){return 0;}return Math.ceil(processed/total*100);},checkAborted:function(intervalId){if(self.paused||self.cancelling){clearInterval(intervalId);self.unlock();}},upload:function(){var rm=self.resumableManager,fm=self.fileManager,ids=fm.getIdList(),flag='new',intervalId;intervalId=setInterval(function(){var id;rm.checkAborted(intervalId);if(flag==='new'){self.lock();flag='processing';id=ids.shift();fm.initStats(id);if(fm.stack[id]){rm.init(id,fm.stack[id],fm.getIndex(id));rm.testUpload();rm.uploadResumable();}}if(!fm.isPending(id)&&rm.completed){flag='new';}if(fm.isProcessed()){var $initThumbs=self.$preview.find('.file-preview-initial');if($initThumbs.length){$h.addCss($initThumbs,$h.SORT_CSS);self._initSortable();}clearInterval(intervalId);self._clearFileInput();self.unlock();setTimeout(function(){var data=self.previewCache.data;if(data){self.initialPreview=data.content;self.initialPreviewConfig=data.config;self.initialPreviewThumbTags=data.tags;}self._raise('filebatchuploadcomplete',[self.initialPreview,self.initialPreviewConfig,self.initialPreviewThumbTags,self._getExtraData()]);},self.processDelay);}},self.processDelay);},uploadResumable:function(){var i,rm=self.resumableManager,total=rm.chunkCount;for(i=0;iopts.maxRetries){rm.setProcessed('error');return;}var fd,outData,fnBefore,fnSuccess,fnError,fnComplete,slice=file.slice?'slice':(file.mozSlice?'mozSlice':(file.webkitSlice?'webkitSlice':'slice')),blob=file[slice](chunkSize*index,chunkSize*(index+1));fd=new FormData();f=fm.stack[id];self._setUploadData(fd,{chunkCount:rm.chunkCount,chunkIndex:index,chunkSize:chunkSize,chunkSizeStart:chunkSize*index,fileBlob:[blob,rm.fileName],fileId:id,fileName:rm.fileName,fileRelativePath:f.relativePath,fileSize:file.size,retryCount:retry});if(rm.$progress&&rm.$progress.length){rm.$progress.show();}fnBefore=function(jqXHR){outData=self._getOutData(fd,jqXHR);if(self.showPreview){if(!$thumb.hasClass('file-preview-success')){self._setThumbStatus($thumb,'Loading');$h.addCss($thumb,'file-uploading');}$btnDelete.attr('disabled',true);}self._raise('filechunkbeforesend',[id,index,retry,fm,rm,outData]);};fnSuccess=function(data,textStatus,jqXHR){outData=self._getOutData(fd,jqXHR,data);var paramNames=self.uploadParamNames,chunkIndex=paramNames.chunkIndex||'chunkIndex',opts=self.resumableUploadOptions,params=[id,index,retry,fm,rm,outData];rm.currThreads--;if(data.error){if(opts.showErrorLog){self._log(logs.retryStatus,{retry:retry+1,filename:rm.fileName,chunk:index});}rm.pushAjax(index,retry+1);rm.error=data.error;self._raise('filechunkerror',params);}else{rm.logs[data[chunkIndex]]=true;if(!rm.processed[id]){rm.processed[id]={};}rm.processed[id][data[chunkIndex]]=true;rm.processed[id].data=data;self._raise('filechunksuccess',params);rm.check();}};fnError=function(jqXHR,textStatus,errorThrown){outData=self._getOutData(fd,jqXHR);rm.currThreads--;rm.error=errorThrown;rm.logAjaxError(jqXHR,textStatus,errorThrown);self._raise('filechunkajaxerror',[id,index,retry,fm,rm,outData]);rm.pushAjax(index,retry+1);};fnComplete=function(){self._raise('filechunkcomplete',[id,index,retry,fm,rm,self._getOutData(fd)]);};self._ajaxSubmit(fnBefore,fnSuccess,fnComplete,fnError,fd,id,rm.fileIndex);},loopAjax:function(){var rm=self.resumableManager;if(rm.currThreads=rm.getTotalChunks()){rm.setProcessed('success');clearInterval(rm.chunkIntervalId);}}}}}};self.resumableManager.reset();},_initTemplateDefaults:function(){var self=this,tMain1,tMain2,tPreview,tFileIcon,tClose,tCaption,tBtnDefault,tBtnLink,tBtnBrowse,tModalMain,tModal,tProgress,tSize,tFooter,tActions,tActionDelete,tActionUpload,tActionDownload,tActionZoom,tActionDrag,tIndicator,tTagBef,tTagBef1,tTagBef2,tTagAft,tGeneric,tHtml,tImage,tText,tOffice,tGdocs,tVideo,tAudio,tFlash,tObject,tPdf,tOther,tStyle,tZoomCache,vDefaultDim,tStats;tMain1='{preview}\n'+'
\n'+'
\n'+' {caption}\n'+'
\n'+' {remove}\n'+' {cancel}\n'+' {pause}\n'+' {upload}\n'+' {browse}\n'+'
\n'+'
';tMain2='{preview}\n
\n
\n'+'{remove}\n{cancel}\n{upload}\n{browse}\n';tPreview='
\n'+' {close}'+'
\n'+'
\n'+'
\n'+'
'+'
\n'+'
\n'+'
\n'+'
';tClose=$h.closeButton('fileinput-remove');tFileIcon='';tCaption='
\n'+' \n'+' \n'+'
';tBtnDefault='';tBtnLink='{icon} {label}';tBtnBrowse='
{icon} {label}
';tModalMain='';tModal='\n';tProgress='
\n'+'
\n'+' {status}\n'+'
\n'+'
{stats}';tStats='
'+'{pendingTime} '+'{uploadSpeed}'+'
';tSize=' ({sizeText})';tFooter='';tActions='
\n'+' \n'+'
\n'+'{drag}\n'+'
';tActionDelete='\n';tActionUpload='';tActionDownload='{downloadIcon}';tActionZoom='';tActionDrag='{dragIcon}';tIndicator='
{indicator}
';tTagBef='
\n';tTagBef2=tTagBef+' title="{caption}">
\n';tTagAft='
{footer}\n
\n';tGeneric='{content}\n';tStyle=' {style}';tHtml='
{data}
\n';tImage='\n';tText='\n';tOffice='';tGdocs='';tVideo='\n';tAudio='\n';tFlash='\n';tPdf='\n';tObject='\n'+'\n'+$h.OBJECT_PARAMS+' '+$h.DEFAULT_PREVIEW+'\n\n';tOther='
\n'+$h.DEFAULT_PREVIEW+'\n
\n';tZoomCache='';vDefaultDim={width:'100%',height:'100%','min-height':'480px'};if(self._isPdfRendered()){tPdf=self.pdfRendererTemplate.replace('{renderer}',self._encodeURI(self.pdfRendererUrl));}self.defaults={layoutTemplates:{main1:tMain1,main2:tMain2,preview:tPreview,close:tClose,fileIcon:tFileIcon,caption:tCaption,modalMain:tModalMain,modal:tModal,progress:tProgress,stats:tStats,size:tSize,footer:tFooter,indicator:tIndicator,actions:tActions,actionDelete:tActionDelete,actionUpload:tActionUpload,actionDownload:tActionDownload,actionZoom:tActionZoom,actionDrag:tActionDrag,btnDefault:tBtnDefault,btnLink:tBtnLink,btnBrowse:tBtnBrowse,zoomCache:tZoomCache},previewMarkupTags:{tagBefore1:tTagBef1,tagBefore2:tTagBef2,tagAfter:tTagAft},previewContentTemplates:{generic:tGeneric,html:tHtml,image:tImage,text:tText,office:tOffice,gdocs:tGdocs,video:tVideo,audio:tAudio,flash:tFlash,object:tObject,pdf:tPdf,other:tOther},allowedPreviewTypes:['image','html','text','video','audio','flash','pdf','object'],previewTemplates:{},previewSettings:{image:{width:'auto',height:'auto','max-width':'100%','max-height':'100%'},html:{width:'213px',height:'160px'},text:{width:'213px',height:'160px'},office:{width:'213px',height:'160px'},gdocs:{width:'213px',height:'160px'},video:{width:'213px',height:'160px'},audio:{width:'100%',height:'30px'},flash:{width:'213px',height:'160px'},object:{width:'213px',height:'160px'},pdf:{width:'100%',height:'160px'},other:{width:'213px',height:'160px'}},previewSettingsSmall:{image:{width:'auto',height:'auto','max-width':'100%','max-height':'100%'},html:{width:'100%',height:'160px'},text:{width:'100%',height:'160px'},office:{width:'100%',height:'160px'},gdocs:{width:'100%',height:'160px'},video:{width:'100%',height:'auto'},audio:{width:'100%',height:'30px'},flash:{width:'100%',height:'auto'},object:{width:'100%',height:'auto'},pdf:{width:'100%',height:'160px'},other:{width:'100%',height:'160px'}},previewZoomSettings:{image:{width:'auto',height:'auto','max-width':'100%','max-height':'100%'},html:vDefaultDim,text:vDefaultDim,office:{width:'100%',height:'100%','max-width':'100%','min-height':'480px'},gdocs:{width:'100%',height:'100%','max-width':'100%','min-height':'480px'},video:{width:'auto',height:'100%','max-width':'100%'},audio:{width:'100%',height:'30px'},flash:{width:'auto',height:'480px'},object:{width:'auto',height:'100%','max-width':'100%','min-height':'480px'},pdf:vDefaultDim,other:{width:'auto',height:'100%','min-height':'480px'}},mimeTypeAliases:{'video/quicktime':'video/mp4'},fileTypeSettings:{image:function(vType,vName){return($h.compare(vType,'image.*')&&!$h.compare(vType,/(tiff?|wmf)$/i)||$h.compare(vName,/\.(gif|png|jpe?g)$/i));},html:function(vType,vName){return $h.compare(vType,'text/html')||$h.compare(vName,/\.(htm|html)$/i);},office:function(vType,vName){return $h.compare(vType,/(word|excel|powerpoint|office)$/i)||$h.compare(vName,/\.(docx?|xlsx?|pptx?|pps|potx?)$/i);},gdocs:function(vType,vName){return $h.compare(vType,/(word|excel|powerpoint|office|iwork-pages|tiff?)$/i)||$h.compare(vName,/\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i);},text:function(vType,vName){return $h.compare(vType,'text.*')||$h.compare(vName,/\.(xml|javascript)$/i)||$h.compare(vName,/\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);},video:function(vType,vName){return $h.compare(vType,'video.*')&&($h.compare(vType,/(ogg|mp4|mp?g|mov|webm|3gp)$/i)||$h.compare(vName,/\.(og?|mp4|webm|mp?g|mov|3gp)$/i));},audio:function(vType,vName){return $h.compare(vType,'audio.*')&&($h.compare(vName,/(ogg|mp3|mp?g|wav)$/i)||$h.compare(vName,/\.(og?|mp3|mp?g|wav)$/i));},flash:function(vType,vName){return $h.compare(vType,'application/x-shockwave-flash',true)||$h.compare(vName,/\.(swf)$/i);},pdf:function(vType,vName){return $h.compare(vType,'application/pdf',true)||$h.compare(vName,/\.(pdf)$/i);},object:function(){return true;},other:function(){return true;}},fileActionSettings:{showRemove:true,showUpload:true,showDownload:true,showZoom:true,showDrag:true,removeIcon:'',removeClass:'btn btn-sm btn-kv btn-default btn-outline-secondary',removeErrorClass:'btn btn-sm btn-kv btn-danger',removeTitle:'Remove file',uploadIcon:'',uploadClass:'btn btn-sm btn-kv btn-default btn-outline-secondary',uploadTitle:'Upload file',uploadRetryIcon:'',uploadRetryTitle:'Retry upload',downloadIcon:'',downloadClass:'btn btn-sm btn-kv btn-default btn-outline-secondary',downloadTitle:'Download file',zoomIcon:'',zoomClass:'btn btn-sm btn-kv btn-default btn-outline-secondary',zoomTitle:'View Details',dragIcon:'',dragClass:'text-info',dragTitle:'Move / Rearrange',dragSettings:{},indicatorNew:'',indicatorSuccess:'',indicatorError:'',indicatorLoading:'',indicatorPaused:'',indicatorNewTitle:'Not uploaded yet',indicatorSuccessTitle:'Uploaded',indicatorErrorTitle:'Upload Error',indicatorLoadingTitle:'Uploading ...',indicatorPausedTitle:'Upload Paused'}};$.each(self.defaults,function(key,setting){if(key==='allowedPreviewTypes'){if(self.allowedPreviewTypes===undefined){self.allowedPreviewTypes=setting;}return;}self[key]=$.extend(true,{},setting,self[key]);});self._initPreviewTemplates();},_initPreviewTemplates:function(){var self=this,tags=self.previewMarkupTags,tagBef,tagAft=tags.tagAfter;$.each(self.previewContentTemplates,function(key,value){if($h.isEmpty(self.previewTemplates[key])){tagBef=tags.tagBefore2;if(key==='generic'||key==='image'||key==='html'||key==='text'){tagBef=tags.tagBefore1;}if(self._isPdfRendered()&&key==='pdf'){tagBef=tagBef.replace('kv-file-content','kv-file-content kv-pdf-rendered');}self.previewTemplates[key]=tagBef+value+tagAft;}});},_initPreviewCache:function(){var self=this;self.previewCache={data:{},init:function(){var content=self.initialPreview;if(content.length>0&&!$h.isArray(content)){content=content.split(self.initialPreviewDelimiter);}self.previewCache.data={content:content,config:self.initialPreviewConfig,tags:self.initialPreviewThumbTags};},count:function(skipNull){if(!self.previewCache.data||!self.previewCache.data.content){return 0;}if(skipNull){var chk=self.previewCache.data.content.filter(function(n){return n!==null;});return chk.length;}return self.previewCache.data.content.length;},get:function(i,isDisabled){var ind='init_'+i,data=self.previewCache.data,config=data.config[i],fileId,content=data.content[i],previewId=self.previewInitId+'-'+ind,out,$tmp,cat,ftr,fname,ftype,frameClass,asData=$h.ifSet('previewAsData',config,self.initialPreviewAsData),a=config?{title:config.title||null,alt:config.alt||null}:{title:null,alt:null},parseTemplate=function(cat,dat,fn,ft,id,ftr,ind,fc,t){fc=' file-preview-initial '+$h.SORT_CSS+(fc?' '+fc:'');fileId=config&&config.fileId||'file_'+id;return self._generatePreviewTemplate(cat,dat,fn,ft,id,fileId,false,null,fc,ftr,ind,t,a,config&&config.zoomData||dat);};if(!content||!content.length){return'';}isDisabled=isDisabled===undefined?true:isDisabled;cat=$h.ifSet('type',config,self.initialPreviewFileType||'generic');fname=$h.ifSet('filename',config,$h.ifSet('caption',config));ftype=$h.ifSet('filetype',config,cat);ftr=self.previewCache.footer(i,isDisabled,(config&&config.size||null));frameClass=$h.ifSet('frameClass',config);if(asData){out=parseTemplate(cat,content,fname,ftype,previewId,ftr,ind,frameClass);}else{out=parseTemplate('generic',content,fname,ftype,previewId,ftr,ind,frameClass,cat).setTokens({'content':data.content[i]});}if(data.tags.length&&data.tags[i]){out=$h.replaceTags(out,data.tags[i]);}if(!$h.isEmpty(config)&&!$h.isEmpty(config.frameAttr)){$tmp=$(document.createElement('div')).html(out);$tmp.find('.file-preview-initial').attr(config.frameAttr);out=$tmp.html();$tmp.remove();}return out;},clean:function(data){data.content=$h.cleanArray(data.content);data.config=$h.cleanArray(data.config);data.tags=$h.cleanArray(data.tags);self.previewCache.data=data;},add:function(content,config,tags,append){var data=self.previewCache.data,index=content.length-1;if(!content||!content.length){return index;}if(!$h.isArray(content)){content=content.split(self.initialPreviewDelimiter);}if(append){index=data.content.push(content[0])-1;data.config[index]=config;data.tags[index]=tags;}else{data.content=content;data.config=config;data.tags=tags;}self.previewCache.clean(data);return index;},set:function(content,config,tags,append){var data=self.previewCache.data,i,chk;if(!content||!content.length){return;}if(!$h.isArray(content)){content=content.split(self.initialPreviewDelimiter);}chk=content.filter(function(n){return n!==null;});if(!chk.length){return;}if(data.content===undefined){data.content=[];}if(data.config===undefined){data.config=[];}if(data.tags===undefined){data.tags=[];}if(append){for(i=0;i'+msg+'':'
  • '+msg+'
  • ';if($error.find('ul').length===0){self._addError('
      '+e+'
    ');}else{$error.find('ul').append(e);}$error.fadeIn(800);self._raise(ev,[params,msg]);self._setValidationError('file-input-new');return true;},_showError:function(msg,params,event){var self=this,$error=self.$errorContainer,ev=event||'fileerror';params=params||{};params.reader=self.reader;self._addError(msg);$error.fadeIn(800);self._raise(ev,[params,msg]);if(!self.isAjaxUpload){self._clearFileInput();}self._setValidationError('file-input-new');self.$btnUpload.attr('disabled',true);return true;},_noFilesError:function(params){var self=this,label=self.minFileCount>1?self.filePlural:self.fileSingle,msg=self.msgFilesTooLess.replace('{n}',self.minFileCount).replace('{files}',label),$error=self.$errorContainer;self._addError(msg);self.isError=true;self._updateFileDetails(0);$error.fadeIn(800);self._raise('fileerror',[params,msg]);self._clearFileInput();self._setValidationError();},_parseError:function(operation,jqXHR,errorThrown,fileName){var self=this,errMsg=$.trim(errorThrown+''),textPre,text=jqXHR.responseJSON!==undefined&&jqXHR.responseJSON.error!==undefined?jqXHR.responseJSON.error:jqXHR.responseText;if(self.cancelling&&self.msgUploadAborted){errMsg=self.msgUploadAborted;}if(self.showAjaxErrorDetails&&text){text=$.trim(text.replace(/\n\s*\n/g,'\n'));textPre=text.length?'
    '+text+'
    ':'';errMsg+=errMsg?textPre:text;}if(!errMsg){errMsg=self.msgAjaxError.replace('{operation}',operation);}self.cancelling=false;return fileName?''+fileName+': '+errMsg:errMsg;},_parseFileType:function(type,name){var self=this,isValid,vType,cat,i,types=self.allowedPreviewTypes||[];if(type==='application/text-plain'){return'text';}for(i=0;i-1){ext=fname.split('.').pop();if(self.previewFileIconSettings){out=self.previewFileIconSettings[ext]||self.previewFileIconSettings[ext.toLowerCase()]||null;}if(self.previewFileExtSettings){$.each(self.previewFileExtSettings,function(key,func){if(self.previewFileIconSettings[key]&&func(ext)){out=self.previewFileIconSettings[key];return;}});}}return out;},_parseFilePreviewIcon:function(content,fname){var self=this,icn=self._getPreviewIcon(fname)||self.previewFileIcon,out=content;if(out.indexOf('{previewFileIcon}')>-1){out=out.setTokens({'previewFileIconClass':self.previewFileIconClass,'previewFileIcon':icn});}return out;},_raise:function(event,params){var self=this,e=$.Event(event);if(params!==undefined){self.$element.trigger(e,params);}else{self.$element.trigger(e);}if(e.isDefaultPrevented()||e.result===false){return false;}switch(event){case'filebatchuploadcomplete':case'filebatchuploadsuccess':case'fileuploaded':case'fileclear':case'filecleared':case'filereset':case'fileerror':case'filefoldererror':case'fileuploaderror':case'filebatchuploaderror':case'filedeleteerror':case'filecustomerror':case'filesuccessremove':break;default:if(!self.ajaxAborted){self.ajaxAborted=e.result;}break;}return true;},_listenFullScreen:function(isFullScreen){var self=this,$modal=self.$modal,$btnFull,$btnBord;if(!$modal||!$modal.length){return;}$btnFull=$modal&&$modal.find('.btn-fullscreen');$btnBord=$modal&&$modal.find('.btn-borderless');if(!$btnFull.length||!$btnBord.length){return;}$btnFull.removeClass('active').attr('aria-pressed','false');$btnBord.removeClass('active').attr('aria-pressed','false');if(isFullScreen){$btnFull.addClass('active').attr('aria-pressed','true');}else{$btnBord.addClass('active').attr('aria-pressed','true');}if($modal.hasClass('file-zoom-fullscreen')){self._maximizeZoomDialog();}else{if(isFullScreen){self._maximizeZoomDialog();}else{$btnBord.removeClass('active').attr('aria-pressed','false');}}},_listen:function(){var self=this,$el=self.$element,$form=self.$form,$cont=self.$container,fullScreenEvents;self._handler($el,'click',function(e){if($el.hasClass('file-no-browse')){if($el.data('zoneClicked')){$el.data('zoneClicked',false);}else{e.preventDefault();}}});self._handler($el,'change',$.proxy(self._change,self));if(self.showBrowse){self._handler(self.$btnFile,'click',$.proxy(self._browse,self));}self._handler($cont.find('.fileinput-remove:not([disabled])'),'click',$.proxy(self.clear,self));self._handler($cont.find('.fileinput-cancel'),'click',$.proxy(self.cancel,self));self._handler($cont.find('.fileinput-pause'),'click',$.proxy(self.pause,self));self._initDragDrop();self._handler($form,'reset',$.proxy(self.clear,self));if(!self.isAjaxUpload){self._handler($form,'submit',$.proxy(self._submitForm,self));}self._handler(self.$container.find('.fileinput-upload'),'click',$.proxy(self._uploadClick,self));self._handler($(window),'resize',function(){self._listenFullScreen(screen.width===window.innerWidth&&screen.height===window.innerHeight);});fullScreenEvents='webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';self._handler($(document),fullScreenEvents,function(){self._listenFullScreen($h.checkFullScreen());});self._autoFitContent();self._initClickable();self._refreshPreview();},_autoFitContent:function(){var width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,self=this,config=width<400?(self.previewSettingsSmall||self.defaults.previewSettingsSmall):(self.previewSettings||self.defaults.previewSettings),sel;$.each(config,function(cat,settings){sel='.file-preview-frame .file-preview-'+cat;self.$preview.find(sel+'.kv-preview-data,'+sel+' .kv-preview-data').css(settings);});},_scanDroppedItems:function(item,files,path){path=path||'';var self=this,i,dirReader,readDir,errorHandler=function(e){self._log($h.logMessages.badDroppedFiles);self._log(e);};if(item.isFile){item.file(function(file){files.push(file);},errorHandler);}else{if(item.isDirectory){dirReader=item.createReader();readDir=function(){dirReader.readEntries(function(entries){if(entries&&entries.length>0){for(i=0;i-1;self._zoneDragDropInit(e);if(self.isDisabled||!hasFiles){e.originalEvent.dataTransfer.effectAllowed='none';e.originalEvent.dataTransfer.dropEffect='none';return;}if(self._raise('fileDragEnter',{'sourceEvent':e,'files':dataTransfer.types.Files})){$h.addCss(self.$dropZone,'file-highlighted');}},_zoneDragLeave:function(e){var self=this;self._zoneDragDropInit(e);if(self.isDisabled){return;}if(self._raise('fileDragLeave',{'sourceEvent':e})){self.$dropZone.removeClass('file-highlighted');}},_zoneDrop:function(e){var self=this,i,$el=self.$element,dataTransfer=e.originalEvent.dataTransfer,files=dataTransfer.files,items=dataTransfer.items,folders=$h.getDragDropFolders(items),processFiles=function(){if(!self.isAjaxUpload){self.changeTriggered=true;$el.get(0).files=files;setTimeout(function(){self.changeTriggered=false;$el.trigger('change'+self.namespace);},self.processDelay);}else{self._change(e,files);}self.$dropZone.removeClass('file-highlighted');};e.preventDefault();if(self.isDisabled||$h.isEmpty(files)){return;}if(!self._raise('fileDragDrop',{'sourceEvent':e,'files':files})){return;}if(folders>0){if(!self.isAjaxUpload){self._showFolderError(folders);return;}files=[];for(i=0;i.kv-file-content img');$zoomImg=self.$preview.find('#zoom-'+id+' >.kv-file-content img');self.setImageOrientation($img,$zoomImg,config.exif.Orientation,$thumb);}i++;});},_initPreview:function(isInit){var self=this,cap=self.initialCaption||'',out;if(!self.previewCache.count(true)){self._clearPreview();if(isInit){self._setCaption(cap);}else{self._initCaption();}return;}out=self.previewCache.out();cap=isInit&&self.initialCaption?self.initialCaption:out.caption;self._setPreviewContent(out.content);self._setInitThumbAttr();self._setCaption(cap);self._initSortable();if(!$h.isEmpty(out.content)){self.$container.removeClass('file-input-new');}self._initPreviewImageOrientations();},_getZoomButton:function(type){var self=this,label=self.previewZoomButtonIcons[type],css=self.previewZoomButtonClasses[type],title=' title="'+(self.previewZoomButtonTitles[type]||'')+'" ',params=title+(type==='close'?' data-dismiss="modal" aria-hidden="true"':'');if(type==='fullscreen'||type==='borderless'||type==='toggleheader'){params+=' data-toggle="button" aria-pressed="false" autocomplete="off"';}return'';},_getModalContent:function(){var self=this;return self._getLayoutTemplate('modal').setTokens({'rtl':self.rtl?' kv-rtl':'','zoomFrameClass':self.frameClass,'heading':self.msgZoomModalHeading,'prev':self._getZoomButton('prev'),'next':self._getZoomButton('next'),'toggleheader':self._getZoomButton('toggleheader'),'fullscreen':self._getZoomButton('fullscreen'),'borderless':self._getZoomButton('borderless'),'close':self._getZoomButton('close')});},_listenModalEvent:function(event){var self=this,$modal=self.$modal,getParams=function(e){return{sourceEvent:e,previewId:$modal.data('previewId'),modal:$modal};};$modal.on(event+'.bs.modal',function(e){var $btnFull=$modal.find('.btn-fullscreen'),$btnBord=$modal.find('.btn-borderless');self._raise('filezoom'+event,getParams(e));if(event==='shown'){$btnBord.removeClass('active').attr('aria-pressed','false');$btnFull.removeClass('active').attr('aria-pressed','false');if($modal.hasClass('file-zoom-fullscreen')){self._maximizeZoomDialog();if($h.checkFullScreen()){$btnFull.addClass('active').attr('aria-pressed','true');}else{$btnBord.addClass('active').attr('aria-pressed','true');}}}});},_initZoom:function(){var self=this,$dialog,modalMain=self._getLayoutTemplate('modalMain'),modalId='#'+$h.MODAL_ID;if(!self.showPreview){return;}self.$modal=$(modalId);if(!self.$modal||!self.$modal.length){$dialog=$(document.createElement('div')).html(modalMain).insertAfter(self.$container);self.$modal=$(modalId).insertBefore($dialog);$dialog.remove();}$h.initModal(self.$modal);self.$modal.html(self._getModalContent());$.each($h.MODAL_EVENTS,function(key,event){self._listenModalEvent(event);});},_initZoomButtons:function(){var self=this,previewId=self.$modal.data('previewId')||'',$first,$last,thumbs=self.getFrames().toArray(),len=thumbs.length,$prev=self.$modal.find('.btn-prev'),$next=self.$modal.find('.btn-next');if(thumbs.length<2){$prev.hide();$next.hide();return;}else{$prev.show();$next.show();}if(!len){return;}$first=$(thumbs[0]);$last=$(thumbs[len-1]);$prev.removeAttr('disabled');$next.removeAttr('disabled');if($first.length&&$first.attr('id')===previewId){$prev.attr('disabled',true);}if($last.length&&$last.attr('id')===previewId){$next.attr('disabled',true);}},_maximizeZoomDialog:function(){var self=this,$modal=self.$modal,$head=$modal.find('.modal-header:visible'),$foot=$modal.find('.modal-footer:visible'),$body=$modal.find('.modal-body'),h=$(window).height(),diff=0;$modal.addClass('file-zoom-fullscreen');if($head&&$head.length){h-=$head.outerHeight(true);}if($foot&&$foot.length){h-=$foot.outerHeight(true);}if($body&&$body.length){diff=$body.outerHeight(true)-$body.height();h-=diff;}$modal.find('.kv-zoom-body').height(h);},_resizeZoomDialog:function(fullScreen){var self=this,$modal=self.$modal,$btnFull=$modal.find('.btn-fullscreen'),$btnBord=$modal.find('.btn-borderless');if($modal.hasClass('file-zoom-fullscreen')){$h.toggleFullScreen(false);if(!fullScreen){if(!$btnFull.hasClass('active')){$modal.removeClass('file-zoom-fullscreen');self.$modal.find('.kv-zoom-body').css('height',self.zoomModalHeight);}else{$btnFull.removeClass('active').attr('aria-pressed','false');}}else{if(!$btnFull.hasClass('active')){$modal.removeClass('file-zoom-fullscreen');self._resizeZoomDialog(true);if($btnBord.hasClass('active')){$btnBord.removeClass('active').attr('aria-pressed','false');}}}}else{if(!fullScreen){self._maximizeZoomDialog();return;}$h.toggleFullScreen(true);}$modal.focus();},_setZoomContent:function($frame,animate){var self=this,$content,tmplt,body,title,$body,$dataEl,config,previewId=$frame.attr('id'),$zoomPreview=self.$preview.find('#zoom-'+previewId),$modal=self.$modal,$tmp,$btnFull=$modal.find('.btn-fullscreen'),$btnBord=$modal.find('.btn-borderless'),cap,size,$btnTogh=$modal.find('.btn-toggleheader');tmplt=$zoomPreview.attr('data-template')||'generic';$content=$zoomPreview.find('.kv-file-content');body=$content.length?$content.html():'';cap=$frame.data('caption')||'';size=$frame.data('size')||'';title=cap+' '+size;$modal.find('.kv-zoom-title').attr('title',$('
    ').html(title).text()).html(title);$body=$modal.find('.kv-zoom-body');$modal.removeClass('kv-single-content');if(animate){$tmp=$body.addClass('file-thumb-loading').clone().insertAfter($body);$body.html(body).hide();$tmp.fadeOut('fast',function(){$body.fadeIn('fast',function(){$body.removeClass('file-thumb-loading');});$tmp.remove();});}else{$body.html(body);}config=self.previewZoomSettings[tmplt];if(config){$dataEl=$body.find('.kv-preview-data');$h.addCss($dataEl,'file-zoom-detail');$.each(config,function(key,value){$dataEl.css(key,value);if(($dataEl.attr('width')&&key==='width')||($dataEl.attr('height')&&key==='height')){$dataEl.removeAttr(key);}});}$modal.data('previewId',previewId);self._handler($modal.find('.btn-prev'),'click',function(){self._zoomSlideShow('prev',previewId);});self._handler($modal.find('.btn-next'),'click',function(){self._zoomSlideShow('next',previewId);});self._handler($btnFull,'click',function(){self._resizeZoomDialog(true);});self._handler($btnBord,'click',function(){self._resizeZoomDialog(false);});self._handler($btnTogh,'click',function(){var $header=$modal.find('.modal-header'),$floatBar=$modal.find('.modal-body .floating-buttons'),ht,$actions=$header.find('.kv-zoom-actions'),resize=function(height){var $body=self.$modal.find('.kv-zoom-body'),h=self.zoomModalHeight;if($modal.hasClass('file-zoom-fullscreen')){h=$body.outerHeight(true);if(!height){h=h-$header.outerHeight(true);}}$body.css('height',height?h+height:h);};if($header.is(':visible')){ht=$header.outerHeight(true);$header.slideUp('slow',function(){$actions.find('.btn').appendTo($floatBar);resize(ht);});}else{$floatBar.find('.btn').appendTo($actions);$header.slideDown('slow',function(){resize();});}$modal.focus();});self._handler($modal,'keydown',function(e){var key=e.which||e.keyCode,$prev=$(this).find('.btn-prev'),$next=$(this).find('.btn-next'),vId=$(this).data('previewId'),vPrevKey=self.rtl?39:37,vNextKey=self.rtl?37:39;if(key===vPrevKey&&$prev.length&&!$prev.attr('disabled')){self._zoomSlideShow('prev',vId);}if(key===vNextKey&&$next.length&&!$next.attr('disabled')){self._zoomSlideShow('next',vId);}});},_zoomPreview:function($btn){var self=this,$frame,$modal=self.$modal;if(!$btn.length){throw'Cannot zoom to detailed preview!';}$h.initModal($modal);$modal.html(self._getModalContent());$frame=$btn.closest($h.FRAMES);self._setZoomContent($frame);$modal.modal('show');self._initZoomButtons();},_zoomSlideShow:function(dir,previewId){var self=this,$btn=self.$modal.find('.kv-zoom-actions .btn-'+dir),$targFrame,i,thumbs=self.getFrames().toArray(),len=thumbs.length,out;if($btn.attr('disabled')){return;}for(i=0;i=len||!thumbs[out]){return;}$targFrame=$(thumbs[out]);if($targFrame.length){self._setZoomContent($targFrame,true);}self._initZoomButtons();self._raise('filezoom'+dir,{'previewId':previewId,modal:self.$modal});},_initZoomButton:function(){var self=this;self.$preview.find('.kv-file-zoom').each(function(){var $el=$(this);self._handler($el,'click',function(){self._zoomPreview($el);});});},_inputFileCount:function(){return this.$element.get(0).files.length;},_refreshPreview:function(){var self=this,files;if((!self._inputFileCount()&&!self.isAjaxUpload)||!self.showPreview||!self.isPreviewable){return;}if(self.isAjaxUpload){if(self.fileManager.count()>0){files=$.extend(true,{},self.fileManager.stack);self.fileManager.clear();self._clearFileInput();}else{files=self.$element.get(0).files;}}else{files=self.$element.get(0).files;}if(files&&files.length){self.readFiles(files);self._setFileDropZoneTitle();}},_clearObjects:function($el){$el.find('video audio').each(function(){this.pause();$(this).remove();});$el.find('img object div').each(function(){$(this).remove();});},_clearFileInput:function(){var self=this,$el=self.$element,$srcFrm,$tmpFrm,$tmpEl;if(!self._inputFileCount()){return;}$srcFrm=$el.closest('form');$tmpFrm=$(document.createElement('form'));$tmpEl=$(document.createElement('div'));$el.before($tmpEl);if($srcFrm.length){$srcFrm.after($tmpFrm);}else{$tmpEl.after($tmpFrm);}$tmpFrm.append($el).trigger('reset');$tmpEl.before($el).remove();$tmpFrm.remove();},_resetUpload:function(){var self=this;self.uploadCache={content:[],config:[],tags:[],append:true};self.$btnUpload.removeAttr('disabled');self._setProgress(0);self.$progress.hide();self._resetErrors(false);self._initAjax();self.fileManager.clearImages();self._resetCanvas();self.cacheInitialPreview={};if(self.overwriteInitial){self.initialPreview=[];self.initialPreviewConfig=[];self.initialPreviewThumbTags=[];self.previewCache.data={content:[],config:[],tags:[]};}},_resetCanvas:function(){var self=this;if(self.canvas&&self.imageCanvasContext){self.imageCanvasContext.clearRect(0,0,self.canvas.width,self.canvas.height);}},_hasInitialPreview:function(){var self=this;return!self.overwriteInitial&&self.previewCache.count(true);},_resetPreview:function(){var self=this,out,cap;if(self.previewCache.count(true)){out=self.previewCache.out();self._setPreviewContent(out.content);self._setInitThumbAttr();cap=self.initialCaption?self.initialCaption:out.caption;self._setCaption(cap);}else{self._clearPreview();self._initCaption();}if(self.showPreview){self._initZoom();self._initSortable();}},_clearDefaultPreview:function(){var self=this;self.$preview.find('.file-default-preview').remove();},_validateDefaultPreview:function(){var self=this;if(!self.showPreview||$h.isEmpty(self.defaultPreviewContent)){return;}self._setPreviewContent('
    '+self.defaultPreviewContent+'
    ');self.$container.removeClass('file-input-new');self._initClickable();},_resetPreviewThumbs:function(isAjax){var self=this,out;if(isAjax){self._clearPreview();self.clearFileStack();return;}if(self._hasInitialPreview()){out=self.previewCache.out();self._setPreviewContent(out.content);self._setInitThumbAttr();self._setCaption(out.caption);self._initPreviewActions();}else{self._clearPreview();}},_getLayoutTemplate:function(t){var self=this,template=self.layoutTemplates[t];if($h.isEmpty(self.customLayoutTags)){return template;}return $h.replaceTags(template,self.customLayoutTags);},_getPreviewTemplate:function(t){var self=this,template=self.previewTemplates[t];if($h.isEmpty(self.customPreviewTags)){return template;}return $h.replaceTags(template,self.customPreviewTags);},_getOutData:function(formdata,jqXHR,responseData,filesData){var self=this;jqXHR=jqXHR||{};responseData=responseData||{};filesData=filesData||self.fileManager.list();return{formdata:formdata,files:filesData,filenames:self.filenames,filescount:self.getFilesCount(),extra:self._getExtraData(),response:responseData,reader:self.reader,jqXHR:jqXHR};},_getMsgSelected:function(n){var self=this,strFiles=n===1?self.fileSingle:self.filePlural;return n>0?self.msgSelected.replace('{n}',n).replace('{files}',strFiles):self.msgNoFilesSelected;},_getFrame:function(id){var self=this,$frame=$('#'+id);if(!$frame.length){self._log($h.logMessages.invalidThumb,{id:id});return null;}return $frame;},_getThumbs:function(css){css=css||'';return this.getFrames(':not(.file-preview-initial)'+css);},_getExtraData:function(fileId,index){var self=this,data=self.uploadExtraData;if(typeof self.uploadExtraData==='function'){data=self.uploadExtraData(fileId,index);}return data;},_initXhr:function(xhrobj,fileId,fileCount){var self=this,fm=self.fileManager,func=function(event){var pct=0,total=event.total,loaded=event.loaded||event.position,stats=fm.getUploadStats(fileId,loaded,total);if(event.lengthComputable&&!self.enableResumableUpload){pct=$h.round(loaded/total*100);}if(fileId){self._setFileUploadStats(fileId,pct,fileCount,stats);}else{self._setProgress(pct,null,null,self._getStats(stats));}self._raise('fileajaxprogress',[stats]);};if(xhrobj.upload){if(self.progressDelay){func=$h.debounce(func,self.progressDelay);}xhrobj.upload.addEventListener('progress',func,false);}return xhrobj;},_initAjaxSettings:function(){var self=this;self._ajaxSettings=$.extend(true,{},self.ajaxSettings);self._ajaxDeleteSettings=$.extend(true,{},self.ajaxDeleteSettings);},_mergeAjaxCallback:function(funcName,srcFunc,type){var self=this,settings=self._ajaxSettings,flag=self.mergeAjaxCallbacks,targFunc;if(type==='delete'){settings=self._ajaxDeleteSettings;flag=self.mergeAjaxDeleteCallbacks;}targFunc=settings[funcName];if(flag&&typeof targFunc==='function'){if(flag==='before'){settings[funcName]=function(){targFunc.apply(this,arguments);srcFunc.apply(this,arguments);};}else{settings[funcName]=function(){srcFunc.apply(this,arguments);targFunc.apply(this,arguments);};}}else{settings[funcName]=srcFunc;}},_ajaxSubmit:function(fnBefore,fnSuccess,fnComplete,fnError,formdata,fileId,index,vUrl){var self=this,settings,defaults,data,processQueue;if(!self._raise('filepreajax',[formdata,fileId,index])){return;}formdata.append('initialPreview',JSON.stringify(self.initialPreview));formdata.append('initialPreviewConfig',JSON.stringify(self.initialPreviewConfig));formdata.append('initialPreviewThumbTags',JSON.stringify(self.initialPreviewThumbTags));self._initAjaxSettings();self._mergeAjaxCallback('beforeSend',fnBefore);self._mergeAjaxCallback('success',fnSuccess);self._mergeAjaxCallback('complete',fnComplete);self._mergeAjaxCallback('error',fnError);vUrl=vUrl||self.uploadUrlThumb||self.uploadUrl;if(typeof vUrl==='function'){vUrl=vUrl();}data=self._getExtraData(fileId,index)||{};if(typeof data==='object'){$.each(data,function(key,value){formdata.append(key,value);});}defaults={xhr:function(){var xhrobj=$.ajaxSettings.xhr();return self._initXhr(xhrobj,fileId,self.fileManager.count());},url:self._encodeURI(vUrl),type:'POST',dataType:'json',data:formdata,cache:false,processData:false,contentType:false};settings=$.extend(true,{},defaults,self._ajaxSettings);self.ajaxQueue.push(settings);processQueue=function(){var config,xhr;if(self.ajaxCurrentThreads0){self.hasInitData=true;content=out.initialPreview||[];config=out.initialPreviewConfig||[];tags=out.initialPreviewThumbTags||[];append=out.append===undefined||out.append;if(content.length>0&&!$h.isArray(content)){content=content.split(self.initialPreviewDelimiter);}if(content.length){self._mergeArray('initialPreview',content);self._mergeArray('initialPreviewConfig',config);self._mergeArray('initialPreviewThumbTags',tags);}if($thumb!==undefined){if(!allFiles){index=self.previewCache.add(content[0],config[0],tags[0],append);data=self.previewCache.get(index,false);$div=$(document.createElement('div')).html(data).hide().insertAfter($thumb);$newCache=$div.find('.kv-zoom-cache');if($newCache&&$newCache.length){$newCache.insertAfter($thumb);}$thumb.fadeOut('slow',function(){var $newThumb=$div.find('.file-preview-frame');if($newThumb&&$newThumb.length){$newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');}self._initPreviewActions();self._clearFileInput();$h.cleanZoomCache(self.$preview.find('#zoom-'+$thumb.attr('id')));$thumb.remove();$div.remove();self._initSortable();});}else{i=$thumb.attr('data-fileindex');self.uploadCache.content[i]=content[0];self.uploadCache.config[i]=config[0]||[];self.uploadCache.tags[i]=tags[0]||[];self.uploadCache.append=append;}}else{self.previewCache.set(content,config,tags,append);self._initPreview();self._initPreviewActions();}}},_initSuccessThumbs:function(){var self=this;if(!self.showPreview){return;}self._getThumbs($h.FRAMES+'.file-preview-success').each(function(){var $thumb=$(this),$preview=self.$preview,$remove=$thumb.find('.kv-file-remove');$remove.removeAttr('disabled');self._handler($remove,'click',function(){var id=$thumb.attr('id'),out=self._raise('filesuccessremove',[id,$thumb.attr('data-fileindex')]);$h.cleanMemory($thumb);if(out===false){return;}$thumb.fadeOut('slow',function(){$h.cleanZoomCache($preview.find('#zoom-'+id));$thumb.remove();if(!self.getFrames().length){self.reset();}});});});},_updateInitialPreview:function(){var self=this,u=self.uploadCache,i,j,len=0,data=self.cacheInitialPreview;if(data&&data.content){len=data.content.length;}if(self.showPreview){self.previewCache.set(u.content,u.config,u.tags,u.append);if(len){for(i=0;i0||!$.isEmptyObject(self.uploadExtraData),uploadFailed,$prog,fnBefore,errMsg,fnSuccess,fnComplete,fnError,updateUploadLog,op=self.ajaxOperations.uploadThumb,fileObj=fm.getFile(id),params={id:previewId,index:i,fileId:id},fileName=self.fileManager.getFileName(id,true);if(self.enableResumableUpload){return;}if(self.showPreview){$thumb=self.fileManager.getThumb(id);$prog=$thumb.find('.file-thumb-progress');$btnUpload=$thumb.find('.kv-file-upload');$btnDelete=$thumb.find('.kv-file-remove');$prog.show();}if(count===0||!hasPostData||(self.showPreview&&$btnUpload&&$btnUpload.hasClass('disabled'))||self._abort(params)){return;}updateUploadLog=function(){if(!uploadFailed){fm.removeFile(id);}else{fm.errors.push(id);}fm.setProcessed(id);if(fm.isProcessed()){self.fileBatchCompleted=true;}};chkComplete=function(){var $initThumbs;if(!self.fileBatchCompleted){return;}setTimeout(function(){var triggerReset=fm.count()===0,errCount=fm.errors.length;self._updateInitialPreview();self.unlock(triggerReset);if(triggerReset){self._clearFileInput();}$initThumbs=self.$preview.find('.file-preview-initial');if(self.uploadAsync&&$initThumbs.length){$h.addCss($initThumbs,$h.SORT_CSS);self._initSortable();}self._raise('filebatchuploadcomplete',[fm.stack,self._getExtraData()]);if(!self.retryErrorUploads||errCount===0){fm.clear();}self._setProgress(101);self.ajaxAborted=false;},self.processDelay);};fnBefore=function(jqXHR){outData=self._getOutData(formdata,jqXHR);fm.initStats(id);self.fileBatchCompleted=false;if(!isBatch){self.ajaxAborted=false;}if(self.showPreview){if(!$thumb.hasClass('file-preview-success')){self._setThumbStatus($thumb,'Loading');$h.addCss($thumb,'file-uploading');}$btnUpload.attr('disabled',true);$btnDelete.attr('disabled',true);}if(!isBatch){self.lock();}if(fm.errors.indexOf(id)!==-1){delete fm.errors[id];}self._raise('filepreupload',[outData,previewId,i]);$.extend(true,params,outData);if(self._abort(params)){jqXHR.abort();if(!isBatch){self._setThumbStatus($thumb,'New');$thumb.removeClass('file-uploading');$btnUpload.removeAttr('disabled');$btnDelete.removeAttr('disabled');self.unlock();}self._setProgressCancelled();}};fnSuccess=function(data,textStatus,jqXHR){var pid=self.showPreview&&$thumb.attr('id')?$thumb.attr('id'):previewId;outData=self._getOutData(formdata,jqXHR,data);$.extend(true,params,outData);setTimeout(function(){if($h.isEmpty(data)||$h.isEmpty(data.error)){if(self.showPreview){self._setThumbStatus($thumb,'Success');$btnUpload.hide();self._initUploadSuccess(data,$thumb,isBatch);self._setProgress(101,$prog);}self._raise('fileuploaded',[outData,pid,i]);if(!isBatch){self.fileManager.remove($thumb);}else{updateUploadLog();}}else{uploadFailed=true;errMsg=self._parseError(op,jqXHR,self.msgUploadError,self.fileManager.getFileName(id));self._showFileError(errMsg,params);self._setPreviewError($thumb,true);if(!self.retryErrorUploads){$btnUpload.hide();}if(isBatch){updateUploadLog();}self._setProgress(101,$('#'+pid).find('.file-thumb-progress'),self.msgUploadError);}},self.processDelay);};fnComplete=function(){setTimeout(function(){if(self.showPreview){$btnUpload.removeAttr('disabled');$btnDelete.removeAttr('disabled');$thumb.removeClass('file-uploading');}if(!isBatch){self.unlock(false);self._clearFileInput();}else{chkComplete();}self._initSuccessThumbs();},self.processDelay);};fnError=function(jqXHR,textStatus,errorThrown){errMsg=self._parseError(op,jqXHR,errorThrown,self.fileManager.getFileName(id));uploadFailed=true;setTimeout(function(){if(isBatch){updateUploadLog();}self.fileManager.setProgress(id,100);self._setPreviewError($thumb,true);if(!self.retryErrorUploads){$btnUpload.hide();}$.extend(true,params,self._getOutData(formdata,jqXHR));self._setProgress(101,$prog,self.msgAjaxProgressError.replace('{operation}',op));self._setProgress(101,$thumb.find('.file-thumb-progress'),self.msgUploadError);self._showFileError(errMsg,params);},self.processDelay);};formdata.append(self.uploadFileAttr,fileObj.file,fileName);self._setUploadData(formdata,{fileId:id});self._ajaxSubmit(fnBefore,fnSuccess,fnComplete,fnError,formdata,id,i);},_uploadBatch:function(){var self=this,fm=self.fileManager,total=fm.total(),params={},fnBefore,fnSuccess,fnError,fnComplete,hasPostData=total>0||!$.isEmptyObject(self.uploadExtraData),errMsg,setAllUploaded,formdata=new FormData(),op=self.ajaxOperations.uploadBatch;if(total===0||!hasPostData||self._abort(params)){return;}setAllUploaded=function(){self.fileManager.clear();self._clearFileInput();};fnBefore=function(jqXHR){self.lock();fm.initStats();var outData=self._getOutData(formdata,jqXHR);self.ajaxAborted=false;if(self.showPreview){self._getThumbs().each(function(){var $thumb=$(this),$btnUpload=$thumb.find('.kv-file-upload'),$btnDelete=$thumb.find('.kv-file-remove');if(!$thumb.hasClass('file-preview-success')){self._setThumbStatus($thumb,'Loading');$h.addCss($thumb,'file-uploading');}$btnUpload.attr('disabled',true);$btnDelete.attr('disabled',true);});}self._raise('filebatchpreupload',[outData]);if(self._abort(outData)){jqXHR.abort();self._getThumbs().each(function(){var $thumb=$(this),$btnUpload=$thumb.find('.kv-file-upload'),$btnDelete=$thumb.find('.kv-file-remove');if($thumb.hasClass('file-preview-loading')){self._setThumbStatus($thumb,'New');$thumb.removeClass('file-uploading');}$btnUpload.removeAttr('disabled');$btnDelete.removeAttr('disabled');});self._setProgressCancelled();}};fnSuccess=function(data,textStatus,jqXHR){var outData=self._getOutData(formdata,jqXHR,data),key=0,$thumbs=self._getThumbs(':not(.file-preview-success)'),keys=$h.isEmpty(data)||$h.isEmpty(data.errorkeys)?[]:data.errorkeys;if($h.isEmpty(data)||$h.isEmpty(data.error)){self._raise('filebatchuploadsuccess',[outData]);setAllUploaded();if(self.showPreview){$thumbs.each(function(){var $thumb=$(this);self._setThumbStatus($thumb,'Success');$thumb.removeClass('file-uploading');$thumb.find('.kv-file-upload').hide().removeAttr('disabled');});self._initUploadSuccess(data);}else{self.reset();}self._setProgress(101);}else{if(self.showPreview){$thumbs.each(function(){var $thumb=$(this);$thumb.removeClass('file-uploading');$thumb.find('.kv-file-upload').removeAttr('disabled');$thumb.find('.kv-file-remove').removeAttr('disabled');if(keys.length===0||$.inArray(key,keys)!==-1){self._setPreviewError($thumb,true);if(!self.retryErrorUploads){$thumb.find('.kv-file-upload').hide();self.fileManager.remove($thumb);}}else{$thumb.find('.kv-file-upload').hide();self._setThumbStatus($thumb,'Success');self.fileManager.remove($thumb);}if(!$thumb.hasClass('file-preview-error')||self.retryErrorUploads){key++;}});self._initUploadSuccess(data);}errMsg=self._parseError(op,jqXHR,self.msgUploadError);self._showFileError(errMsg,outData,'filebatchuploaderror');self._setProgress(101,self.$progress,self.msgUploadError);}};fnComplete=function(){self.unlock();self._initSuccessThumbs();self._clearFileInput();self._raise('filebatchuploadcomplete',[self.fileManager.stack,self._getExtraData()]);};fnError=function(jqXHR,textStatus,errorThrown){var outData=self._getOutData(formdata,jqXHR);errMsg=self._parseError(op,jqXHR,errorThrown);self._showFileError(errMsg,outData,'filebatchuploaderror');self.uploadFileCount=total-1;if(!self.showPreview){return;}self._getThumbs().each(function(){var $thumb=$(this);$thumb.removeClass('file-uploading');if(self.fileManager.getFile($thumb.attr('data-fileid'))){self._setPreviewError($thumb);}});self._getThumbs().removeClass('file-uploading');self._getThumbs(' .kv-file-upload').removeAttr('disabled');self._getThumbs(' .kv-file-delete').removeAttr('disabled');self._setProgress(101,self.$progress,self.msgAjaxProgressError.replace('{operation}',op));};var ctr=0;$.each(self.fileManager.stack,function(key,data){if(!$h.isEmpty(data.file)){formdata.append(self.uploadFileAttr,data.file,(data.nameFmt||('untitled_'+ctr)));}ctr++;});self._ajaxSubmit(fnBefore,fnSuccess,fnComplete,fnError,formdata);},_uploadExtraOnly:function(){var self=this,params={},fnBefore,fnSuccess,fnComplete,fnError,formdata=new FormData(),errMsg,op=self.ajaxOperations.uploadExtra;if(self._abort(params)){return;}fnBefore=function(jqXHR){self.lock();var outData=self._getOutData(formdata,jqXHR);self._raise('filebatchpreupload',[outData]);self._setProgress(50);params.data=outData;params.xhr=jqXHR;if(self._abort(params)){jqXHR.abort();self._setProgressCancelled();}};fnSuccess=function(data,textStatus,jqXHR){var outData=self._getOutData(formdata,jqXHR,data);if($h.isEmpty(data)||$h.isEmpty(data.error)){self._raise('filebatchuploadsuccess',[outData]);self._clearFileInput();self._initUploadSuccess(data);self._setProgress(101);}else{errMsg=self._parseError(op,jqXHR,self.msgUploadError);self._showFileError(errMsg,outData,'filebatchuploaderror');}};fnComplete=function(){self.unlock();self._clearFileInput();self._raise('filebatchuploadcomplete',[self.fileManager.stack,self._getExtraData()]);};fnError=function(jqXHR,textStatus,errorThrown){var outData=self._getOutData(formdata,jqXHR);errMsg=self._parseError(op,jqXHR,errorThrown);params.data=outData;self._showFileError(errMsg,outData,'filebatchuploaderror');self._setProgress(101,self.$progress,self.msgAjaxProgressError.replace('{operation}',op));};self._ajaxSubmit(fnBefore,fnSuccess,fnComplete,fnError,formdata);},_deleteFileIndex:function($frame){var self=this,ind=$frame.attr('data-fileindex'),rev=self.reversePreviewOrder;if(ind.substring(0,5)==='init_'){ind=parseInt(ind.replace('init_',''));self.initialPreview=$h.spliceArray(self.initialPreview,ind,rev);self.initialPreviewConfig=$h.spliceArray(self.initialPreviewConfig,ind,rev);self.initialPreviewThumbTags=$h.spliceArray(self.initialPreviewThumbTags,ind,rev);self.getFrames().each(function(){var $nFrame=$(this),nInd=$nFrame.attr('data-fileindex');if(nInd.substring(0,5)==='init_'){nInd=parseInt(nInd.replace('init_',''));if(nInd>ind){nInd--;$nFrame.attr('data-fileindex','init_'+nInd);}}});if(self.uploadAsync||self.enableResumableUpload){self.cacheInitialPreview=self.getPreview();}}},_initFileActions:function(){var self=this,$preview=self.$preview;if(!self.showPreview){return;}self._initZoomButton();self.getFrames(' .kv-file-remove').each(function(){var $el=$(this),$frame=$el.closest($h.FRAMES),hasError,id=$frame.attr('id'),ind=$frame.attr('data-fileindex'),n,cap,status;self._handler($el,'click',function(){status=self._raise('filepreremove',[id,ind]);if(status===false||!self._validateMinCount()){return false;}hasError=$frame.hasClass('file-preview-error');$h.cleanMemory($frame);$frame.fadeOut('slow',function(){$h.cleanZoomCache($preview.find('#zoom-'+id));self.fileManager.remove($frame);self._clearObjects($frame);$frame.remove();if(id&&hasError){self.$errorContainer.find('li[data-thumb-id="'+id+'"]').fadeOut('fast',function(){$(this).remove();if(!self._errorsExist()){self._resetErrors();}});}self._clearFileInput();var chk=self.previewCache.count(true),len=self.fileManager.count(),file,hasThumb=self.showPreview&&self.getFrames().length;if(len===0&&chk===0&&!hasThumb){self.reset();}else{n=chk+len;if(n>1){cap=self._getMsgSelected(n);}else{file=self.fileManager.getFirstFile();cap=file?file.nameFmt:'_';}self._setCaption(cap);}self._raise('fileremoved',[id,ind]);});});});self.getFrames(' .kv-file-upload').each(function(){var $el=$(this);self._handler($el,'click',function(){var $frame=$el.closest($h.FRAMES),id=$frame.attr('data-fileid');self.$progress.hide();if($frame.hasClass('file-preview-error')&&!self.retryErrorUploads){return;}self._uploadSingle(self.fileManager.getIndex(id),id,false);});});},_initPreviewActions:function(){var self=this,$preview=self.$preview,deleteExtraData=self.deleteExtraData||{},btnRemove=$h.FRAMES+' .kv-file-remove',settings=self.fileActionSettings,origClass=settings.removeClass,errClass=settings.removeErrorClass,resetProgress=function(){var hasFiles=self.isAjaxUpload?self.previewCache.count(true):self._inputFileCount();if(!self.getFrames().length&&!hasFiles){self._setCaption('');self.reset();self.initialCaption='';}};self._initZoomButton();$preview.find(btnRemove).each(function(){var $el=$(this),vUrl=$el.data('url')||self.deleteUrl,vKey=$el.data('key'),errMsg,fnBefore,fnSuccess,fnError,op=self.ajaxOperations.deleteThumb;if($h.isEmpty(vUrl)||vKey===undefined){return;}if(typeof vUrl==='function'){vUrl=vUrl();}var $frame=$el.closest($h.FRAMES),cache=self.previewCache.data,settings,params,config,fileName,extraData,index=$frame.attr('data-fileindex');index=parseInt(index.replace('init_',''));config=$h.isEmpty(cache.config)&&$h.isEmpty(cache.config[index])?null:cache.config[index];extraData=$h.isEmpty(config)||$h.isEmpty(config.extra)?deleteExtraData:config.extra;fileName=config.filename||config.caption||'';if(typeof extraData==='function'){extraData=extraData();}params={id:$el.attr('id'),key:vKey,extra:extraData};fnBefore=function(jqXHR){self.ajaxAborted=false;self._raise('filepredelete',[vKey,jqXHR,extraData]);if(self._abort()){jqXHR.abort();}else{$el.removeClass(errClass);$h.addCss($frame,'file-uploading');$h.addCss($el,'disabled '+origClass);}};fnSuccess=function(data,textStatus,jqXHR){var n,cap;if(!$h.isEmpty(data)&&!$h.isEmpty(data.error)){params.jqXHR=jqXHR;params.response=data;errMsg=self._parseError(op,jqXHR,self.msgDeleteError,fileName);self._showFileError(errMsg,params,'filedeleteerror');$frame.removeClass('file-uploading');$el.removeClass('disabled '+origClass).addClass(errClass);resetProgress();return;}$frame.removeClass('file-uploading').addClass('file-deleted');$frame.fadeOut('slow',function(){index=parseInt(($frame.attr('data-fileindex')).replace('init_',''));self.previewCache.unset(index);self._deleteFileIndex($frame);n=self.previewCache.count(true);cap=n>0?self._getMsgSelected(n):'';self._setCaption(cap);self._raise('filedeleted',[vKey,jqXHR,extraData]);$h.cleanZoomCache($preview.find('#zoom-'+$frame.attr('id')));self._clearObjects($frame);$frame.remove();resetProgress();});};fnError=function(jqXHR,textStatus,errorThrown){var errMsg=self._parseError(op,jqXHR,errorThrown,fileName);params.jqXHR=jqXHR;params.response={};self._showFileError(errMsg,params,'filedeleteerror');$frame.removeClass('file-uploading');$el.removeClass('disabled '+origClass).addClass(errClass);resetProgress();};self._initAjaxSettings();self._mergeAjaxCallback('beforeSend',fnBefore,'delete');self._mergeAjaxCallback('success',fnSuccess,'delete');self._mergeAjaxCallback('error',fnError,'delete');settings=$.extend(true,{},{url:self._encodeURI(vUrl),type:'POST',dataType:'json',data:$.extend(true,{},{key:vKey},extraData)},self._ajaxDeleteSettings);self._handler($el,'click',function(){if(!self._validateMinCount()){return false;}self.ajaxAborted=false;self._raise('filebeforedelete',[vKey,extraData]);if(self.ajaxAborted instanceof Promise){self.ajaxAborted.then(function(result){if(!result){$.ajax(settings);}});}else{if(!self.ajaxAborted){$.ajax(settings);}}});});},_hideFileIcon:function(){var self=this;if(self.overwriteInitial){self.$captionContainer.removeClass('icon-visible');}},_showFileIcon:function(){var self=this;$h.addCss(self.$captionContainer,'icon-visible');},_getSize:function(bytes,sizes){var self=this,size=parseFloat(bytes),i,func=self.fileSizeGetter,out;if(!$.isNumeric(bytes)||!$.isNumeric(size)){return'';}if(typeof func==='function'){out=func(size);}else{if(size===0){out='0.00 B';}else{i=Math.floor(Math.log(size)/Math.log(1024));if(!sizes){sizes=['B','KB','MB','GB','TB','PB','EB','ZB','YB'];}out=(size/Math.pow(1024,i)).toFixed(2)*1+' '+sizes[i];}}return self._getLayoutTemplate('size').replace('{sizeText}',out);},_getFileType:function(ftype){var self=this;return self.mimeTypeAliases[ftype]||ftype;},_generatePreviewTemplate:function(cat,data,fname,ftype,previewId,fileId,isError,size,frameClass,foot,ind,templ,attrs,zoomData){var self=this,caption=self.slug(fname),prevContent,zoomContent='',styleAttribs='',screenW=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,config,newCat=self.preferIconicPreview?'other':cat,title=caption,alt=caption,footer=foot||self._renderFileFooter(cat,caption,size,'auto',isError),hasIconSetting=self._getPreviewIcon(fname),typeCss='type-default',forcePrevIcon=hasIconSetting&&self.preferIconicPreview,forceZoomIcon=hasIconSetting&&self.preferIconicZoomPreview,getContent;config=screenW<400?(self.previewSettingsSmall[newCat]||self.defaults.previewSettingsSmall[newCat]):(self.previewSettings[newCat]||self.defaults.previewSettings[newCat]);if(config){$.each(config,function(key,val){styleAttribs+=key+':'+val+';';});}getContent=function(c,d,zoom,frameCss){var id=zoom?'zoom-'+previewId:previewId,tmplt=self._getPreviewTemplate(c),css=(frameClass||'')+' '+frameCss;if(self.frameClass){css=self.frameClass+' '+css;}if(zoom){css=css.replace(' '+$h.SORT_CSS,'');}tmplt=self._parseFilePreviewIcon(tmplt,fname);if(c==='text'){d=$h.htmlEncode(d);}if(cat==='object'&&!ftype){$.each(self.defaults.fileTypeSettings,function(key,func){if(key==='object'||key==='other'){return;}if(func(fname,ftype)){typeCss='type-'+key;}});}if(!$h.isEmpty(attrs)){if(attrs.title!==undefined&&attrs.title!==null){title=attrs.title;}if(attrs.alt!==undefined&&attrs.alt!==null){title=attrs.alt;}}return tmplt.setTokens({'previewId':id,'caption':caption,'title':title,'alt':alt,'frameClass':css,'type':self._getFileType(ftype),'fileindex':ind,'fileid':fileId||'','typeCss':typeCss,'footer':footer,'data':d,'template':templ||cat,'style':styleAttribs?'style="'+styleAttribs+'"':''});};ind=ind||previewId.slice(previewId.lastIndexOf('-')+1);if(self.fileActionSettings.showZoom){zoomContent=getContent((forceZoomIcon?'other':cat),zoomData?zoomData:data,true,'kv-zoom-thumb');}zoomContent='\n'+self._getLayoutTemplate('zoomCache').replace('{zoomContent}',zoomContent);if(typeof self.sanitizeZoomCache==='function'){zoomContent=self.sanitizeZoomCache(zoomContent);}prevContent=getContent((forcePrevIcon?'other':cat),data,false,'kv-preview-thumb');return prevContent+zoomContent;},_addToPreview:function($preview,content){var self=this;return self.reversePreviewOrder?$preview.prepend(content):$preview.append(content);},_previewDefault:function(file,previewId,isDisabled){var self=this,$preview=self.$preview;if(!self.showPreview){return;}var fname=$h.getFileName(file),ftype=file?file.type:'',content,size=file.size||0,caption=self._getFileName(file,''),isError=isDisabled===true&&!self.isAjaxUpload,data=$h.createObjectURL(file),fileId=self.fileManager.getId(file);self._clearDefaultPreview();content=self._generatePreviewTemplate('other',data,fname,ftype,previewId,fileId,isError,size);self._addToPreview($preview,content);self._setThumbAttr(previewId,caption,size);if(isDisabled===true&&self.isAjaxUpload){self._setThumbStatus($('#'+previewId),'Error');}},canPreview:function(file){var self=this;if(!file||!self.showPreview||!self.$preview||!self.$preview.length){return false;}var name=file.name||'',type=file.type||'',size=(file.size||0)/1000,cat=self._parseFileType(type,name),allowedTypes,allowedMimes,allowedExts,skipPreview,types=self.allowedPreviewTypes,mimes=self.allowedPreviewMimeTypes,exts=self.allowedPreviewExtensions||[],dTypes=self.disabledPreviewTypes,dMimes=self.disabledPreviewMimeTypes,dExts=self.disabledPreviewExtensions||[],maxSize=self.maxFilePreviewSize&&parseFloat(self.maxFilePreviewSize)||0,expAllExt=new RegExp('\\.('+exts.join('|')+')$','i'),expDisExt=new RegExp('\\.('+dExts.join('|')+')$','i');allowedTypes=!types||types.indexOf(cat)!==-1;allowedMimes=!mimes||mimes.indexOf(type)!==-1;allowedExts=!exts.length||$h.compare(name,expAllExt);skipPreview=(dTypes&&dTypes.indexOf(cat)!==-1)||(dMimes&&dMimes.indexOf(type)!==-1)||(dExts.length&&$h.compare(name,expDisExt))||(maxSize&&!isNaN(maxSize)&&size>maxSize);return!skipPreview&&(allowedTypes||allowedMimes||allowedExts);},_previewFile:function(i,file,theFile,previewId,data,fileInfo){if(!this.showPreview){return;}var self=this,fname=$h.getFileName(file),ftype=fileInfo.type,caption=fileInfo.name,cat=self._parseFileType(ftype,fname),content,$preview=self.$preview,fsize=file.size||0,iData=(cat==='text'||cat==='html'||cat==='image')?theFile.target.result:data,fileId=self.fileManager.getId(file);if(cat==='html'&&self.purifyHtml&&window.DOMPurify){iData=window.DOMPurify.sanitize(iData);}content=self._generatePreviewTemplate(cat,iData,fname,ftype,previewId,fileId,false,fsize);self._clearDefaultPreview();self._addToPreview($preview,content);var $thumb=$preview.find('#'+previewId),$img=$thumb.find('img'),id=$thumb.attr('data-fileid');self._validateImageOrientation($img,file,previewId,id,caption,ftype,fsize,iData);self._setThumbAttr(previewId,caption,fsize);self._initSortable();},_setThumbAttr:function(id,caption,size){var self=this,$frame=$('#'+id);if($frame.length){size=size&&size>0?self._getSize(size):'';$frame.data({'caption':caption,'size':size});}},_setInitThumbAttr:function(){var self=this,data=self.previewCache.data,len=self.previewCache.count(true),config,caption,size,previewId;if(len===0){return;}for(var i=0;i&"']/g,'_');},_updateFileDetails:function(numFiles){var self=this,$el=self.$element,label,n,log,nFiles,file,name=($h.isIE(9)&&$h.findFileName($el.val()))||($el[0].files[0]&&$el[0].files[0].name);if(!name&&self.fileManager.count()>0){file=self.fileManager.getFirstFile();label=file.nameFmt;}else{label=name?self.slug(name):'_';}n=self.isAjaxUpload?self.fileManager.count():numFiles;nFiles=self.previewCache.count(true)+n;log=n===1?label:self._getMsgSelected(nFiles);if(self.isError){self.$previewContainer.removeClass('file-thumb-loading');self.$previewStatus.html('');self.$captionContainer.removeClass('icon-visible');}else{self._showFileIcon();}self._setCaption(log,self.isError);self.$container.removeClass('file-input-new file-input-ajax-new');if(arguments.length===1){self._raise('fileselect',[numFiles,label]);}if(self.previewCache.count(true)){self._initPreviewActions();}},_setThumbStatus:function($thumb,status){var self=this;if(!self.showPreview){return;}var icon='indicator'+status,msg=icon+'Title',css='file-preview-'+status.toLowerCase(),$indicator=$thumb.find('.file-upload-indicator'),config=self.fileActionSettings;$thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');if(status==='Success'){$thumb.find('.file-drag-handle').remove();}$indicator.html(config[icon]);$indicator.attr('title',config[msg]);$thumb.addClass(css);if(status==='Error'&&!self.retryErrorUploads){$thumb.find('.kv-file-upload').attr('disabled',true);}},_setProgressCancelled:function(){var self=this;self._setProgress(101,self.$progress,self.msgCancelled);},_setProgress:function(p,$el,error,stats){var self=this;$el=$el||self.$progress;if(!$el.length){return;}var pct=Math.min(p,100),out,pctLimit=self.progressUploadThreshold,t=p<=100?self.progressTemplate:self.progressCompleteTemplate,template=pct<100?self.progressTemplate:(error?(self.paused?self.progressPauseTemplate:self.progressErrorTemplate):t);if(p>=100){stats='';}if(!$h.isEmpty(template)){if(pctLimit&&pct>pctLimit&&p<=100){out=template.setTokens({'percent':pctLimit,'status':self.msgUploadThreshold});}else{out=template.setTokens({'percent':pct,'status':(p>100?self.msgUploadEnd:pct+'%')});}stats=stats||'';out=out.setTokens({stats:stats});$el.html(out);if(error){$el.find('[role="progressbar"]').html(error);}}},_setFileDropZoneTitle:function(){var self=this,$zone=self.$container.find('.file-drop-zone'),title=self.dropZoneTitle,strFiles;if(self.isClickable){strFiles=$h.isEmpty(self.$element.attr('multiple'))?self.fileSingle:self.filePlural;title+=self.dropZoneClickTitle.replace('{files}',strFiles);}$zone.find('.'+self.dropZoneTitleClass).remove();if(!self.showPreview||$zone.length===0||self.fileManager.count()>0||!self.dropZoneEnabled||(!self.isAjaxUpload&&self.$element.files)){return;}if($zone.find($h.FRAMES).length===0&&$h.isEmpty(self.defaultPreviewContent)){$zone.prepend('
    '+title+'
    ');}self.$container.removeClass('file-input-new');$h.addCss(self.$container,'file-input-ajax-new');},_getStats:function(stats){var self=this,pendingTime,t;if(!self.showUploadStats||!stats||!stats.bitrate){return'';}t=self._getLayoutTemplate('stats');pendingTime=(!stats.elapsed||!stats.bps)?self.msgCalculatingTime:self.msgPendingTime.setTokens({time:$h.getElapsed(Math.ceil(stats.pendingBytes/stats.bps))});return t.setTokens({uploadSpeed:stats.bitrate,pendingTime:pendingTime});},_setResumableProgress:function(pct,stats,$thumb){var self=this,rm=self.resumableManager,obj=$thumb?rm:self,$prog=$thumb?$thumb.find('.file-thumb-progress'):null;if(obj.lastProgress===0){obj.lastProgress=pct;}if(pct0&&self._getFileCount(len-1)=limit:dim<=limit;if(isValid){return;}msg=self['msgImage'+type+chk].setTokens({'name':fname,'size':limit});self._showFileError(msg,params);self._setPreviewError($thumb);},_getExifObj:function(data){var self=this,exifObj=null,error=$h.logMessages.exifWarning;if(data.slice(0,23)!=='data:image/jpeg;base64,'&&data.slice(0,22)!=='data:image/jpg;base64,'){exifObj=null;return;}try{exifObj=window.piexif?window.piexif.load(data):null;}catch(err){exifObj=null;error=err&&err.message||'';}if(!exifObj){self._log($h.logMessages.badExifParser,{details:error});}return exifObj;},setImageOrientation:function($img,$zoomImg,value,$thumb){var self=this,invalidImg=!$img||!$img.length,invalidZoomImg=!$zoomImg||!$zoomImg.length,$mark,isHidden=false,$div,zoomOnly=invalidImg&&$thumb&&$thumb.attr('data-template')==='image',ev;if(invalidImg&&invalidZoomImg){return;}ev='load.fileinputimageorient';if(zoomOnly){$img=$zoomImg;$zoomImg=null;$img.css(self.previewSettings.image);$div=$(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));$mark=$(document.createElement('span')).insertBefore($img);$img.css('visibility','hidden').removeClass('file-zoom-detail').appendTo($div);}else{isHidden=!$img.is(':visible');}$img.off(ev).on(ev,function(){if(isHidden){self.$preview.removeClass('hide-content');$thumb.find('.kv-file-content').css('visibility','hidden');}var img=$img.get(0),zoomImg=$zoomImg&&$zoomImg.length?$zoomImg.get(0):null,h=img.offsetHeight,w=img.offsetWidth,r=$h.getRotation(value);if(isHidden){$thumb.find('.kv-file-content').css('visibility','visible');self.$preview.addClass('hide-content');}$img.data('orientation',value);if(zoomImg){$zoomImg.data('orientation',value);}if(value<5){$h.setTransform(img,r);$h.setTransform(zoomImg,r);return;}var offsetAngle=Math.atan(w/h),origFactor=Math.sqrt(Math.pow(h,2)+Math.pow(w,2)),scale=!origFactor?1:(h/Math.cos(Math.PI/2+offsetAngle))/origFactor,s=' scale('+Math.abs(scale)+')';$h.setTransform(img,r+s);$h.setTransform(zoomImg,r+s);if(zoomOnly){$img.css('visibility','visible').insertAfter($mark).addClass('file-zoom-detail');$mark.remove();$div.remove();}});},_validateImageOrientation:function($img,file,previewId,fileId,caption,ftype,fsize,iData){var self=this,exifObj,value,autoOrientImage=self.autoOrientImage;exifObj=autoOrientImage?self._getExifObj(iData):null;value=exifObj?exifObj['0th'][piexif.ImageIFD.Orientation]:null;if(!value){self._validateImage(previewId,fileId,caption,ftype,fsize,iData,exifObj);return;}self.setImageOrientation($img,$('#zoom-'+previewId+' img'),value,$('#'+previewId));self._raise('fileimageoriented',{'$img':$img,'file':file});self._validateImage(previewId,fileId,caption,ftype,fsize,iData,exifObj);},_validateImage:function(previewId,fileId,fname,ftype,fsize,iData,exifObj){var self=this,$preview=self.$preview,params,w1,w2,$thumb=$preview.find('#'+previewId),i=$thumb.attr('data-fileindex'),$img=$thumb.find('img');fname=fname||'Untitled';$img.one('load',function(){w1=$thumb.width();w2=$preview.width();if(w1>w2){$img.css('width','100%');}params={ind:i,id:previewId,fileId:fileId};self._checkDimensions(i,'Small',$img,$thumb,fname,'Width',params);self._checkDimensions(i,'Small',$img,$thumb,fname,'Height',params);if(!self.resizeImage){self._checkDimensions(i,'Large',$img,$thumb,fname,'Width',params);self._checkDimensions(i,'Large',$img,$thumb,fname,'Height',params);}self._raise('fileimageloaded',[previewId]);self.fileManager.addImage(fileId,{ind:i,img:$img,thumb:$thumb,pid:previewId,typ:ftype,siz:fsize,validated:false,imgData:iData,exifObj:exifObj});$thumb.data('exif',exifObj);self._validateAllImages();}).one('error',function(){self._raise('fileimageloaderror',[previewId]);}).each(function(){if(this.complete){$(this).trigger('load');}else{if(this.error){$(this).trigger('error');}}});},_validateAllImages:function(){var self=this,counter={val:0},numImgs=self.fileManager.getImageCount(),fsize,minSize=self.resizeIfSizeMoreThan;if(numImgs!==self.fileManager.totalImages){return;}self._raise('fileimagesloaded');if(!self.resizeImage){return;}$.each(self.fileManager.loadedImages,function(id,config){if(!config.validated){fsize=config.siz;if(fsize&&fsize>minSize*1000){self._getResizedImage(id,config,counter,numImgs);}config.validated=true;}});},_getResizedImage:function(id,config,counter,numImgs){var self=this,img=$(config.img)[0],width=img.naturalWidth,height=img.naturalHeight,blob,ratio=1,maxWidth=self.maxImageWidth||width,maxHeight=self.maxImageHeight||height,isValidImage=!!(width&&height),chkWidth,chkHeight,canvas=self.imageCanvas,dataURI,context=self.imageCanvasContext,type=config.typ,pid=config.pid,ind=config.ind,$thumb=config.thumb,throwError,msg,exifObj=config.exifObj,exifStr,file,params,evParams;throwError=function(msg,params,ev){if(self.isAjaxUpload){self._showFileError(msg,params,ev);}else{self._showError(msg,params,ev);}self._setPreviewError($thumb);};file=self.fileManager.getFile(id);params={id:pid,'index':ind,fileId:id};evParams=[id,pid,ind];if(!file||!isValidImage||(width<=maxWidth&&height<=maxHeight)){if(isValidImage&&file){self._raise('fileimageresized',evParams);}counter.val++;if(counter.val===numImgs){self._raise('fileimagesresized');}if(!isValidImage){throwError(self.msgImageResizeError,params,'fileimageresizeerror');return;}}type=type||self.resizeDefaultImageType;chkWidth=width>maxWidth;chkHeight=height>maxHeight;if(self.resizePreference==='width'){ratio=chkWidth?maxWidth/width:(chkHeight?maxHeight/height:1);}else{ratio=chkHeight?maxHeight/height:(chkWidth?maxWidth/width:1);}self._resetCanvas();width*=ratio;height*=ratio;canvas.width=width;canvas.height=height;try{context.drawImage(img,0,0,width,height);dataURI=canvas.toDataURL(type,self.resizeQuality);if(exifObj){exifStr=window.piexif.dump(exifObj);dataURI=window.piexif.insert(exifStr,dataURI);}blob=$h.dataURI2Blob(dataURI);self.fileManager.setFile(id,blob);self._raise('fileimageresized',evParams);counter.val++;if(counter.val===numImgs){self._raise('fileimagesresized',[undefined,undefined]);}if(!(blob instanceof Blob)){throwError(self.msgImageResizeError,params,'fileimageresizeerror');}}catch(err){counter.val++;if(counter.val===numImgs){self._raise('fileimagesresized',[undefined,undefined]);}msg=self.msgImageResizeException.replace('{errors}',err.message);throwError(msg,params,'fileimageresizeexception');}},_initBrowse:function($container){var self=this,$el=self.$element;if(self.showBrowse){self.$btnFile=$container.find('.btn-file').append($el);}else{$el.appendTo($container).attr('tabindex',-1);$h.addCss($el,'file-no-browse');}},_initClickable:function(){var self=this,$zone,$tmpZone;if(!self.isClickable){return;}$zone=self.$dropZone;if(!self.isAjaxUpload){$tmpZone=self.$preview.find('.file-default-preview');if($tmpZone.length){$zone=$tmpZone;}}$h.addCss($zone,'clickable');$zone.attr('tabindex',-1);self._handler($zone,'click',function(e){var $tar=$(e.target);if(!$(self.elErrorContainer+':visible').length&&(!$tar.parents('.file-preview-thumbnails').length||$tar.parents('.file-default-preview').length)){self.$element.data('zoneClicked',true).trigger('click');$zone.blur();}});},_initCaption:function(){var self=this,cap=self.initialCaption||'';if(self.overwriteInitial||$h.isEmpty(cap)){self.$caption.val('');return false;}self._setCaption(cap);return true;},_setCaption:function(content,isError){var self=this,title,out,icon,n,cap,file;if(!self.$caption.length){return;}self.$captionContainer.removeClass('icon-visible');if(isError){title=$('
    '+self.msgValidationError+'
    ').text();n=self.fileManager.count();if(n){file=self.fileManager.getFirstFile();cap=n===1&&file?file.nameFmt:self._getMsgSelected(n);}else{cap=self._getMsgSelected(self.msgNo);}out=$h.isEmpty(content)?cap:content;icon=''+self.msgValidationErrorIcon+'';}else{if($h.isEmpty(content)){return;}title=$('
    '+content+'
    ').text();out=title;icon=self._getLayoutTemplate('fileIcon');}self.$captionContainer.addClass('icon-visible');self.$caption.attr('title',title).val(out);self.$captionIcon.html(icon);},_createContainer:function(){var self=this,attribs={'class':'file-input file-input-new'+(self.rtl?' kv-rtl':'')},$container=$(document.createElement('div')).attr(attribs).html(self._renderMain());$container.insertBefore(self.$element);self._initBrowse($container);if(self.theme){$container.addClass('theme-'+self.theme);}return $container;},_refreshContainer:function(){var self=this,$container=self.$container,$el=self.$element;$el.insertAfter($container);$container.html(self._renderMain());self._initBrowse($container);self._validateDisabled();},_validateDisabled:function(){var self=this;self.$caption.attr({readonly:self.isDisabled});},_renderMain:function(){var self=this,dropCss=self.dropZoneEnabled?' file-drop-zone':'file-drop-disabled',close=!self.showClose?'':self._getLayoutTemplate('close'),preview=!self.showPreview?'':self._getLayoutTemplate('preview').setTokens({'class':self.previewClass,'dropClass':dropCss}),css=self.isDisabled?self.captionClass+' file-caption-disabled':self.captionClass,caption=self.captionTemplate.setTokens({'class':css+' kv-fileinput-caption'});return self.mainTemplate.setTokens({'class':self.mainClass+(!self.showBrowse&&self.showCaption?' no-browse':''),'preview':preview,'close':close,'caption':caption,'upload':self._renderButton('upload'),'remove':self._renderButton('remove'),'cancel':self._renderButton('cancel'),'pause':self._renderButton('pause'),'browse':self._renderButton('browse')});},_renderButton:function(type){var self=this,tmplt=self._getLayoutTemplate('btnDefault'),css=self[type+'Class'],title=self[type+'Title'],icon=self[type+'Icon'],label=self[type+'Label'],status=self.isDisabled?' disabled':'',btnType='button';switch(type){case'remove':if(!self.showRemove){return'';}break;case'cancel':if(!self.showCancel){return'';}css+=' kv-hidden';break;case'pause':if(!self.showPause){return'';}css+=' kv-hidden';break;case'upload':if(!self.showUpload){return'';}if(self.isAjaxUpload&&!self.isDisabled){tmplt=self._getLayoutTemplate('btnLink').replace('{href}',self.uploadUrl);}else{btnType='submit';}break;case'browse':if(!self.showBrowse){return'';}tmplt=self._getLayoutTemplate('btnBrowse');break;default:return'';}css+=type==='browse'?' btn-file':' fileinput-'+type+' fileinput-'+type+'-button';if(!$h.isEmpty(label)){label=' '+label+'';}return tmplt.setTokens({'type':btnType,'css':css,'title':title,'status':status,'icon':icon,'label':label});},_renderThumbProgress:function(){var self=this;return'
    '+self.progressInfoTemplate.setTokens({percent:101,status:self.msgUploadBegin,stats:''})+'
    ';},_renderFileFooter:function(cat,caption,size,width,isError){var self=this,config=self.fileActionSettings,rem=config.showRemove,drg=config.showDrag,upl=config.showUpload,zoom=config.showZoom,out,params,template=self._getLayoutTemplate('footer'),tInd=self._getLayoutTemplate('indicator'),ind=isError?config.indicatorError:config.indicatorNew,title=isError?config.indicatorErrorTitle:config.indicatorNewTitle,indicator=tInd.setTokens({'indicator':ind,'indicatorTitle':title});size=self._getSize(size);params={type:cat,caption:caption,size:size,width:width,progress:'',indicator:indicator};if(self.isAjaxUpload){params.progress=self._renderThumbProgress();params.actions=self._renderFileActions(params,upl,false,rem,zoom,drg,false,false,false);}else{params.actions=self._renderFileActions(params,false,false,false,zoom,drg,false,false,false);}out=template.setTokens(params);out=$h.replaceTags(out,self.previewThumbTags);return out;},_renderFileActions:function(cfg,showUpl,showDwn,showDel,showZoom,showDrag,disabled,url,key,isInit,dUrl,dFile){var self=this;if(!cfg.type&&isInit){cfg.type='image';}if(self.enableResumableUpload){showUpl=false;}else{if(typeof showUpl==='function'){showUpl=showUpl(cfg);}}if(typeof showDwn==='function'){showDwn=showDwn(cfg);}if(typeof showDel==='function'){showDel=showDel(cfg);}if(typeof showZoom==='function'){showZoom=showZoom(cfg);}if(typeof showDrag==='function'){showDrag=showDrag(cfg);}if(!showUpl&&!showDwn&&!showDel&&!showZoom&&!showDrag){return'';}var vUrl=url===false?'':' data-url="'+url+'"',btnZoom='',btnDrag='',css,vKey=key===false?'':' data-key="'+key+'"',btnDelete='',btnUpload='',btnDownload='',template=self._getLayoutTemplate('actions'),config=self.fileActionSettings,otherButtons=self.otherActionButtons.setTokens({'dataKey':vKey,'key':key}),removeClass=disabled?config.removeClass+' disabled':config.removeClass;if(showDel){btnDelete=self._getLayoutTemplate('actionDelete').setTokens({'removeClass':removeClass,'removeIcon':config.removeIcon,'removeTitle':config.removeTitle,'dataUrl':vUrl,'dataKey':vKey,'key':key});}if(showUpl){btnUpload=self._getLayoutTemplate('actionUpload').setTokens({'uploadClass':config.uploadClass,'uploadIcon':config.uploadIcon,'uploadTitle':config.uploadTitle});}if(showDwn){btnDownload=self._getLayoutTemplate('actionDownload').setTokens({'downloadClass':config.downloadClass,'downloadIcon':config.downloadIcon,'downloadTitle':config.downloadTitle,'downloadUrl':dUrl||self.initialPreviewDownloadUrl});btnDownload=btnDownload.setTokens({'filename':dFile,'key':key});}if(showZoom){btnZoom=self._getLayoutTemplate('actionZoom').setTokens({'zoomClass':config.zoomClass,'zoomIcon':config.zoomIcon,'zoomTitle':config.zoomTitle});}if(showDrag&&isInit){css='drag-handle-init '+config.dragClass;btnDrag=self._getLayoutTemplate('actionDrag').setTokens({'dragClass':css,'dragTitle':config.dragTitle,'dragIcon':config.dragIcon});}return template.setTokens({'delete':btnDelete,'upload':btnUpload,'download':btnDownload,'zoom':btnZoom,'drag':btnDrag,'other':otherButtons});},_browse:function(e){var self=this;if(e&&e.isDefaultPrevented()||!self._raise('filebrowse')){return;}if(self.isError&&!self.isAjaxUpload){self.clear();}self.$captionContainer.focus();},_change:function(e){var self=this;if(self.changeTriggered){return;}var $el=self.$element,isDragDrop=arguments.length>1,isAjaxUpload=self.isAjaxUpload,tfiles,files=isDragDrop?arguments[1]:$el.get(0).files,total,maxCount=!isAjaxUpload&&$h.isEmpty($el.attr('multiple'))?1:self.maxFileCount,len,ctr=self.fileManager.count(),isSingleUpload=$h.isEmpty($el.attr('multiple')),flagSingle=(isSingleUpload&&ctr>0),throwError=function(mesg,file,previewId,index){var p1=$.extend(true,{},self._getOutData(null,{},{},files),{id:previewId,index:index}),p2={id:previewId,index:index,file:file,files:files};return isAjaxUpload?self._showFileError(mesg,p1):self._showError(mesg,p2);},maxCountCheck=function(n,m){var msg=self.msgFilesTooMany.replace('{m}',m).replace('{n}',n);self.isError=throwError(msg,null,null,null);self.$captionContainer.removeClass('icon-visible');self._setCaption('',true);self.$container.removeClass('file-input-new file-input-ajax-new');};self.reader=null;self._resetUpload();self._hideFileIcon();if(self.dropZoneEnabled){self.$container.find('.file-drop-zone .'+self.dropZoneTitleClass).remove();}if(!isAjaxUpload){if(e.target&&e.target.files===undefined){files=e.target.value?[{name:e.target.value.replace(/^.+\\/,'')}]:[];}else{files=e.target.files||{};}}tfiles=files;if($h.isEmpty(tfiles)||tfiles.length===0){if(!isAjaxUpload){self.clear();}self._raise('fileselectnone');return;}self._resetErrors();len=tfiles.length;total=self._getFileCount(isAjaxUpload?(self.fileManager.count()+len):len);if(maxCount>0&&total>maxCount){if(!self.autoReplace||len>maxCount){maxCountCheck((self.autoReplace&&len>maxCount?len:total),maxCount);return;}if(total>maxCount){self._resetPreviewThumbs(isAjaxUpload);}}else{if(!isAjaxUpload||flagSingle){self._resetPreviewThumbs(false);if(flagSingle){self.clearFileStack();}}else{if(isAjaxUpload&&ctr===0&&(!self.previewCache.count(true)||self.overwriteInitial)){self._resetPreviewThumbs(true);}}}self.readFiles(tfiles);},_abort:function(params){var self=this,data;if(self.ajaxAborted&&typeof self.ajaxAborted==='object'&&self.ajaxAborted.message!==undefined){data=$.extend(true,{},self._getOutData(null),params);data.abortData=self.ajaxAborted.data||{};data.abortMessage=self.ajaxAborted.message;self._setProgress(101,self.$progress,self.msgCancelled);self._showFileError(self.ajaxAborted.message,data,'filecustomerror');self.cancel();return true;}return!!self.ajaxAborted;},_resetFileStack:function(){var self=this,i=0;self._getThumbs().each(function(){var $thumb=$(this),ind=$thumb.attr('data-fileindex'),pid=$thumb.attr('id');if(ind==='-1'||ind===-1){return;}if(!self.fileManager.getFile($thumb.attr('data-fileid'))){$thumb.attr({'id':self.previewInitId+'-'+i,'data-fileindex':i});i++;}else{$thumb.attr({'id':'uploaded-'+$h.uniqId(),'data-fileindex':'-1'});}self.$preview.find('#zoom-'+pid).attr({'id':'zoom-'+$thumb.attr('id'),'data-fileindex':$thumb.attr('data-fileindex')});});},_isFileSelectionValid:function(cnt){var self=this;cnt=cnt||0;if(self.required&&!self.getFilesCount()){self.$errorContainer.html('');self._showFileError(self.msgFileRequired);return false;}if(self.minFileCount>0&&self._getFileCount(cnt)=numFiles){if(self.isAjaxUpload&&self.fileManager.count()>0){self._raise('filebatchselected',[self.fileManager.stack]);}else{self._raise('filebatchselected',[files]);}$container.removeClass('file-thumb-loading');$status.html('');return;}var node=ctr+i,previewId=previewInitId+'-'+node,file=files[i],fSizeKB,j,msg,$thumb,fnText=settings.text,fnImage=settings.image,fnHtml=settings.html,typ,chk,typ1,typ2,caption=self._getFileName(file,''),fileSize=(file&&file.size||0)/1000,fileExtExpr='',previewData=$h.createObjectURL(file),fileCount=0,strTypes='',fileId,func,knownTypes=0,isText,isHtml,isImage,txtFlag,processFileLoaded=function(){var msg=msgProgress.setTokens({'index':i+1,'files':numFiles,'percent':50,'name':caption});setTimeout(function(){$status.html(msg);self._updateFileDetails(numFiles);readFile(i+1);},self.processDelay);self._raise('fileloaded',[file,previewId,i,reader]);};if(!file){return;}fileId=self.fileManager.getId(file);if(typLen>0){for(j=0;j0&&fileSize>self.maxFileSize){msg=self.msgSizeTooLarge.setTokens({'name':caption,'size':fSizeKB,'maxSize':self.maxFileSize});throwError(msg,file,previewId,i,fileId);return;}if(self.minFileSize!==null&&fileSize<=$h.getNum(self.minFileSize)){msg=self.msgSizeTooSmall.setTokens({'name':caption,'size':fSizeKB,'minSize':self.minFileSize});throwError(msg,file,previewId,i,fileId);return;}if(!$h.isEmpty(fileTypes)&&$h.isArray(fileTypes)){for(j=0;j0){for(i=0;i0){for(i=0;i0)?self.initialCaption:'';self.$caption.attr('title','').val(cap);$h.addCss(self.$container,'file-input-new');self._validateDefaultPreview();}if(self.$container.find($h.FRAMES).length===0){if(!self._initCaption()){self.$captionContainer.removeClass('icon-visible');}}self._hideFileIcon();self.$captionContainer.focus();self._setFileDropZoneTitle();self._raise('filecleared');return self.$element;},reset:function(){var self=this;if(!self._raise('filereset')){return;}self.lastProgress=0;self._resetPreview();self.$container.find('.fileinput-filename').text('');$h.addCss(self.$container,'file-input-new');if(self.getFrames().length||self.dropZoneEnabled){self.$container.removeClass('file-input-new');}self.clearFileStack();self._setFileDropZoneTitle();return self.$element;},disable:function(){var self=this;self.isDisabled=true;self._raise('filedisabled');self.$element.attr('disabled','disabled');self.$container.find('.kv-fileinput-caption').addClass('file-caption-disabled');self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button').attr('disabled',true);$h.addCss(self.$container.find('.btn-file'),'disabled');self._initDragDrop();return self.$element;},enable:function(){var self=this;self.isDisabled=false;self._raise('fileenabled');self.$element.removeAttr('disabled');self.$container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button').removeAttr('disabled');self.$container.find('.btn-file').removeClass('disabled');self._initDragDrop();return self.$element;},upload:function(){var self=this,fm=self.fileManager,totLen=fm.count(),i,outData,len,hasExtraData=!$.isEmptyObject(self._getExtraData());if(!self.isAjaxUpload||self.isDisabled||!self._isFileSelectionValid(totLen)){return;}self.lastProgress=0;self._resetUpload();if(totLen===0&&!hasExtraData){self._showFileError(self.msgUploadEmpty);return;}self.cancelling=false;self.$progress.show();self.lock();len=fm.count();if(totLen===0&&hasExtraData){self._setProgress(2);self._uploadExtraOnly();return;}if(self.enableResumableUpload){return self.resume();}if(self.uploadAsync||self.enableResumableUpload){outData=self._getOutData(null);self._raise('filebatchpreupload',[outData]);self.fileBatchCompleted=false;self.uploadCache={content:[],config:[],tags:[],append:true};for(i=0;i',next:'',toggleheader:'',fullscreen:'',borderless:'',close:''},previewZoomButtonClasses:{prev:'btn btn-navigate',next:'btn btn-navigate',toggleheader:'btn btn-sm btn-kv btn-default btn-outline-secondary',fullscreen:'btn btn-sm btn-kv btn-default btn-outline-secondary',borderless:'btn btn-sm btn-kv btn-default btn-outline-secondary',close:'btn btn-sm btn-kv btn-default btn-outline-secondary'},previewTemplates:{},previewContentTemplates:{},preferIconicPreview:false,preferIconicZoomPreview:false,allowedFileTypes:null,allowedFileExtensions:null,allowedPreviewTypes:undefined,allowedPreviewMimeTypes:null,allowedPreviewExtensions:null,disabledPreviewTypes:undefined,disabledPreviewExtensions:['msi','exe','com','zip','rar','app','vb','scr'],disabledPreviewMimeTypes:null,defaultPreviewContent:null,customLayoutTags:{},customPreviewTags:{},previewFileIcon:'',previewFileIconClass:'file-other-icon',previewFileIconSettings:{},previewFileExtSettings:{},buttonLabelClass:'hidden-xs',browseIcon:' ',browseClass:'btn btn-primary',removeIcon:'',removeClass:'btn btn-default btn-secondary',cancelIcon:'',cancelClass:'btn btn-default btn-secondary',pauseIcon:'',pauseClass:'btn btn-default btn-secondary',uploadIcon:'',uploadClass:'btn btn-default btn-secondary',uploadUrl:null,uploadUrlThumb:null,uploadAsync:true,uploadParamNames:{chunkCount:'chunkCount',chunkIndex:'chunkIndex',chunkSize:'chunkSize',chunkSizeStart:'chunkSizeStart',chunksUploaded:'chunksUploaded',fileBlob:'fileBlob',fileId:'fileId',fileName:'fileName',fileRelativePath:'fileRelativePath',fileSize:'fileSize',retryCount:'retryCount'},maxAjaxThreads:5,processDelay:100,queueDelay:10,progressDelay:0,enableResumableUpload:false,resumableUploadOptions:{fallback:null,testUrl:null,chunkSize:2*1024,maxThreads:4,maxRetries:3,showErrorLog:true},uploadExtraData:{},zoomModalHeight:480,minImageWidth:null,minImageHeight:null,maxImageWidth:null,maxImageHeight:null,resizeImage:false,resizePreference:'width',resizeQuality:0.92,resizeDefaultImageType:'image/jpeg',resizeIfSizeMoreThan:0,minFileSize:0,maxFileSize:0,maxFilePreviewSize:25600,minFileCount:0,maxFileCount:0,validateInitialCount:false,msgValidationErrorClass:'text-danger',msgValidationErrorIcon:' ',msgErrorClass:'file-error-message',progressThumbClass:'progress-bar progress-bar-striped active',progressClass:'progress-bar bg-success progress-bar-success progress-bar-striped active',progressInfoClass:'progress-bar bg-info progress-bar-info progress-bar-striped active',progressCompleteClass:'progress-bar bg-success progress-bar-success',progressPauseClass:'progress-bar bg-primary progress-bar-primary progress-bar-striped active',progressErrorClass:'progress-bar bg-danger progress-bar-danger',progressUploadThreshold:99,previewFileType:'image',elCaptionContainer:null,elCaptionText:null,elPreviewContainer:null,elPreviewImage:null,elPreviewStatus:null,elErrorContainer:null,errorCloseButton:$h.closeButton('kv-error-close'),slugCallback:null,dropZoneEnabled:true,dropZoneTitleClass:'file-drop-zone-title',fileActionSettings:{},otherActionButtons:'',textEncoding:'UTF-8',ajaxSettings:{},ajaxDeleteSettings:{},showAjaxErrorDetails:true,mergeAjaxCallbacks:false,mergeAjaxDeleteCallbacks:false,retryErrorUploads:true,reversePreviewOrder:false,usePdfRenderer:function(){var isIE11=!!window.MSInputMethodContext&&!!document.documentMode;return!!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i)||isIE11;},pdfRendererUrl:'',pdfRendererTemplate:''};$.fn.fileinputLocales.en={fileSingle:'file',filePlural:'files',browseLabel:'Browse …',removeLabel:'Remove',removeTitle:'Clear all unprocessed files',cancelLabel:'Cancel',cancelTitle:'Abort ongoing upload',pauseLabel:'Pause',pauseTitle:'Pause ongoing upload',uploadLabel:'Upload',uploadTitle:'Upload selected files',msgNo:'No',msgNoFilesSelected:'No files selected',msgCancelled:'Cancelled',msgPaused:'Paused',msgPlaceholder:'Select {files}...',msgZoomModalHeading:'Detailed Preview',msgFileRequired:'You must select a file to upload.',msgSizeTooSmall:'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.',msgSizeTooLarge:'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.',msgFilesTooLess:'You must select at least {n} {files} to upload.',msgFilesTooMany:'Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.',msgFileNotFound:'File "{name}" not found!',msgFileSecured:'Security restrictions prevent reading the file "{name}".',msgFileNotReadable:'File "{name}" is not readable.',msgFilePreviewAborted:'File preview aborted for "{name}".',msgFilePreviewError:'An error occurred while reading the file "{name}".',msgInvalidFileName:'Invalid or unsupported characters in file name "{name}".',msgInvalidFileType:'Invalid type for file "{name}". Only "{types}" files are supported.',msgInvalidFileExtension:'Invalid extension for file "{name}". Only "{extensions}" files are supported.',msgFileTypes:{'image':'image','html':'HTML','text':'text','video':'video','audio':'audio','flash':'flash','pdf':'PDF','object':'object'},msgUploadAborted:'The file upload was aborted',msgUploadThreshold:'Processing...',msgUploadBegin:'Initializing...',msgUploadEnd:'Done',msgUploadResume:'Resuming upload...',msgUploadEmpty:'No valid data available for upload.',msgUploadError:'Upload Error',msgDeleteError:'Delete Error',msgProgressError:'Error',msgValidationError:'Validation Error',msgLoading:'Loading file {index} of {files} …',msgProgress:'Loading file {index} of {files} - {name} - {percent}% completed.',msgSelected:'{n} {files} selected',msgFoldersNotAllowed:'Drag & drop files only! {n} folder(s) dropped were skipped.',msgImageWidthSmall:'Width of image file "{name}" must be at least {size} px.',msgImageHeightSmall:'Height of image file "{name}" must be at least {size} px.',msgImageWidthLarge:'Width of image file "{name}" cannot exceed {size} px.',msgImageHeightLarge:'Height of image file "{name}" cannot exceed {size} px.',msgImageResizeError:'Could not get the image dimensions to resize.',msgImageResizeException:'Error while resizing the image.
    {errors}
    ',msgAjaxError:'Something went wrong with the {operation} operation. Please try again later!',msgAjaxProgressError:'{operation} failed',msgDuplicateFile:'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',msgResumableUploadRetriesExceeded:'Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ',msgPendingTime:'{time} remaining',msgCalculatingTime:'calculating time remaining',ajaxOperations:{deleteThumb:'file delete',uploadThumb:'file upload',uploadBatch:'batch file upload',uploadExtra:'form data upload'},dropZoneTitle:'Drag & drop files here …',dropZoneClickTitle:'
    (or click to select {files})',previewZoomButtonTitles:{prev:'View previous file',next:'View next file',toggleheader:'Toggle header',fullscreen:'Toggle full screen',borderless:'Toggle borderless mode',close:'Close detailed preview'}};$.fn.fileinputLocales.zh={fileSingle:'文件',filePlural:'个文件',browseLabel:'选择 …',removeLabel:'移除',removeTitle:'清除选中文件',cancelLabel:'取消',cancelTitle:'取消进行中的上传',pauseLabel:'Pause',pauseTitle:'Pause ongoing upload',uploadLabel:'上传',uploadTitle:'上传选中文件',msgNo:'没有',msgNoFilesSelected:'未选择文件',msgPaused:'Paused',msgCancelled:'取消',msgPlaceholder:'选择 {files}...',msgZoomModalHeading:'详细预览',msgFileRequired:'必须选择一个文件上传.',msgSizeTooSmall:'文件 "{name}" ({size} KB) 必须大于限定大小 {minSize} KB.',msgSizeTooLarge:'文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB.',msgFilesTooLess:'你必须选择最少 {n} {files} 来上传. ',msgFilesTooMany:'选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}.',msgFileNotFound:'文件 "{name}" 未找到!',msgFileSecured:'安全限制,为了防止读取文件 "{name}".',msgFileNotReadable:'文件 "{name}" 不可读.',msgFilePreviewAborted:'取消 "{name}" 的预览.',msgFilePreviewError:'读取 "{name}" 时出现了一个错误.',msgInvalidFileName:'文件名 "{name}" 包含非法字符.',msgInvalidFileType:'不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',msgInvalidFileExtension:'不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',msgFileTypes:{'image':'image','html':'HTML','text':'text','video':'video','audio':'audio','flash':'flash','pdf':'PDF','object':'object'},msgUploadAborted:'该文件上传被中止',msgUploadThreshold:'处理中...',msgUploadBegin:'正在初始化...',msgUploadEnd:'完成',msgUploadResume:'Resuming upload...',msgUploadEmpty:'无效的文件上传.',msgUploadError:'Upload Error',msgDeleteError:'Delete Error',msgProgressError:'上传出错',msgValidationError:'验证错误',msgLoading:'加载第 {index} 文件 共 {files} …',msgProgress:'加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',msgSelected:'{n} {files} 选中',msgFoldersNotAllowed:'只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',msgImageWidthSmall:'图像文件的"{name}"的宽度必须是至少{size}像素.',msgImageHeightSmall:'图像文件的"{name}"的高度必须至少为{size}像素.',msgImageWidthLarge:'图像文件"{name}"的宽度不能超过{size}像素.',msgImageHeightLarge:'图像文件"{name}"的高度不能超过{size}像素.',msgImageResizeError:'无法获取的图像尺寸调整。',msgImageResizeException:'调整图像大小时发生错误。
    {errors}
    ',msgAjaxError:'{operation} 发生错误. 请重试!',msgAjaxProgressError:'{operation} 失败',msgDuplicateFile:'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',msgResumableUploadRetriesExceeded:'Upload aborted beyond {max} retries for file {file}! Error Details:
    {error}
    ',msgPendingTime:'{time} remaining',msgCalculatingTime:'calculating time remaining',ajaxOperations:{deleteThumb:'删除文件',uploadThumb:'上传文件',uploadBatch:'批量上传',uploadExtra:'表单数据上传'},dropZoneTitle:'拖拽文件到这里 …
    支持多文件同时上传',dropZoneClickTitle:'
    (或点击{files}按钮选择文件)',fileActionSettings:{removeTitle:'删除文件',uploadTitle:'上传文件',downloadTitle:'下载文件',uploadRetryTitle:'重试',zoomTitle:'查看详情',dragTitle:'移动 / 重置',indicatorNewTitle:'没有上传',indicatorSuccessTitle:'上传',indicatorErrorTitle:'上传错误',indicatorPausedTitle:'Upload Paused',indicatorLoadingTitle:'上传 ...'},previewZoomButtonTitles:{prev:'预览上一个文件',next:'预览下一个文件',toggleheader:'缩放',fullscreen:'全屏',borderless:'无边界模式',close:'关闭当前预览'}};$.fn.fileinput.Constructor=FileInput;$(document).ready(function(){var $input=$('input.file[type=file]');if($input.length){$input.fileinput();}});}));