(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},h=0,c=0,l=[];function g(e,d,g,i){var c={data:i||(d?d.data:{}),_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};e&&a.extend(c,e,{nodes:[],parent:d});if(g){c.tmpl=g;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++h;(l.length?f:b)[h]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a.fn[d].apply(a(i[h]),k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,l,j){if(d[0]&&d[0].nodeType){var f=a.makeArray(arguments),g=d.length,i=0,h;while(i<g&&!(h=a.data(d[i++],"tmplItem")));if(g>1)f[0]=[a.makeArray(d)];if(h&&c)f[2]=function(b){a.tmpl.afterManip(this,b,j)};r.apply(this,f)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var j,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(i(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);j=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(i(c,null,j)):j},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){_=_.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(_,$1,$2);_=[];",close:"call=$item.calls();_=call._.concat($item.wrap(call,_));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){_.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){_.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function i(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:i(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=j(c).concat(b);if(d)b=b.concat(j(d))});return b?b:j(c)}function j(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,_=[],$data=$item.data;with($data){_.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,j,d,b,c,e){var i=a.tmpl.tag[j],h,f,g;if(!i)throw"Template command not found: "+j;h=i._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=k(b);e=e?","+k(e)+")":c?")":"";f=c?b.indexOf(".")>-1?b+c:"("+b+").call($item"+e:b;g=c?f:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else g=f=h.$1||"null";d=k(d);return"');"+i[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(g).split("$1").join(f).split("$2").join(d?d.replace(/\s*([^\(]+)\s*(\((.*?)\))?/g,function(d,c,b,a){a=a?","+a+")":b?")":"";return a?"("+c+").call($item"+a:d}):h.$2||"")+"_.push('"})+"');}return _;")}function n(c,b){c._wrap=i(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function k(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,i;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(i=j.length-1;i>=0;i--)m(j[i]);m(k)}function m(j){var p,i=j,k,e,m;if(m=j.getAttribute(d)){while(i.parentNode&&(i=i.parentNode).nodeType===1&&!(p=i.getAttribute(d)));if(p!==m){i=i.parentNode?i.nodeType===11?0:i.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[i]||f[i],null,true);e.key=++h;b[h]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;i=a.data(j.parentNode,"tmplItem");i=i?i.key:0}if(e){k=e;while(k&&k.key!=i){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent,null,true)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);
(function($){'use strict';var counter=0;$.ajaxTransport('iframe',function(options,originalOptions,jqXHR){if(options.type==='POST'||options.type==='GET'){var form,iframe;return{send:function(headers,completeCallback){form=$('<form style="display:none;"></form>');iframe=$('<iframe src="javascript:false;" name="iframe-transport-'+(counter+=1)+'"></iframe>').bind('load',function(){var fileInputClones;iframe.unbind('load').bind('load',function(){var response;try{response=iframe.contents();if(!response.length||!response[0].firstChild){throw new Error();}}catch(e){response=undefined}completeCallback(200,'success',{'iframe':response});$('<iframe src="javascript:false;"></iframe>').appendTo(form);form.remove()});form.prop('target',iframe.prop('name')).prop('action',options.url).prop('method',options.type);if(options.formData){$.each(options.formData,function(index,field){$('<input type="hidden"/>').prop('name',field.name).val(field.value).appendTo(form)})}if(options.fileInput&&options.fileInput.length&&options.type==='POST'){fileInputClones=options.fileInput.clone();options.fileInput.after(function(index){return fileInputClones[index]});if(options.paramName){options.fileInput.each(function(){$(this).prop('name',options.paramName)})}form.append(options.fileInput).prop('enctype','multipart/form-data').prop('encoding','multipart/form-data')}form.submit();if(fileInputClones&&fileInputClones.length){options.fileInput.each(function(index,input){var clone=$(fileInputClones[index]);$(input).prop('name',clone.prop('name'));clone.replaceWith(input)})}});form.append(iframe).appendTo('body')},abort:function(){if(iframe){iframe.unbind('load').prop('src','javascript'.concat(':false;'))}if(form){form.remove()}}}}});$.ajaxSetup({converters:{'iframe text':function(iframe){return iframe.text()},'iframe json':function(iframe){return $.parseJSON(iframe.text())},'iframe html':function(iframe){return iframe.find('body').html()},'iframe script':function(iframe){return $.globalEval(iframe.text())}}})}(jQuery));
(function($){'use strict';$.widget('blueimp.fileupload',{options:{namespace:undefined,dropZone:$(document),fileInput:undefined,replaceFileInput:true,paramName:undefined,singleFileUploads:true,limitMultiFileUploads:undefined,sequentialUploads:false,limitConcurrentUploads:undefined,forceIframeTransport:false,multipart:true,maxChunkSize:undefined,uploadedBytes:undefined,recalculateProgress:true,formData:function(form){return form.serializeArray()},add:function(e,data){data.submit()},processData:false,contentType:false,cache:false},_refreshOptionsList:['namespace','dropZone','fileInput'],_isXHRUpload:function(options){var undef='undefined';return!options.forceIframeTransport&&typeof XMLHttpRequestUpload!==undef&&typeof File!==undef&&(!options.multipart||typeof FormData!==undef)},_getFormData:function(options){var formData;if(typeof options.formData==='function'){return options.formData(options.form)}else if($.isArray(options.formData)){return options.formData}else if(options.formData){formData=[];$.each(options.formData,function(name,value){formData.push({name:name,value:value})});return formData}return[]},_getTotal:function(files){var total=0;$.each(files,function(index,file){total+=file.size||1});return total},_onProgress:function(e,data){if(e.lengthComputable){var total=data.total||this._getTotal(data.files),loaded=parseInt(e.loaded/e.total*(data.chunkSize||total),10)+(data.uploadedBytes||0);this._loaded+=loaded-(data.loaded||data.uploadedBytes||0);data.lengthComputable=true;data.loaded=loaded;data.total=total;this._trigger('progress',e,data);this._trigger('progressall',e,{lengthComputable:true,loaded:this._loaded,total:this._total})}},_initProgressListener:function(options){var that=this,xhr=options.xhr?options.xhr():$.ajaxSettings.xhr();if(xhr.upload&&xhr.upload.addEventListener){xhr.upload.addEventListener('progress',function(e){that._onProgress(e,options)},false);options.xhr=function(){return xhr}}},_initXHRData:function(options){var formData,file=options.files[0];if(!options.multipart||options.blob){options.headers=$.extend(options.headers,{'X-File-Name':file.name,'X-File-Type':file.type,'X-File-Size':file.size});if(!options.blob){options.contentType=file.type;options.data=file}else if(!options.multipart){options.contentType='application/octet-stream';options.data=options.blob}}if(options.multipart&&typeof FormData!=='undefined'){if(options.formData instanceof FormData){formData=options.formData}else{formData=new FormData();$.each(this._getFormData(options),function(index,field){formData.append(field.name,field.value)})}if(options.blob){formData.append(options.paramName,options.blob)}else{$.each(options.files,function(index,file){if(file instanceof Blob){formData.append(options.paramName,file)}})}options.data=formData}options.blob=null},_initIframeSettings:function(options){options.dataType='iframe '+(options.dataType||'');options.formData=this._getFormData(options)},_initDataSettings:function(options){if(this._isXHRUpload(options)){if(!this._chunkedUpload(options,true)){if(!options.data){this._initXHRData(options)}this._initProgressListener(options)}}else{this._initIframeSettings(options)}},_initFormSettings:function(options){if(!options.form||!options.form.length){options.form=$(options.fileInput.prop('form'))}if(!options.paramName){options.paramName=options.fileInput.prop('name')||'files[]'}if(!options.url){options.url=options.form.prop('action')||location.href}options.type=(options.type||options.form.prop('method')||'').toUpperCase();if(options.type!=='POST'&&options.type!=='PUT'){options.type='POST'}},_getAJAXSettings:function(data){var options=$.extend({},this.options,data);this._initFormSettings(options);this._initDataSettings(options);return options},_enhancePromise:function(promise){promise.success=promise.done;promise.error=promise.fail;promise.complete=promise.always;return promise},_getXHRPromise:function(resolveOrReject,context,args){var dfd=$.Deferred(),promise=dfd.promise();context=context||this.options.context||promise;if(resolveOrReject===true){dfd.resolveWith(context,args)}else if(resolveOrReject===false){dfd.rejectWith(context,args)}promise.abort=dfd.promise;return this._enhancePromise(promise)},_chunkedUpload:function(options,testOnly){var that=this,file=options.files[0],fs=file.size,ub=options.uploadedBytes=options.uploadedBytes||0,mcs=options.maxChunkSize||fs,slice=file.webkitSlice||file.mozSlice||file.slice,upload,n,jqXHR,pipe;if(!(this._isXHRUpload(options)&&slice&&(ub||mcs<fs))||options.data){return false}if(testOnly){return true}if(ub>=fs){file.error='uploadedBytes';return this._getXHRPromise(false)}n=Math.ceil((fs-ub)/mcs);upload=function(i){if(!i){return that._getXHRPromise(true)}return upload(i-=1).pipe(function(){var o=$.extend({},options);o.blob=slice.call(file,ub+i*mcs,ub+(i+1)*mcs);o.chunkSize=o.blob.size;that._initXHRData(o);that._initProgressListener(o);jqXHR=($.ajax(o)||that._getXHRPromise(false,o.context)).done(function(){if(!o.loaded){that._onProgress($.Event('progress',{lengthComputable:true,loaded:o.chunkSize,total:o.chunkSize}),o)}options.uploadedBytes=o.uploadedBytes+=o.chunkSize});return jqXHR})};pipe=upload(n);pipe.abort=function(){return jqXHR.abort()};return this._enhancePromise(pipe)},_beforeSend:function(e,data){if(this._active===0){this._trigger('start')}this._active+=1;this._loaded+=data.uploadedBytes||0;this._total+=this._getTotal(data.files)},_onDone:function(result,textStatus,jqXHR,options){if(!this._isXHRUpload(options)){this._onProgress($.Event('progress',{lengthComputable:true,loaded:1,total:1}),options)}options.result=result;options.textStatus=textStatus;options.jqXHR=jqXHR;this._trigger('done',null,options)},_onFail:function(jqXHR,textStatus,errorThrown,options){options.jqXHR=jqXHR;options.textStatus=textStatus;options.errorThrown=errorThrown;this._trigger('fail',null,options);if(options.recalculateProgress){this._loaded-=options.loaded||options.uploadedBytes||0;this._total-=options.total||this._getTotal(options.files)}},_onAlways:function(result,textStatus,jqXHR,errorThrown,options){this._active-=1;options.result=result;options.textStatus=textStatus;options.jqXHR=jqXHR;options.errorThrown=errorThrown;this._trigger('always',null,options);if(this._active===0){this._trigger('stop');this._loaded=this._total=0}},_onSend:function(e,data){var that=this,jqXHR,slot,pipe,options=that._getAJAXSettings(data),send=function(resolve,args){that._sending+=1;jqXHR=jqXHR||((resolve!==false&&that._trigger('send',e,options)!==false&&(that._chunkedUpload(options)||$.ajax(options)))||that._getXHRPromise(false,options.context,args)).done(function(result,textStatus,jqXHR){that._onDone(result,textStatus,jqXHR,options)}).fail(function(jqXHR,textStatus,errorThrown){that._onFail(jqXHR,textStatus,errorThrown,options)}).always(function(a1,a2,a3){that._sending-=1;if(a3&&a3.done){that._onAlways(a1,a2,a3,undefined,options)}else{that._onAlways(undefined,a2,a1,a3,options)}if(options.limitConcurrentUploads&&options.limitConcurrentUploads>that._sending){var nextSlot=that._slots.shift();while(nextSlot){if(!nextSlot.isRejected()){nextSlot.resolve();break}nextSlot=that._slots.shift()}}});return jqXHR};this._beforeSend(e,options);if(this.options.sequentialUploads||(this.options.limitConcurrentUploads&&this.options.limitConcurrentUploads<=this._sending)){if(this.options.limitConcurrentUploads>1){slot=$.Deferred();this._slots.push(slot);pipe=slot.pipe(send)}else{pipe=(this._sequence=this._sequence.pipe(send,send))}pipe.abort=function(){var args=[undefined,'abort','abort'];if(!jqXHR){if(slot){slot.rejectWith(args)}return send(false,args)}return jqXHR.abort()};return this._enhancePromise(pipe)}return send()},_onAdd:function(e,data){var that=this,result=true,options=$.extend({},this.options,data),fileSet=data.files,limit=options.limitMultiFileUploads,i;if(!(options.singleFileUploads||limit)||!this._isXHRUpload(options)){fileSet=[fileSet]}else if(!options.singleFileUploads&&limit){fileSet=[];for(i=0;i<data.files.length;i+=limit){fileSet.push(data.files.slice(i,i+limit))}}$.each(fileSet,function(index,file){var files=$.isArray(file)?file:[file],newData=$.extend({},data,{files:files});newData.submit=function(){return that._onSend(e,newData)};return(result=that._trigger('add',e,newData))});return result},_normalizeFile:function(index,file){if(file.name===undefined&&file.size===undefined){file.name=file.fileName;file.size=file.fileSize}},_replaceFileInput:function(input){var inputClone=input.clone(true);$('<form></form>').append(inputClone)[0].reset();input.after(inputClone).detach();$.cleanData(input.unbind('remove'));this.options.fileInput=this.options.fileInput.map(function(i,el){if(el===input[0]){return inputClone[0]}return el});if(input[0]===this.element[0]){this.element=inputClone}},_onChange:function(e){var that=e.data.fileupload,data={files:$.each($.makeArray(e.target.files),that._normalizeFile),fileInput:$(e.target),form:$(e.target.form)};if(!data.files.length){data.files=[{name:e.target.value.replace(/^.*\\/,'')}]}if(that.options.replaceFileInput){that._replaceFileInput(data.fileInput)}if(that._trigger('change',e,data)===false||that._onAdd(e,data)===false){return false}},_onDrop:function(e){var that=e.data.fileupload,dataTransfer=e.dataTransfer=e.originalEvent.dataTransfer,data={files:$.each($.makeArray(dataTransfer&&dataTransfer.files),that._normalizeFile)};if(that._trigger('drop',e,data)===false||that._onAdd(e,data)===false){return false}e.preventDefault()},_onDragOver:function(e){var that=e.data.fileupload,dataTransfer=e.dataTransfer=e.originalEvent.dataTransfer;if(that._trigger('dragover',e)===false){return false}if(dataTransfer){dataTransfer.dropEffect=dataTransfer.effectAllowed='copy'}e.preventDefault()},_initEventHandlers:function(){var ns=this.options.namespace||this.widgetName;this.options.dropZone.bind('dragover.'+ns,{fileupload:this},this._onDragOver).bind('drop.'+ns,{fileupload:this},this._onDrop);this.options.fileInput.bind('change.'+ns,{fileupload:this},this._onChange)},_destroyEventHandlers:function(){var ns=this.options.namespace||this.widgetName;this.options.dropZone.unbind('dragover.'+ns,this._onDragOver).unbind('drop.'+ns,this._onDrop);this.options.fileInput.unbind('change.'+ns,this._onChange)},_beforeSetOption:function(key,value){this._destroyEventHandlers()},_afterSetOption:function(key,value){var options=this.options;if(!options.fileInput){options.fileInput=$()}if(!options.dropZone){options.dropZone=$()}this._initEventHandlers()},_setOption:function(key,value){var refresh=$.inArray(key,this._refreshOptionsList)!==-1;if(refresh){this._beforeSetOption(key,value)}$.Widget.prototype._setOption.call(this,key,value);if(refresh){this._afterSetOption(key,value)}},_create:function(){var options=this.options;if(options.fileInput===undefined){options.fileInput=this.element.is('input:file')?this.element:this.element.find('input:file')}else if(!options.fileInput){options.fileInput=$()}if(!options.dropZone){options.dropZone=$()}this._slots=[];this._sequence=this._getXHRPromise(true);this._sending=this._active=this._loaded=this._total=0;this._initEventHandlers()},destroy:function(){this._destroyEventHandlers();$.Widget.prototype.destroy.call(this)},enable:function(){$.Widget.prototype.enable.call(this);this._initEventHandlers()},disable:function(){this._destroyEventHandlers();$.Widget.prototype.disable.call(this)},add:function(data){if(!data||this.options.disabled){return}data.files=$.each($.makeArray(data.files),this._normalizeFile);this._onAdd(null,data)},send:function(data){if(data&&!this.options.disabled){data.files=$.each($.makeArray(data.files),this._normalizeFile);if(data.files.length){return this._onSend(null,data)}}return this._getXHRPromise(false,data&&data.context)}})}(jQuery));
(function($){'use strict';$.widget('blueimpUI.fileupload',$.blueimp.fileupload,{options:{autoUpload:false,maxNumberOfFiles:undefined,maxFileSize:undefined,minFileSize:1,acceptFileTypes:/.+$/i,previewFileTypes:/^image\/(gif|jpeg|png)$/,previewMaxWidth:80,previewMaxHeight:80,previewAsCanvas:true,uploadTemplate:$('#template-upload'),downloadTemplate:$('#template-download'),dataType:'json',add:function(e,data){var that=$(this).data('fileupload');that._adjustMaxNumberOfFiles(-data.files.length);data.isAdjusted=true;data.isValidated=that._validate(data.files);data.context=that._renderUpload(data.files).appendTo($(this).find('.files')).fadeIn(function(){$(this).show()}).data('data',data);if((that.options.autoUpload||data.autoUpload)&&data.isValidated){data.jqXHR=data.submit()}},send:function(e,data){if(!data.isValidated){var that=$(this).data('fileupload');if(!data.isAdjusted){that._adjustMaxNumberOfFiles(-data.files.length)}if(!that._validate(data.files)){return false}}if(data.context&&data.dataType&&data.dataType.substr(0,6)==='iframe'){data.context.find('.ui-progressbar').progressbar('value',parseInt(100,10))}},done:function(e,data){var that=$(this).data('fileupload');if(data.context){data.context.each(function(index){var file=($.isArray(data.result)&&data.result[index])||{error:'emptyResult'};if(file.error){that._adjustMaxNumberOfFiles(1)}$(this).fadeOut(function(){that._renderDownload([file]).css('display','none').replaceAll(this).fadeIn(function(){$(this).show()})})})}else{that._renderDownload(data.result).css('display','none').appendTo($(this).find('.files')).fadeIn(function(){$(this).show()})}},fail:function(e,data){var that=$(this).data('fileupload');that._adjustMaxNumberOfFiles(data.files.length);if(data.context){data.context.each(function(index){$(this).fadeOut(function(){if(data.errorThrown!=='abort'){var file=data.files[index];file.error=file.error||data.errorThrown||true;that._renderDownload([file]).css('display','none').replaceAll(this).fadeIn(function(){$(this).show()})}else{data.context.remove()}})})}else if(data.errorThrown!=='abort'){that._adjustMaxNumberOfFiles(-data.files.length);data.context=that._renderUpload(data.files).css('display','none').appendTo($(this).find('.files')).fadeIn(function(){$(this).show()}).data('data',data)}},progress:function(e,data){if(data.context){data.context.find('.ui-progressbar').progressbar('value',parseInt(data.loaded/data.total*100,10))}},progressall:function(e,data){$(this).find('.fileupload-progressbar').progressbar('value',parseInt(data.loaded/data.total*100,10))},start:function(){$(this).find('.fileupload-progressbar').progressbar('value',0).fadeIn()},stop:function(){$(this).find('.fileupload-progressbar').fadeOut()},destroy:function(e,data){var that=$(this).data('fileupload');if(data.url){$.ajax(data).success(function(){that._adjustMaxNumberOfFiles(1);$(this).fadeOut(function(){$(this).remove()})})}else{that._adjustMaxNumberOfFiles(1);data.context.fadeOut(function(){$(this).remove()})}}},_scaleImage:function(img,options){options=options||{};var canvas=document.createElement('canvas'),scale=Math.min((options.maxWidth||img.width)/img.width,(options.maxHeight||img.height)/img.height);if(scale>=1){scale=Math.max((options.minWidth||img.width)/img.width,(options.minHeight||img.height)/img.height)}img.width=parseInt(img.width*scale,10);img.height=parseInt(img.height*scale,10);if(!options.canvas||!canvas.getContext){return img}canvas.width=img.width;canvas.height=img.height;canvas.getContext('2d').drawImage(img,0,0,img.width,img.height);return canvas},_createObjectURL:function(file){var undef='undefined',urlAPI=(typeof window.createObjectURL!==undef&&window)||(typeof URL!==undef&&URL)||(typeof webkitURL!==undef&&webkitURL);return urlAPI?urlAPI.createObjectURL(file):false},_revokeObjectURL:function(url){var undef='undefined',urlAPI=(typeof window.revokeObjectURL!==undef&&window)||(typeof URL!==undef&&URL)||(typeof webkitURL!==undef&&webkitURL);return urlAPI?urlAPI.revokeObjectURL(url):false},_loadFile:function(file,callback){if(typeof FileReader!=='undefined'&&FileReader.prototype.readAsDataURL){var fileReader=new FileReader();fileReader.onload=function(e){callback(e.target.result)};fileReader.readAsDataURL(file);return true}return false},_loadImage:function(file,callback,options){var that=this,url,img;if(!options||!options.fileTypes||options.fileTypes.test(file.type)){url=this._createObjectURL(file);img=$('<img>').bind('load',function(){$(this).unbind('load');that._revokeObjectURL(url);callback(that._scaleImage(img[0],options))});if(url){img.prop('src',url);return true}else{return this._loadFile(file,function(url){img.prop('src',url)})}}return false},_enableDragToDesktop:function(){var link=$(this),url=link.prop('href'),name=decodeURIComponent(url.split('/').pop()).replace(/:/g,'-'),type='application/octet-stream';link.bind('dragstart',function(e){try{e.originalEvent.dataTransfer.setData('DownloadURL',[type,name,url].join(':'))}catch(err){}})},_adjustMaxNumberOfFiles:function(operand){if(typeof this.options.maxNumberOfFiles==='number'){this.options.maxNumberOfFiles+=operand;if(this.options.maxNumberOfFiles<1){this._disableFileInputButton()}else{this._enableFileInputButton()}}},_formatFileSize:function(file){if(typeof file.size!=='number'){return''}if(file.size>=1000000000){return(file.size/1000000000).toFixed(2)+' GB'}if(file.size>=1000000){return(file.size/1000000).toFixed(2)+' MB'}return(file.size/1000).toFixed(2)+' KB'},_hasError:function(file){if(file.error){return file.error}if(this.options.maxNumberOfFiles<0){return'maxNumberOfFiles'}if(!(this.options.acceptFileTypes.test(file.type)||this.options.acceptFileTypes.test(file.name))){return'acceptFileTypes'}if(this.options.maxFileSize&&file.size>this.options.maxFileSize){return'maxFileSize'}if(typeof file.size==='number'&&file.size<this.options.minFileSize){return'minFileSize'}return null},_validate:function(files){var that=this,valid=!!files.length;$.each(files,function(index,file){file.error=that._hasError(file);if(file.error){valid=false}});return valid},_uploadTemplateHelper:function(file){file.sizef=this._formatFileSize(file);return file},_renderUploadTemplate:function(files){var that=this;return $.tmpl(this.options.uploadTemplate,$.map(files,function(file){return that._uploadTemplateHelper(file)}))},_renderUpload:function(files){var that=this,options=this.options,tmpl=this._renderUploadTemplate(files),isValidated=this._validate(files);if(!(tmpl instanceof $)){return $()}tmpl.css('display','none');tmpl.find('.progress div').slice(isValidated?1:0).remove().end().first().progressbar();tmpl.find('.start button').slice(this.options.autoUpload||!isValidated?0:1).remove().end().first().button({text:false,icons:{primary:'ui-icon-circle-arrow-e'}});tmpl.find('.cancel button').slice(1).remove().end().first().button({text:false,icons:{primary:'ui-icon-cancel'}});tmpl.find('.preview').each(function(index,node){that._loadImage(files[index],function(img){$(img).hide().appendTo(node).fadeIn()},{maxWidth:options.previewMaxWidth,maxHeight:options.previewMaxHeight,fileTypes:options.previewFileTypes,canvas:options.previewAsCanvas})});return tmpl},_downloadTemplateHelper:function(file){file.sizef=this._formatFileSize(file);return file},_renderDownloadTemplate:function(files){var that=this;return $.tmpl(this.options.downloadTemplate,$.map(files,function(file){return that._downloadTemplateHelper(file)}))},_renderDownload:function(files){var tmpl=this._renderDownloadTemplate(files);if(!(tmpl instanceof $)){return $()}tmpl.css('display','none');tmpl.find('.delete button').button({text:false,icons:{primary:'ui-icon-trash'}});tmpl.find('a').each(this._enableDragToDesktop);return tmpl},_startHandler:function(e){e.preventDefault();var tmpl=$(this).closest('.template-upload'),data=tmpl.data('data');if(data&&data.submit&&!data.jqXHR){data.jqXHR=data.submit();$(this).fadeOut()}},_cancelHandler:function(e){e.preventDefault();var tmpl=$(this).closest('.template-upload'),data=tmpl.data('data')||{};if(!data.jqXHR){data.errorThrown='abort';e.data.fileupload._trigger('fail',e,data)}else{data.jqXHR.abort()}},_deleteHandler:function(e){e.preventDefault();var button=$(this);e.data.fileupload._trigger('destroy',e,{context:button.closest('.template-download'),url:button.attr('data-url'),type:button.attr('data-type'),dataType:e.data.fileupload.options.dataType})},_initEventHandlers:function(){$.blueimp.fileupload.prototype._initEventHandlers.call(this);var filesList=this.element.find('.files'),eventData={fileupload:this};filesList.find('.start button').live('click.'+this.options.namespace,eventData,this._startHandler);filesList.find('.cancel button').live('click.'+this.options.namespace,eventData,this._cancelHandler);filesList.find('.delete button').live('click.'+this.options.namespace,eventData,this._deleteHandler)},_destroyEventHandlers:function(){var filesList=this.element.find('.files');filesList.find('.start button').die('click.'+this.options.namespace);filesList.find('.cancel button').die('click.'+this.options.namespace);filesList.find('.delete button').die('click.'+this.options.namespace);$.blueimp.fileupload.prototype._destroyEventHandlers.call(this)},_initFileUploadButtonBar:function(){var fileUploadButtonBar=this.element.find('.fileupload-buttonbar'),filesList=this.element.find('.files'),ns=this.options.namespace;fileUploadButtonBar.addClass('ui-widget-header ui-corner-top');this.element.find('.fileinput-button').each(function(){var fileInput=$(this).find('input:file').detach();$(this).button({icons:{primary:'ui-icon-plusthick'}}).append(fileInput)});fileUploadButtonBar.find('.start').button({icons:{primary:'ui-icon-circle-arrow-e'}}).bind('click.'+ns,function(e){e.preventDefault();filesList.find('.start button').click()});fileUploadButtonBar.find('.cancel').button({icons:{primary:'ui-icon-cancel'}}).bind('click.'+ns,function(e){e.preventDefault();filesList.find('.cancel button').click()});fileUploadButtonBar.find('.delete').button({icons:{primary:'ui-icon-trash'}}).bind('click.'+ns,function(e){e.preventDefault();filesList.find('.delete button').click()})},_destroyFileUploadButtonBar:function(){this.element.find('.fileupload-buttonbar').removeClass('ui-widget-header ui-corner-top');this.element.find('.fileinput-button').each(function(){var fileInput=$(this).find('input:file').detach();$(this).button('destroy').append(fileInput)});this.element.find('.fileupload-buttonbar button').unbind('click.'+this.options.namespace).button('destroy')},_enableFileInputButton:function(){this.element.find('.fileinput-button input:file:disabled').each(function(){var fileInput=$(this),button=fileInput.parent();fileInput.detach().prop('disabled',false);button.button('enable').append(fileInput)})},_disableFileInputButton:function(){this.element.find('.fileinput-button input:file:enabled').each(function(){var fileInput=$(this),button=fileInput.parent();fileInput.detach().prop('disabled',true);button.button('disable').append(fileInput)})},_initTemplates:function(){if(this.options.uploadTemplate instanceof $&&!this.options.uploadTemplate.length){this.options.uploadTemplate=$(this.options.uploadTemplate.selector)}if(this.options.downloadTemplate instanceof $&&!this.options.downloadTemplate.length){this.options.downloadTemplate=$(this.options.downloadTemplate.selector)}},_create:function(){$.blueimp.fileupload.prototype._create.call(this);this._initTemplates();this.element.addClass('ui-widget');this._initFileUploadButtonBar();this.element.find('.fileupload-content').addClass('ui-widget-content ui-corner-bottom');this.element.find('.fileupload-progressbar').hide().progressbar()},destroy:function(){this.element.find('.fileupload-progressbar').progressbar('destroy');this.element.find('.fileupload-content').removeClass('ui-widget-content ui-corner-bottom');this._destroyFileUploadButtonBar();this.element.removeClass('ui-widget');$.blueimp.fileupload.prototype.destroy.call(this)},enable:function(){$.blueimp.fileupload.prototype.enable.call(this);this.element.find(':ui-button').not('.fileinput-button').button('enable');this._enableFileInputButton()},disable:function(){this.element.find(':ui-button').not('.fileinput-button').button('disable');this._disableFileInputButton();$.blueimp.fileupload.prototype.disable.call(this)}})}(jQuery));

$(function () {
    $('#fileupload').fileupload({
        url: '/index/upload',
        autoUpload: true
    });

    // Load existing files:
    $.getJSON($('#fileupload form').prop('action'), function (files) {
        var fu = $('#fileupload').data('fileupload');
        fu._adjustMaxNumberOfFiles(-files.length);
        fu._renderDownload(files)
            .appendTo($('#fileupload .files'))
            .fadeIn(function () {
                // Fix for IE7 and lower:
                $(this).show();
            });
    });
    
    //$('.fileupload-progressbar').progressbar();

    $('#other').change(function () {
		if ($(this).is(':checked')) {
			$('#contact_company_other-label').show();
			$('#contact_company_other-element').show();
			$('#contact_nip_other-label').show();
			$('#contact_nip_other-element').show();
			$('#contact_address_other-label').show();
			$('#contact_address_other-element').show();
		} else {
			$('#contact_company_other-label').hide();
			$('#contact_company_other-element').hide();
			$('#contact_nip_other-label').hide();
			$('#contact_nip_other-element').hide();
			$('#contact_address_other-label').hide();
			$('#contact_address_other-element').hide();
		}
	}).change();
});
