NDOJ/resources/fine-uploader/jquery.fine-uploader.min.js.map
2021-11-27 21:28:48 -06:00

1 line
No EOL
621 KiB
Text

{"version":3,"sources":["?","../client/js/jquery-plugin.js","../client/js/jquery-dnd.js","../client/js/util.js","../client/js/export.js","../client/js/error/error.js","../client/js/version.js","../client/js/features.js","../client/js/promise.js","../client/js/blob-proxy.js","../client/js/button.js","../client/js/upload-data.js","../client/js/uploader.basic.api.js","../client/js/uploader.basic.js","../client/js/ajax.requester.js","../client/js/upload-handler/upload.handler.js","../client/js/upload-handler/upload.handler.controller.js","../client/js/window.receive.message.js","../client/js/upload-handler/form.upload.handler.js","../client/js/upload-handler/xhr.upload.handler.js","../client/js/deletefile.ajax.requester.js","../client/js/image-support/megapix-image.js","../client/js/image-support/image.js","../client/js/image-support/exif.js","../client/js/identify.js","../client/js/image-support/validation.image.js","../client/js/session.js","../client/js/session.ajax.requester.js","../client/js/image-support/scaler.js","../client/js/third-party/ExifRestorer.js","../client/js/total-progress.js","../client/js/paste.js","../client/js/form-support.js","../client/js/traditional/traditional.form.upload.handler.js","../client/js/traditional/traditional.xhr.upload.handler.js","../client/js/traditional/all-chunks-done.ajax.requester.js","../client/js/dnd.js","../client/js/uploader.api.js","../client/js/uploader.js","../client/js/templating.js","../client/js/ui.handler.events.js","../client/js/ui.handler.click.filebuttons.js","../client/js/ui.handler.click.filename.js","../client/js/ui.handler.focusin.filenameinput.js","../client/js/ui.handler.focus.filenameinput.js","../client/js/ui.handler.edit.filename.js"],"names":["global","$","init","options","xformedOpts","transformVariables","newUploaderInstance","getNewUploaderInstance","uploader","addCallbacks","$el","params","uploaderType","pluginOption","namespace","charAt","toUpperCase","slice","toLowerCase","qq","FineUploader","dataStore","key","val","data","undefined","instanceToStore","option","optionVal","transformedOpts","callbacks","each","_options","prop","nonJqueryCallback","name","callbackEventTarget","exec","substring","nonJqueryCallbackRetVal","jqueryEventCallbackRetVal","originalArgs","Array","prototype","call","arguments","transformedArgs","idx","arg","push","maybeWrapInJquery","apply","this","triggerHandler","error","log","message","source","dest","xformed","arrayVals","element","inArray","pluginOptions","isPlainObject","isArray","arrayVal","arrayObjDest","merge","isValidCommand","command","type","match","delegateCommand","retVal","xformedArgs","origArgs","transformedVal","nodeType","cloneNode","fn","fineUploader","optionsOrCommand","self","selfArgs","retVals","index","el","length","jQuery","dropZoneElements","dnd","DragAndDrop","func","$callbackEl","args","fineUploaderDnd","hide","style","display","attach","addEventListener","attachEvent","detach","removeEventListener","detachEvent","contains","descendant","compareDocumentPosition","insertBefore","elementB","parentNode","remove","removeChild","css","styles","Error","opacity","filter","Math","round","extend","hasClass","considerParent","re","RegExp","test","className","addClass","removeClass","replace","getByClass","first","candidates","result","querySelector","querySelectorAll","getElementsByTagName","getFirstByClass","children","child","firstChild","nextSibling","setText","text","innerText","textContent","clearText","hasAttribute","attrName","attrVal","getAttribute","canvasToBlob","canvas","mime","quality","dataUriToBlob","toDataURL","dataUri","arrayBuffer","byteString","intArray","mimeString","createBlob","BlobBuilder","window","WebKitBlobBuilder","MozBlobBuilder","MSBlobBuilder","blobBuilder","append","getBlob","Blob","split","indexOf","atob","decodeURI","ArrayBuffer","Uint8Array","character","charCodeAt","level","console","isObject","variable","Object","toString","isFunction","value","buffer","constructor","isItemList","maybeItemList","isNodeList","maybeNodeList","item","namedItem","isString","maybeString","trimStr","string","String","trim","format","str","newStr","nextIdxToReplace","isFile","maybeFile","File","isFileList","maybeFileList","FileList","isFileOrInput","maybeFileOrInput","isInput","maybeInput","notFile","evaluateType","normalizedType","HTMLInputElement","tagName","isBlob","maybeBlob","isXhrUploadSupported","input","document","createElement","multiple","FormData","createXhrInstance","upload","XMLHttpRequest","ActiveXObject","isFolderDropSupported","dataTransfer","items","webkitGetAsEntry","isFileChunkingSupported","androidStock","webkitSlice","mozSlice","sliceBlob","fileOrBlob","start","end","arrayBufferToHex","bytesAsHex","bytes","byt","byteAsHexStr","readBlobToHex","blob","startOffset","initialBlob","fileReader","FileReader","promise","Promise","onload","success","onerror","failure","readAsArrayBuffer","second","extendNested","override","target","sourceFn","super_","srcPropName","srcPropVal","arr","elt","from","len","hasOwnProperty","getUniqueId","c","r","random","ie","navigator","userAgent","ie7","ie8","ie10","ie11","edge","safari","vendor","chrome","opera","firefox","windows","platform","android","ios6","ios","ios7","ios8","ios800","iosChrome","iosSafari","iosSafariWebView","preventDefault","e","returnValue","toElement","div","html","innerHTML","iterableItem","callback","keyOrIndex","Storage","getItem","bind","oldFunc","context","newArgs","concat","obj2url","obj","temp","prefixDone","uristrings","prefix","add","nextObj","i","nextTemp","encodeURIComponent","join","obj2FormData","formData","arrayKeyName","obj2Inputs","form","setAttribute","appendChild","parseJson","json","JSON","parse","eval","getExtension","filename","extIdx","lastIndexOf","substr","getFilename","blobOrFileInput","fileName","DisposeSupport","disposers","dispose","disposer","shift","addDisposer","disposeFunction","define","amd","module","exports","version","supportedFeatures","testSupportsFileInputElement","tempInput","supported","disabled","ex","isChrome14OrHigher","isCrossOriginXhrSupported","withCredentials","isXdrSupported","XDomainRequest","isCrossOriginAjaxSupported","isFolderSelectionSupported","webkitdirectory","isLocalStorageSupported","localStorage","setItem","isDragAndDropSupported","span","supportsUploading","supportsUploadingBlobs","supportsFileDrop","supportsAjaxFileUploading","supportsFolderDrop","supportsChunking","supportsResume","supportsUploadViaPaste","supportsUploadCors","supportsDeleteFileXdr","supportsDeleteFileCorsXhr","supportsDeleteFileCors","supportsFolderSelection","supportsImagePreviews","supportsUploadProgress","postMessage","ajaxUploading","blobUploading","canDetermineSize","chunking","deleteFileCors","deleteFileCorsXdr","deleteFileCorsXhr","dialogElement","HTMLDialogElement","fileDrop","folderDrop","folderSelection","imagePreviews","imageValidation","itemSizeValidation","pause","progressBar","resume","scaling","tiffPreviews","unlimitedScaledImageSize","uploading","uploadCors","uploadCustomHeaders","uploadNonMultipart","uploadViaPaste","isGenericPromise","maybePromise","then","successArgs","failureArgs","successCallbacks","failureCallbacks","doneCallbacks","state","onSuccess","onFailure","done","BlobProxy","referenceBlob","onCreate","create","UploadButton","o","createInput","BUTTON_ID_ATTR_NAME","buttonId","title","setMultiple","folders","acceptFiles","position","right","top","fontFamily","fontSize","margin","padding","cursor","height","disposeSupport","onChange","hoverClass","focusClass","ios8BrowserCrashWorkaround","overflow","direction","getInput","getButtonId","isMultiple","optInput","removeAttribute","setAcceptFiles","reset","UploadData","uploaderProxy","getDataByIds","idOrIds","entries","id","getDataByUuids","uuids","uuid","byUuid","getDataByStatus","status","statusResults","statuses","statusEnum","statusResultIndexes","byStatus","dataIndex","byProxyGroupId","byBatchId","addFile","spec","SUBMITTING","originalName","size","file","batchId","proxyGroupId","onBeforeStatusChange","onStatusChange","retrieve","optionalFilter","removeFileRef","record","setStatus","newStatus","oldStatus","byStatusOldStatusIndex","splice","uuidChanged","newUuid","oldUuid","updateName","newName","updateSize","newSize","setParentId","targetId","parentId","getIdsInProxyGroup","getIdsInBatch","SUBMITTED","REJECTED","QUEUED","CANCELED","PAUSED","UPLOADING","UPLOAD_FINALIZING","UPLOAD_RETRYING","UPLOAD_SUCCESSFUL","UPLOAD_FAILED","DELETE_FAILED","DELETING","DELETED","basePublicApi","addBlobs","blobDataOrArray","endpoint","addFiles","addInitialFiles","cannedFileList","cannedFile","_addCannedFile","_maybeHandleIos8SafariWorkaround","_storedIds","_currentBatchId","processBlob","_handleNewFile","blobs","defaultName","verifiedFiles","processBlobData","blobData","processCanvas","processCanvasData","canvasData","normalizedQuality","processFileOrInput","fileOrInput","files","normalizeData","fileContainer","_prepareItemsForUpload","cancel","uploadData","_uploadData","getName","_handler","cancelAll","storedIdsCopy","storedFileId","clearStoredFiles","continueUpload","enabled","_uploadFile","deleteFile","_onSubmitDelete","doesExist","fileOrBlobId","isValid","drawThumbnail","fileId","imgOrCanvas","maxSize","fromServer","customResizeFunction","fileOrUrl","promiseToReturn","_imageGenerator","_thumbnailUrls","scale","getFile","container","generate","modifiedContainer","reason","getButton","_getButton","_buttonIdsForFileIds","getEndpoint","_endpointStore","get","uploadDataRecord","getInProgress","getParentId","uploadDataEntry","getUploads","getResumableFilesData","getSize","getNetUploads","_netUploaded","getRemainingAllowedItems","allowedItems","_currentItemLimit","_netUploadedOrQueued","getUuid","isResumable","hasResumeRecord","debug","pauseUpload","expunge","_autoRetries","_retryTimeouts","_preventRetries","_buttons","button","_paramsStore","_pasteHandler","session","refreshOnReset","_refreshSessionData","_succeededSinceLastAllComplete","_failedSinceLastAllComplete","_totalProgress","_customResumeDataStore","retry","_manualRetry","scaleImage","specs","Scaler","setCustomHeaders","headers","_customHeadersStore","set","setCustomResumeData","setDeleteFileCustomHeaders","_deleteFileCustomHeadersStore","setDeleteFileEndpoint","_deleteFileEndpointStore","setDeleteFileParams","_deleteFileParamsStore","setEndpoint","setForm","elementOrId","_updateFormSupportAndParams","setItemLimit","newItemLimit","setName","setParams","setUuid","_onDeleteComplete","errorMessage","uploadStoredFiles","_itemError","_uploadStoredFiles","basePrivateApi","sessionData","deleteFileEndpoint","deleteFileParams","thumbnailUrl","_annotateWithButtonId","associatedInput","qqButtonId","_getButtonId","_batchError","onError","_createDeleteHandler","DeleteFileAjaxRequester","method","maxConnections","uuidParamName","request","uuidName","customHeaders","paramsStore","endpointStore","cors","onDelete","_onDelete","onDeleteComplete","xhrOrXdr","isError","_createPasteHandler","PasteSupport","targetElement","paste","pasteReceived","_handleCheckedCallback","onPasteReceived","_handlePasteSuccess","identifier","_createStore","initialValue","_readOnlyValues_","store","catchall","perIdReadOnlyValues","readOnlyValues","copy","orig","getReadOnlyValues","includeReadOnlyValues","existing","values","addReadOnly","_createUploadDataTracker","_onUploadStatusChange","_maybeAllComplete","setTimeout","_createUploadButton","allowMultiple","workarounds","iosEmptyVideos","_isAllowedExtension","allowedExtensions","accept","validation","classes","buttonFocus","buttonHover","ios8BrowserCrash","inputName","_onInputChange","fileInputTitle","_disposeSupport","_createUploadHandler","additionalOptions","lastOnProgress","preventRetryParam","preventRetryResponseProperty","onProgress","loaded","total","_onProgress","onComplete","xhr","_onComplete","onCancel","cancelFinalizationEffort","_onCancel","onUploadPrep","_onUploadPrep","onUpload","_onUpload","onUploadResult","onUploadChunk","chunkData","_onUploadChunk","onUploadChunkResult","partIndex","onUploadChunkSuccess","_onUploadChunkSuccess","onResume","customResumeData","onAutoRetry","responseJSON","_onAutoRetry","onUuidChanged","setSize","_setSize","getDataByUuid","isQueued","isInProgress","getCustomResumeData","_getCustomResumeData","UploadHandlerController","_fileOrBlobRejected","_formatSize","sizeSymbols","max","toFixed","_generateExtraButtonSpecs","_extraButtonSpecs","extraButtons","extraButtonOptionEntry","extraButtonSpec","_initExtraButton","extraButtonsSpec","_defaultButtonId","buttonOrFileInputOrFile","inputs","fileInput","fileBlobOrInput","_getNotFinished","_getValidationBase","_getValidationDescriptor","fileWrapper","_getValidationDescriptors","fileWrappers","fileDescriptors","_handleCameraAccess","camera","optionRoot","details","callbackRetVal","successParam","newFileWrapperList","actualFile","handler","_customNewFileHandler","_handleNewFileGeneric","addFileToHandler","_trackButton","fileList","extSuppliedName","extension","_handleDeleteSuccess","_handleDeleteFailed","_initFormSupportAndParams","_formSupport","FormSupport","attachedToForm","getFormInputsAsObject","autoUpload","newAutoUpload","newEndpoint","_isDeletePossible","expected","allowXdr","allowed","valid","allowedExt","extRegex","code","maybeNameOrNames","replacement","extensionsForMessage","placeholderMatch","messages","names","validationBase","allowedExtension","formatFileName","sizeLimit","minSizeLimit","placeholder","_onBeforeManualRetry","notFinished","_onAllComplete","ios8SafariUploads","alert","unsupportedBrowserIos8Safari","_maybeParseAndSendUploadError","response","errorReason","defaultResponseError","_maybeProcessNextItemAfterOnValidateCallback","validItem","stopOnFirstInvalidFile","validationDescriptor","onValidate","_onValidateCallbackSuccess","_onValidateCallbackFailure","successful","failed","onAllComplete","_shouldAutoRetry","retryWaitPeriod","autoAttemptDelay","_onBeforeAutoRetry","itemLimit","onManualRetry","clearTimeout","storedItemIndex","fileIndex","onIndividualProgress","_onSubmit","_onSubmitCallbackSuccess","_onSubmitted","onSubmitted","_storeForLater","onSuccessCallback","additionalMandatedParams","adjustedOnSuccessCallback","onSubmitDelete","_deleteHandler","sendDelete","_onTotalProgress","onTotalProgress","enableAuto","_onValidateBatchCallbackFailure","_onValidateBatchCallbackSuccess","validationDescriptors","proposedNetFilesUploadedOrQueued","tooManyItemsError","nextIndex","_validateFileOrBlobData","_upload","onValidateBatch","_preventLeaveInProgress","event","onLeave","Session","_session","addFileRecord","refresh","_sessionRequestComplete","onSessionRequestComplete","onNewSize","maxAutoAttempts","formElementOrId","onSubmit","idToUpload","stillSubmitting","validityChecker","allowEmpty","ImageValidation","validate","image","errorCode","_wrapCallbacks","safeCallback","errorMsg","exception","callbackName","callbackFunc","FineUploaderBasic","disableCancelForFormUploads","warnBeforeUnload","filenameParam","forceMultipart","omitDefaultParams","paramsInBody","requireSuccessJson","totalFileSizeName","maxHeight","maxWidth","minHeight","minWidth","maybeXhr","maybeXhrOrXdr","attemptNumber","fileOrBlobData","typeError","sizeError","minSizeError","emptyError","noFilesError","maxHeightImageError","maxWidthImageError","minHeightImageError","minWidthImageError","retryFailTooManyItems","concurrent","mandatory","paramNames","partByteOffset","chunkSize","totalFileSize","totalParts","partSize","jsonPayload","resetOnStatus","recordsExpireIn","resuming","customKeys","fileOrBlobName","sendCredentials","interceptSubmit","customResizer","sendOriginal","orient","defaultType","defaultQuality","failureText","includeExif","sizes","ImageGenerator","_scaler","handleNewFile","TotalProgress","entry","AjaxRequester","isSimpleMethod","containsNonSimpleHeaders","containsNonSimple","header","isXdr","getCorsAjaxTransport","ontimeout","onprogress","getXhrOrXdr","suppliedXhr","requestData","dequeue","nextId","queue","sendRequest","xdrError","isResponseSuccessful","getParams","onDemandParams","additionalParams","mandatedParams","optXhr","url","payload","onSend","createUrl","additionalQueryParams","getXdrLoadHandler","getXdrErrorHandler","onreadystatechange","getXhrReadyStateChangeHandler","registerForUploadProgress","open","setHeaders","send","shouldParamsBeInQueryString","contentType","stringify","addToPath","readyState","lengthComputable","onDemandHeaders","additionalHeaders","allHeaders","acceptHeader","setRequestHeader","allowXRequestedWithAndCacheControl","responseCode","successfulResponseCodes","prepareToSend","validMethods","DELETE","PATCH","POST","PUT","GET","initTransport","path","cacheBuster","withPath","appendToPath","withParams","withQueryParams","_additionalQueryParams_","withHeaders","withPayload","thePayload","withCacheBuster","qqtimestamp","Date","getTime","canceled","UploadHandler","proxy","fileState","fileItem","getThirdPartyFileId","_getFileState","_setThirdPartyFileId","thirdPartyFileId","_wasCanceled","preventRetryResponse","controller","chunkingPossible","concurrentChunkingPossible","chunked","chunkIdx","_getChunkData","attemptingResume","chunkProgress","_getChunkDataForCallback","finalize","finalizeChunks","normaizedResponse","normalizeResponse","_maybeDeletePersistedChunkData","cleanup","normalizedResponse","handleFailure","clearCachedChunk","inProgressIdx","responseToReport","inProgressChunksArray","inProgress","remaining","unshift","ignoreFailure","keys","_getXhrs","ckid","ckXhr","abort","_cancelled","moveInProgressToRemaining","connectionManager","free","hasMoreParts","nextPart","nextIdx","_getTotalChunks","reevaluateChunking","sendNext","inProgressChunks","available","requestOverrides","uploadChunkData","overrides","uploadChunk","inProgressChunkIdx","_maybePersistChunkedState","clearXhr","_open","_openChunks","_waiting","openChunkEntriesCount","openChunksCount","openChunkIndexes","dontAllowNext","allowNext","waitingIndex","connectionsIndex","getProxyOrBlob","getWaitingOrConnected","waitingOrConnected","chunks","parseInt","isUsingConnection","pop","openChunksEntry","simple","uploadFile","maybeNewUuid","_clearXhrs","getProxy","initHandler","traditional","onFinalizing","_removeExpiredChunkingRecords","isDeferredEligibleForUpload","maybeDefer","generatedBlob","updateBlob","maybeSendDeferredFiles","errorResponse","idsInGroup","uploadedThisId","idInGroup","now","originalResponse","_shouldChunkThisFile","blobToUpload","cancelRetVal","isProxied","_getLocalStorageId","isAttemptingResume","WindowReceiveMessage","callbackWrapperDetachers","receiveMessage","onMessageCallbackWrapper","stopReceivingMessages","detacher","FormUploadHandler","expungeFile","detachLoadEvents","isCors","postMessageCallbackTimers","corsMessageReceiver","iframe","getElementById","_getIframeName","getFileIdForIframeName","iframeName","initIframeForUpload","body","registerPostMessageCallback","onloadCallbacks","onloadCallback","_parseJsonResponse","_detachLoadEvent","formHandlerInstanceId","_attachLoadEvent","responseDescriptor","contentDocument","_createIframe","_initFormForUpload","targetName","innerHtmlOrMessage","XhrUploadHandler","xhrId","ajaxRequester","_getAjaxRequester","getChunkSize","chunkFiles","resumeEnabled","blobOrProxy","_initTempState","_maybePrepareForResume","cachedChunks","tempState","xhrs","ajaxRequesters","responseParser","lastChunkIdx","_getXhr","resumableFilesData","_iterateResumeRecords","notResumable","optInProgress","optRemaining","chunkingState","reverse","paused","totalChunks","parts","newBlob","chunkId","_createXhr","optChunkIdx","_registerXhr","chunkIndex","fileSize","startBytes","endBytes","part","count","startByte","endByte","localStorageId","forEach","_getMimeType","_getPersistableData","ceil","_markNotResumable","removeItem","persistedData","lastUpdated","_registerProgressHandler","progressCalculator","totalSuccessfullyLoadedForFile","loadedForRequest","totalForRequest","estActualChunkLoaded","totalLoadedForFile","chunkLoaded","optAjaxRequester","xhrsId","expirationDays","expirationDate","setDate","getDate","getMandatedParams","_method","requester","detectSubsampling","img","ctx","iw","naturalWidth","ih","naturalHeight","width","getContext","drawImage","getImageData","detectVerticalSquash","alpha","ratio","sy","ey","py","renderImageToDataURL","doSquash","renderImageToCanvas","maybeCalculateDownsampledDimensions","origHeight","origWidth","newHeight","sqrt","newWidth","modifiedDimensions","save","resize","renderImageToCanvasWithCustomResizer","imageHeight","imageWidth","orientation","targetHeight","targetWidth","transformCoordinate","tmpCtx","sx","dx","d","tmpCanvas","vertSquashRatio","dw","dh","dy","clearRect","restore","qqImageRendered","resizeInfo","sourceCanvas","sourceCanvasContext","targetCanvas","translate","rotate","PI","MegaPixImage","srcImage","errorCallback","Image","URL","createObjectURL","webkitURL","src","listeners","imageLoadListeners","render","opt","imgWidth","imgHeight","optionsKey","optionsValue","oldTargetSrc","onrender","isImg","isCanvas","isImgCorsSupported","crossOrigin","isCanvasSupported","determineMimeOfFileName","nameWithPath","pathSegments","isCrossOrigin","targetProtocol","targetHostname","targetPort","targetAnchor","href","protocol","port","hostname","location","registerImgLoadListeners","registerCanvasDrawImageListener","registerThumbnailRenderedListener","registered","draw","drawPreview","Identify","megapixErrorHandler","isPreviewable","dummyExif","exif","Exif","mpImg","Orientation","failureMsg","drawOnCanvasOrImgFromUrl","canvasOrImg","tempImg","tempImgRender","drawOnImgFromUrlWithCssScaling","drawFromUrl","fileBlobOrUrl","_testing","parseLittleEndian","hex","pow","seekToApp1","offset","theOffset","thePromise","segmentLength","getApp1Offset","isLittleEndian","app1Start","getDirEntryCount","littleEndian","getIfd","dirEntries","getDirEntries","ifdHex","getTagValues","tagsToFind","TAG_IDS","vals","tagValHex","tagValLength","idHex","tagsToFindIdx","TAG_INFO","274","parser","onParseFailure","app1Offset","dirEntryCount","tagValues","isIdentifiable","magicBytes","questionableBytes","identifiable","magicBytesEntries","magicBytesArrayEntry","previewable","isPreviewableSync","PREVIEWABLE_MIME_TYPES","fileMime","isRecognizedImage","image/jpeg","image/gif","image/png","image/bmp","image/tiff","hasNonZeroLimits","limits","atLeastOne","limit","getWidthHeight","sizeDetermination","getFailingLimit","dimensions","failingLimit","limitName","limitValue","limitMatcher","dimensionPropName","actualValue","validationEffort","isJsonResponseValid","handleFileItems","fileItems","someItemsIgnored","err","refreshEffort","refreshCompleteCallback","requesterOptions","SessionAjaxRequester","queryServer","responseText","includeOriginal","failedToScaleText","_getSortedSizes","getFileRecords","originalFileUuid","originalFileName","originalBlobOrBlobData","records","originalBlob","sizeRecord","outputType","_determineOutputType","requestedType","refType","_getName","_generateScaledImage","failedText","api","scaledIds","originalId","blobSize","scaledId","qqparentuuid","qqparentsize","param","scalingEffort","scalingOptions","scaler","referenceType","scaledVersionProperties","startOfExt","versionType","scaledName","scaledExt","nameAppendage","sort","a","b","sourceFile","imageGenerator","scaledImageDataUri","signalSuccess","_insertExifHeader","scaledImageDataUriWithExif","originalImage","reader","insertionEffort","originalImageDataUri","ExifRestorer","readAsDataURL","_dataUriToBlob","_createBlob","KEY_STR","encode64","chr1","chr2","enc1","enc2","enc3","output","chr3","enc4","isNaN","origFileBase64","resizedFileBase64","rawImage","decode64","segments","slice2Segments","exifManipulation","exifArray","getExifArray","newImageArray","insertExif","seg","x","imageData","buf","separatePoint","mae","ato","array","rawImageArray","head","endPoint","perFileProgress","totalLoaded","totalSize","lastLoadedSent","lastTotalSent","callbackProxy","noRetryableFiles","retryable","none","failedId","updateTotalProgress","onNew","newLoaded","newTotal","oldLoaded","oldTotal","isImage","registerPasteHandler","detachPasteHandler","clipboardData","getAsFile","unregisterPasteHandler","startUpload","determineNewEndpoint","formEl","validateForm","nativeSubmit","checkValidity","maybeUploadOnSubmit","submit","determineFormEl","_form2Obj","notIrrelevantType","irrelevantTypes","radioOrCheckbox","ignoreValue","checked","selectValue","select","selected","elements","getIframeContentJson","doc","innerHtml","contentWindow","nodeValue","createForm","responseFromMessage","multipart","addChunkingSpecificParams","allChunksDoneRequester","AllChunksDoneAjaxRequester","createReadyStateChangedHandler","onUploadOrChunkComplete","getChunksCompleteParams","isErrorUploadResponse","parseResponse","sendChunksCompleteRequest","complete","setParamsAndGetEntityToSend","entityToSendParams","xhrOverrides","customParams","defaultParams","xhrOverrideParams","setUploadHeaders","headersOptions","headerOverrides","headerName","headerValue","extraHeaders","uploadChunkParams","toSend","promises","endpointHandler","uploadDroppedFiles","uploadDropZone","filesAsArray","dropLog","dropDisabled","processingDroppedFilesComplete","getElement","traverseFileTree","parseEntryPromise","qqPath","extractDirectoryPath","droppedFiles","fileError","fullPath","isDirectory","getFilesInDirectory","entriesLeft","indexOfNameInFullPath","accumEntries","existingPromise","dirReader","createReader","readEntries","newEntries","handleDataTransfer","pendingFolderPromises","handleDataTransferPromise","processingDroppedFiles","allowMultipleItems","dropError","setupDropzone","dropArea","dropZone","UploadDropZone","HIDE_ZONES_EVENT_NAME","onEnter","dropActive","stopPropagation","onLeaveNotDescendants","onDrop","uploadDropZones","isFileDrag","dragEvent","fileDrag","types","leavingDocumentOut","y","setupDragDrop","dropZones","maybeHideDropZones","HTMLElement","setupExtraDropzone","removeDropzone","dzs","targetEl","errorSpecifics","dragoverShouldBeCanceled","disableDropOutside","dropOutsideDisabled","dropEffect","isValidFileDrag","effectTest","dt","isSafari","effectAllowed","includes","isOrSetDropDisabled","isDisabled","preventDrop","triggerHidezonesEvent","triggerUsingOldApi","hideZonesEvent","createEvent","initEvent","CustomEvent","dispatchEvent","attachEvents","effect","relatedTarget","elementFromPoint","clientX","clientY","uiPublicApi","_parent","_templating","addCacheToDom","clearFiles","addExtraDropzone","_dnd","removeExtraDropzone","getItemByFileId","isHiddenForever","getFileContainer","_setupDragAndDrop","_totalFilesInBatch","_filesInBatchAddedToUi","_setupClickAndEditEventHandlers","formattedFilename","updateFilename","uploadPaused","continued","uploadContinued","getId","fileContainerOrChildEl","getFileId","getDropTarget","qqDropTarget","uiPrivateApi","_removeFileItem","removeFile","_fileButtonsClickHandler","FileButtonsClickHandler","_bindFileButtonsClickEvent","_focusinEventSupported","_isEditFilenameEnabled","_filenameClickHandler","_bindFilenameClickEvent","_filenameInputFocusInHandler","_bindFilenameInputFocusInEvent","_filenameInputFocusHandler","_bindFilenameInputFocusEvent","dragAndDrop","extraDropzones","templating","defaultDropZone","getDropZone","showDropProcessing","hideDropProcessing","errorData","lvl","onDeleteFile","onRetry","onPause","onContinue","onGetName","isEditFilenamePossible","FilenameClickHandler","FilenameInputFocusHandler","_filenameEditHandler","onGetUploadStatus","onSetName","onEditingStatusChange","isEditing","qqInput","getEditInput","qqFileContainer","hideFilename","hideEditIcon","showFilename","showEditIcon","markFilenameEditable","hideRetry","setStatusText","_classes","retrying","hidePause","FilenameInputFocusInHandler","hideSpinner","resetTotalProgress","reportDirectoryPaths","qqpath","_addToList","addHandler","updateProgress","hideCancel","hideProgress","waitingForResponse","_displayFileSize","completeUpload","_markFileAsSuccessful","fail","showCancel","isRetryPossible","showRetry","_controlFailureTextDisplay","parentRetVal","newResult","showDeleteButton","_maybeUpdateThumbnail","showSpinner","allowPause","retryNumForDisplay","maxAuto","retryNote","_showCancelLink","showAutoRetryNote","autoRetryNote","resetProgress","_onSubmitDeleteSuccess","forceConfirm","_showDeleteConfirm","_sendDeleteRequest","deletingFailedText","hideDeleteButton","deletingStatusText","confirmMessage","deleteRequestArgs","showConfirm","canned","prependData","prependIndex","dontDisplay","hideScaled","prependFiles","disableCancel","_handledProxyGroup","_clearList","addFileToCache","updateThumbnail","thumbnails","generatePreview","fileSizeOnSubmit","loadedSize","sizeForDisplay","_formatProgress","uploadedSize","formatProgress","mode","responseProperty","failureReason","failedUploadTextDisplay","failUpload","enableTooltip","_showTooltip","showMessage","_setupPastePrompt","namePromptMessage","defaultVal","showPrompt","placeholders","waitUntilResponse","listElement","template","editable","tooManyFilesError","unsupportedBrowser","promptForName","maxCount","notAvailablePath","waitingPath","timeBetweenThumbs","hasDialog","showDialog","confirm","defaultValue","prompt","Templating","templateIdOrEl","containerEl","fileContainerEl","maxThumbs","waitUntilUpdate","thumbnailNotAvailable","waitingForThumbnail","renderFailure","isEditElementsExist","isRetryElementExist","templateDom","showThumbnails","serverScale","fileBatch","content","createDocumentFragment","map","isCancelDisabled","generatedThumbnails","thumbnailQueueMonitorRunning","thumbGenerationQueue","thumbnailMaxSize","selectorClasses","alertDialog","dialogCancelButton","confirmDialog","dialogMessage","dialogOkButton","promptDialog","drop","list","progressBarContainer","totalProgressBarContainer","totalProgressBar","spinner","continueButton","deleteButton","statusText","editFilenameInput","editNameIcon","dropText","dropProcessing","dropProcessingSpinner","thumbnail","previewGeneration","cachedThumbnailNotAvailableImg","cachedWaitingForThumbnailImg","cacheThumbnailPlaceholders","notAvailableUrl","waitingUrl","updatedImg","displayWaitingImg","waitingImgPlacement","maybeScalePlaceholderViaCss","show","generateNewPreview","getThumbnail","qqThumbnailId","maybeSetDisplayNotAvailableImg","generateNextQueuedPreview","queuedThumbRequest","update","processUpdateQueuedPreviewRequest","processNewQueuedPreviewRequest","getCancel","getTemplateEl","getContinue","getDialog","getDelete","getDropProcessing","getEditIcon","getPause","getProgress","getRetry","getSpinner","cssClass","previewing","notAvailableImgPlacement","parseAndGetTemplate","scriptEl","scriptHtml","fileListNode","tempTemplateEl","fileListEl","defaultButton","dropTextEl","uploaderEl","fileTemplate","prependFile","parentEl","beforeEl","optFileOrBlob","relatedThumbnailId","useCachedPreview","showWaitingImg","setProgressBarWidth","percent","bar","progressBarSelector","targetThumbnailId","cachedThumbnailId","targetThumbnail","cachedThumbnail","hideTotalProgress","cantRenderEl","prependInfo","hideForever","batch","thumb","fileEl","fileNameEl","waitingImg","currentNode","getFileList","filenameEl","isFileName","icon","isEditIcon","isEditInput","isCancel","allowContinueButton","isPause","isContinueButton","isDeleteButton","isRetry","textEl","dialog","messageEl","inputEl","cancelBtn","okBtn","closeHandler","cancelClickHandler","okClickHandler","close","showModal","UiEventHandler","s","protectedApi","eventType","srcElement","onHandled","attachTo","getFileIdFromItem","qqFileId","getDisposeSupport","examineEvent","buttonHandlers","buttonType","firstLetterCapButtonType","inheritedInternalApi","handleFilenameEdit","FilenameEditHandler","handleInputFocus","getFilenameSansExtension","filenameSansExt","getOriginalExtension","origName","handleNameUpdate","newFilenameInputEl","origExtension","registerInputBlurHandler","registerInputEnterKeyHandler","keyCode","which","focusInput","focus"],"mappings":";CAAA,SAAUA,SCCT,SAASC,GACN,YAIA,SAASC,GAAKC,GACV,GAAIC,GAAcC,EAAmBF,OACjCG,EAAsBC,EAAuBH,EAKjD,OAHAI,GAASF,GACTG,EAAaL,EAAaE,GAEnBI,EAGX,QAASH,GAAuBI,GAC5B,GAAIC,GAAeC,EAAa,gBAC5BC,EAAYD,EAAa,eAG7B,OAAID,IAGAA,EAAeA,EAAaG,OAAO,GAAGC,cAAgBJ,EAAaK,MAAM,GAAGC,cAExEJ,EACO,GAAIK,IAAGL,GAAW,eAAiBF,GAAcD,GAGrD,GAAIQ,IAAG,eAAiBP,GAAcD,IAGzCG,EACO,GAAIK,IAAGL,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AAMy9C,GAEhBz9C,EAAK89C,SAAW99C,EAAKotC,WAAW6O,cAEhC95D,GAAGsG,OAAOrE,KAAM,GAAIjC,IAAGq7D,eAAex9C,EAAMs+C,IAE5Cn8D,GAAGsG,OAAO61D,GACNC,mBAAoB,SAASv/C,EAAIrN,EAAQ0tD,GACrC,GAAIN,GAAqB/+C,EAAKotC,WAAWqB,aAAazvC,EAEtDgB,GAAKsuC,sBAAsBtvC,GAAI,GAE/B+/C,EAAmBnyD,MAAQ8xD,EAAyB1/C,GAEhDqgD,GACAN,EAAmBO,QAGvBL,EAAyBF,EAAoB//C,GAC7CkgD,EAA6BH,EAAoB//C,Q7CvF9B3T","file":"jquery.fine-uploader.min.js","sourcesContent":[null,"/*globals jQuery, qq*/\n(function($) {\n \"use strict\";\n var $el,\n pluginOptions = [\"uploaderType\", \"endpointType\"];\n\n function init(options) {\n var xformedOpts = transformVariables(options || {}),\n newUploaderInstance = getNewUploaderInstance(xformedOpts);\n\n uploader(newUploaderInstance);\n addCallbacks(xformedOpts, newUploaderInstance);\n\n return $el;\n }\n\n function getNewUploaderInstance(params) {\n var uploaderType = pluginOption(\"uploaderType\"),\n namespace = pluginOption(\"endpointType\");\n\n // If the integrator has defined a specific type of uploader to load, use that, otherwise assume `qq.FineUploader`\n if (uploaderType) {\n // We can determine the correct constructor function to invoke by combining \"FineUploader\"\n // with the upper camel cased `uploaderType` value.\n uploaderType = uploaderType.charAt(0).toUpperCase() + uploaderType.slice(1).toLowerCase();\n\n if (namespace) {\n return new qq[namespace][\"FineUploader\" + uploaderType](params);\n }\n\n return new qq[\"FineUploader\" + uploaderType](params);\n }\n else {\n if (namespace) {\n return new qq[namespace].FineUploader(params);\n }\n\n return new qq.FineUploader(params);\n }\n }\n\n function dataStore(key, val) {\n var data = $el.data(\"fineuploader\");\n\n if (val) {\n if (data === undefined) {\n data = {};\n }\n data[key] = val;\n $el.data(\"fineuploader\", data);\n }\n else {\n if (data === undefined) {\n return null;\n }\n return data[key];\n }\n }\n\n //the underlying Fine Uploader instance is stored in jQuery's data stored, associated with the element\n // tied to this instance of the plug-in\n function uploader(instanceToStore) {\n return dataStore(\"uploader\", instanceToStore);\n }\n\n function pluginOption(option, optionVal) {\n return dataStore(option, optionVal);\n }\n\n // Implement all callbacks defined in Fine Uploader as functions that trigger appropriately names events and\n // return the result of executing the bound handler back to Fine Uploader\n function addCallbacks(transformedOpts, newUploaderInstance) {\n var callbacks = transformedOpts.callbacks = {};\n\n $.each(newUploaderInstance._options.callbacks, function(prop, nonJqueryCallback) {\n var name, callbackEventTarget;\n\n name = /^on(\\w+)/.exec(prop)[1];\n name = name.substring(0, 1).toLowerCase() + name.substring(1);\n callbackEventTarget = $el;\n\n callbacks[prop] = function() {\n var originalArgs = Array.prototype.slice.call(arguments),\n transformedArgs = [],\n nonJqueryCallbackRetVal, jqueryEventCallbackRetVal;\n\n $.each(originalArgs, function(idx, arg) {\n transformedArgs.push(maybeWrapInJquery(arg));\n });\n\n nonJqueryCallbackRetVal = nonJqueryCallback.apply(this, originalArgs);\n\n try {\n jqueryEventCallbackRetVal = callbackEventTarget.triggerHandler(name, transformedArgs);\n }\n catch (error) {\n qq.log(\"Caught error in Fine Uploader jQuery event handler: \" + error.message, \"error\");\n }\n\n /*jshint -W116*/\n if (nonJqueryCallbackRetVal != null) {\n return nonJqueryCallbackRetVal;\n }\n return jqueryEventCallbackRetVal;\n };\n });\n\n newUploaderInstance._options.callbacks = callbacks;\n }\n\n //transform jQuery objects into HTMLElements, and pass along all other option properties\n function transformVariables(source, dest) {\n var xformed, arrayVals;\n\n if (dest === undefined) {\n if (source.uploaderType !== \"basic\") {\n xformed = { element: $el[0] };\n }\n else {\n xformed = {};\n }\n }\n else {\n xformed = dest;\n }\n\n $.each(source, function(prop, val) {\n if ($.inArray(prop, pluginOptions) >= 0) {\n pluginOption(prop, val);\n }\n else if (val instanceof $) {\n xformed[prop] = val[0];\n }\n else if ($.isPlainObject(val)) {\n xformed[prop] = {};\n transformVariables(val, xformed[prop]);\n }\n else if ($.isArray(val)) {\n arrayVals = [];\n $.each(val, function(idx, arrayVal) {\n var arrayObjDest = {};\n\n if (arrayVal instanceof $) {\n $.merge(arrayVals, arrayVal);\n }\n else if ($.isPlainObject(arrayVal)) {\n transformVariables(arrayVal, arrayObjDest);\n arrayVals.push(arrayObjDest);\n }\n else {\n arrayVals.push(arrayVal);\n }\n });\n xformed[prop] = arrayVals;\n }\n else {\n xformed[prop] = val;\n }\n });\n\n if (dest === undefined) {\n return xformed;\n }\n }\n\n function isValidCommand(command) {\n return $.type(command) === \"string\" &&\n !command.match(/^_/) && //enforce private methods convention\n uploader()[command] !== undefined;\n }\n\n // Assuming we have already verified that this is a valid command, call the associated function in the underlying\n // Fine Uploader instance (passing along the arguments from the caller) and return the result of the call back to the caller\n function delegateCommand(command) {\n var xformedArgs = [],\n origArgs = Array.prototype.slice.call(arguments, 1),\n retVal;\n\n transformVariables(origArgs, xformedArgs);\n\n retVal = uploader()[command].apply(uploader(), xformedArgs);\n\n return maybeWrapInJquery(retVal);\n }\n\n // If the value is an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object\n function maybeWrapInJquery(val) {\n var transformedVal = val;\n\n // If the command is returning an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object\n /*jshint -W116*/\n if (val != null && typeof val === \"object\" &&\n (val.nodeType === 1 || val.nodeType === 9) && val.cloneNode) {\n\n transformedVal = $(val);\n }\n\n return transformedVal;\n }\n\n $.fn.fineUploader = function(optionsOrCommand) {\n var self = this, selfArgs = arguments, retVals = [];\n\n this.each(function(index, el) {\n $el = $(el);\n\n if (uploader() && isValidCommand(optionsOrCommand)) {\n retVals.push(delegateCommand.apply(self, selfArgs));\n\n if (self.length === 1) {\n return false;\n }\n }\n else if (typeof optionsOrCommand === \"object\" || !optionsOrCommand) {\n init.apply(self, selfArgs);\n }\n else {\n $.error(\"Method \" + optionsOrCommand + \" does not exist on jQuery.fineUploader\");\n }\n });\n\n if (retVals.length === 1) {\n return retVals[0];\n }\n else if (retVals.length > 1) {\n return retVals;\n }\n\n return this;\n };\n\n}(jQuery));\n","/*globals jQuery, qq*/\n(function($) {\n \"use strict\";\n var rootDataKey = \"fineUploaderDnd\",\n $el;\n\n function init(options) {\n if (!options) {\n options = {};\n }\n\n options.dropZoneElements = [$el];\n var xformedOpts = transformVariables(options);\n addCallbacks(xformedOpts);\n dnd(new qq.DragAndDrop(xformedOpts));\n\n return $el;\n }\n\n function dataStore(key, val) {\n var data = $el.data(rootDataKey);\n\n if (val) {\n if (data === undefined) {\n data = {};\n }\n data[key] = val;\n $el.data(rootDataKey, data);\n }\n else {\n if (data === undefined) {\n return null;\n }\n return data[key];\n }\n }\n\n function dnd(instanceToStore) {\n return dataStore(\"dndInstance\", instanceToStore);\n }\n\n function addCallbacks(transformedOpts) {\n var callbacks = transformedOpts.callbacks = {};\n\n $.each(new qq.DragAndDrop.callbacks(), function(prop, func) {\n var name = prop,\n $callbackEl;\n\n $callbackEl = $el;\n\n callbacks[prop] = function() {\n var args = Array.prototype.slice.call(arguments),\n jqueryHandlerResult = $callbackEl.triggerHandler(name, args);\n\n return jqueryHandlerResult;\n };\n });\n }\n\n //transform jQuery objects into HTMLElements, and pass along all other option properties\n function transformVariables(source, dest) {\n var xformed, arrayVals;\n\n if (dest === undefined) {\n xformed = {};\n }\n else {\n xformed = dest;\n }\n\n $.each(source, function(prop, val) {\n if (val instanceof $) {\n xformed[prop] = val[0];\n }\n else if ($.isPlainObject(val)) {\n xformed[prop] = {};\n transformVariables(val, xformed[prop]);\n }\n else if ($.isArray(val)) {\n arrayVals = [];\n $.each(val, function(idx, arrayVal) {\n if (arrayVal instanceof $) {\n $.merge(arrayVals, arrayVal);\n }\n else {\n arrayVals.push(arrayVal);\n }\n });\n xformed[prop] = arrayVals;\n }\n else {\n xformed[prop] = val;\n }\n });\n\n if (dest === undefined) {\n return xformed;\n }\n }\n\n function isValidCommand(command) {\n return $.type(command) === \"string\" &&\n command === \"dispose\" &&\n dnd()[command] !== undefined;\n }\n\n function delegateCommand(command) {\n var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1);\n transformVariables(origArgs, xformedArgs);\n return dnd()[command].apply(dnd(), xformedArgs);\n }\n\n $.fn.fineUploaderDnd = function(optionsOrCommand) {\n var self = this, selfArgs = arguments, retVals = [];\n\n this.each(function(index, el) {\n $el = $(el);\n\n if (dnd() && isValidCommand(optionsOrCommand)) {\n retVals.push(delegateCommand.apply(self, selfArgs));\n\n if (self.length === 1) {\n return false;\n }\n }\n else if (typeof optionsOrCommand === \"object\" || !optionsOrCommand) {\n init.apply(self, selfArgs);\n }\n else {\n $.error(\"Method \" + optionsOrCommand + \" does not exist in Fine Uploader's DnD module.\");\n }\n });\n\n if (retVals.length === 1) {\n return retVals[0];\n }\n else if (retVals.length > 1) {\n return retVals;\n }\n\n return this;\n };\n\n}(jQuery));\n","/*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob, Storage, ActiveXObject */\n/* jshint -W079 */\nvar qq = function(element) {\n \"use strict\";\n\n return {\n hide: function() {\n element.style.display = \"none\";\n return this;\n },\n\n /** Returns the function which detaches attached event */\n attach: function(type, fn) {\n if (element.addEventListener) {\n element.addEventListener(type, fn, false);\n } else if (element.attachEvent) {\n element.attachEvent(\"on\" + type, fn);\n }\n return function() {\n qq(element).detach(type, fn);\n };\n },\n\n detach: function(type, fn) {\n if (element.removeEventListener) {\n element.removeEventListener(type, fn, false);\n } else if (element.attachEvent) {\n element.detachEvent(\"on\" + type, fn);\n }\n return this;\n },\n\n contains: function(descendant) {\n // The [W3C spec](http://www.w3.org/TR/domcore/#dom-node-contains)\n // says a `null` (or ostensibly `undefined`) parameter\n // passed into `Node.contains` should result in a false return value.\n // IE7 throws an exception if the parameter is `undefined` though.\n if (!descendant) {\n return false;\n }\n\n // compareposition returns false in this case\n if (element === descendant) {\n return true;\n }\n\n if (element.contains) {\n return element.contains(descendant);\n } else {\n /*jslint bitwise: true*/\n return !!(descendant.compareDocumentPosition(element) & 8);\n }\n },\n\n /**\n * Insert this element before elementB.\n */\n insertBefore: function(elementB) {\n elementB.parentNode.insertBefore(element, elementB);\n return this;\n },\n\n remove: function() {\n element.parentNode.removeChild(element);\n return this;\n },\n\n /**\n * Sets styles for an element.\n * Fixes opacity in IE6-8.\n */\n css: function(styles) {\n /*jshint eqnull: true*/\n if (element.style == null) {\n throw new qq.Error(\"Can't apply style to node as it is not on the HTMLElement prototype chain!\");\n }\n\n /*jshint -W116*/\n if (styles.opacity != null) {\n if (typeof element.style.opacity !== \"string\" && typeof (element.filters) !== \"undefined\") {\n styles.filter = \"alpha(opacity=\" + Math.round(100 * styles.opacity) + \")\";\n }\n }\n qq.extend(element.style, styles);\n\n return this;\n },\n\n hasClass: function(name, considerParent) {\n var re = new RegExp(\"(^| )\" + name + \"( |$)\");\n return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className));\n },\n\n addClass: function(name) {\n if (!qq(element).hasClass(name)) {\n element.className += \" \" + name;\n }\n return this;\n },\n\n removeClass: function(name) {\n var re = new RegExp(\"(^| )\" + name + \"( |$)\");\n element.className = element.className.replace(re, \" \").replace(/^\\s+|\\s+$/g, \"\");\n return this;\n },\n\n getByClass: function(className, first) {\n var candidates,\n result = [];\n\n if (first && element.querySelector) {\n return element.querySelector(\".\" + className);\n }\n else if (element.querySelectorAll) {\n return element.querySelectorAll(\".\" + className);\n }\n\n candidates = element.getElementsByTagName(\"*\");\n\n qq.each(candidates, function(idx, val) {\n if (qq(val).hasClass(className)) {\n result.push(val);\n }\n });\n return first ? result[0] : result;\n },\n\n getFirstByClass: function(className) {\n return qq(element).getByClass(className, true);\n },\n\n children: function() {\n var children = [],\n child = element.firstChild;\n\n while (child) {\n if (child.nodeType === 1) {\n children.push(child);\n }\n child = child.nextSibling;\n }\n\n return children;\n },\n\n setText: function(text) {\n element.innerText = text;\n element.textContent = text;\n return this;\n },\n\n clearText: function() {\n return qq(element).setText(\"\");\n },\n\n // Returns true if the attribute exists on the element\n // AND the value of the attribute is NOT \"false\" (case-insensitive)\n hasAttribute: function(attrName) {\n var attrVal;\n\n if (element.hasAttribute) {\n\n if (!element.hasAttribute(attrName)) {\n return false;\n }\n\n /*jshint -W116*/\n return (/^false$/i).exec(element.getAttribute(attrName)) == null;\n }\n else {\n attrVal = element[attrName];\n\n if (attrVal === undefined) {\n return false;\n }\n\n /*jshint -W116*/\n return (/^false$/i).exec(attrVal) == null;\n }\n }\n };\n};\n\n(function() {\n \"use strict\";\n\n qq.canvasToBlob = function(canvas, mime, quality) {\n return qq.dataUriToBlob(canvas.toDataURL(mime, quality));\n };\n\n qq.dataUriToBlob = function(dataUri) {\n var arrayBuffer, byteString,\n createBlob = function(data, mime) {\n var BlobBuilder = window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder,\n blobBuilder = BlobBuilder && new BlobBuilder();\n\n if (blobBuilder) {\n blobBuilder.append(data);\n return blobBuilder.getBlob(mime);\n }\n else {\n return new Blob([data], {type: mime});\n }\n },\n intArray, mimeString;\n\n // convert base64 to raw binary data held in a string\n if (dataUri.split(\",\")[0].indexOf(\"base64\") >= 0) {\n byteString = atob(dataUri.split(\",\")[1]);\n }\n else {\n byteString = decodeURI(dataUri.split(\",\")[1]);\n }\n\n // extract the MIME\n mimeString = dataUri.split(\",\")[0]\n .split(\":\")[1]\n .split(\";\")[0];\n\n // write the bytes of the binary string to an ArrayBuffer\n arrayBuffer = new ArrayBuffer(byteString.length);\n intArray = new Uint8Array(arrayBuffer);\n qq.each(byteString, function(idx, character) {\n intArray[idx] = character.charCodeAt(0);\n });\n\n return createBlob(arrayBuffer, mimeString);\n };\n\n qq.log = function(message, level) {\n if (window.console) {\n if (!level || level === \"info\") {\n window.console.log(message);\n }\n else\n {\n if (window.console[level]) {\n window.console[level](message);\n }\n else {\n window.console.log(\"<\" + level + \"> \" + message);\n }\n }\n }\n };\n\n qq.isObject = function(variable) {\n return variable && !variable.nodeType && Object.prototype.toString.call(variable) === \"[object Object]\";\n };\n\n qq.isFunction = function(variable) {\n return typeof (variable) === \"function\";\n };\n\n /**\n * Check the type of a value. Is it an \"array\"?\n *\n * @param value value to test.\n * @returns true if the value is an array or associated with an `ArrayBuffer`\n */\n qq.isArray = function(value) {\n return Object.prototype.toString.call(value) === \"[object Array]\" ||\n (value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer);\n };\n\n // Looks for an object on a `DataTransfer` object that is associated with drop events when utilizing the Filesystem API.\n qq.isItemList = function(maybeItemList) {\n return Object.prototype.toString.call(maybeItemList) === \"[object DataTransferItemList]\";\n };\n\n // Looks for an object on a `NodeList` or an `HTMLCollection`|`HTMLFormElement`|`HTMLSelectElement`\n // object that is associated with collections of Nodes.\n qq.isNodeList = function(maybeNodeList) {\n return Object.prototype.toString.call(maybeNodeList) === \"[object NodeList]\" ||\n // If `HTMLCollection` is the actual type of the object, we must determine this\n // by checking for expected properties/methods on the object\n (maybeNodeList.item && maybeNodeList.namedItem);\n };\n\n qq.isString = function(maybeString) {\n return Object.prototype.toString.call(maybeString) === \"[object String]\";\n };\n\n qq.trimStr = function(string) {\n if (String.prototype.trim) {\n return string.trim();\n }\n\n return string.replace(/^\\s+|\\s+$/g, \"\");\n };\n\n /**\n * @param str String to format.\n * @returns {string} A string, swapping argument values with the associated occurrence of {} in the passed string.\n */\n qq.format = function(str) {\n\n var args = Array.prototype.slice.call(arguments, 1),\n newStr = str,\n nextIdxToReplace = newStr.indexOf(\"{}\");\n\n qq.each(args, function(idx, val) {\n var strBefore = newStr.substring(0, nextIdxToReplace),\n strAfter = newStr.substring(nextIdxToReplace + 2);\n\n newStr = strBefore + val + strAfter;\n nextIdxToReplace = newStr.indexOf(\"{}\", nextIdxToReplace + val.length);\n\n // End the loop if we have run out of tokens (when the arguments exceed the # of tokens)\n if (nextIdxToReplace < 0) {\n return false;\n }\n });\n\n return newStr;\n };\n\n qq.isFile = function(maybeFile) {\n return window.File && Object.prototype.toString.call(maybeFile) === \"[object File]\";\n };\n\n qq.isFileList = function(maybeFileList) {\n return window.FileList && Object.prototype.toString.call(maybeFileList) === \"[object FileList]\";\n };\n\n qq.isFileOrInput = function(maybeFileOrInput) {\n return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);\n };\n\n qq.isInput = function(maybeInput, notFile) {\n var evaluateType = function(type) {\n var normalizedType = type.toLowerCase();\n\n if (notFile) {\n return normalizedType !== \"file\";\n }\n\n return normalizedType === \"file\";\n };\n\n if (window.HTMLInputElement) {\n if (Object.prototype.toString.call(maybeInput) === \"[object HTMLInputElement]\") {\n if (maybeInput.type && evaluateType(maybeInput.type)) {\n return true;\n }\n }\n }\n if (maybeInput.tagName) {\n if (maybeInput.tagName.toLowerCase() === \"input\") {\n if (maybeInput.type && evaluateType(maybeInput.type)) {\n return true;\n }\n }\n }\n\n return false;\n };\n\n qq.isBlob = function(maybeBlob) {\n if (window.Blob && Object.prototype.toString.call(maybeBlob) === \"[object Blob]\") {\n return true;\n }\n };\n\n qq.isXhrUploadSupported = function() {\n var input = document.createElement(\"input\");\n input.type = \"file\";\n\n return (\n input.multiple !== undefined &&\n typeof File !== \"undefined\" &&\n typeof FormData !== \"undefined\" &&\n typeof (qq.createXhrInstance()).upload !== \"undefined\");\n };\n\n // Fall back to ActiveX is native XHR is disabled (possible in any version of IE).\n qq.createXhrInstance = function() {\n if (window.XMLHttpRequest) {\n return new XMLHttpRequest();\n }\n\n try {\n return new ActiveXObject(\"MSXML2.XMLHTTP.3.0\");\n }\n catch (error) {\n qq.log(\"Neither XHR or ActiveX are supported!\", \"error\");\n return null;\n }\n };\n\n qq.isFolderDropSupported = function(dataTransfer) {\n return dataTransfer.items &&\n dataTransfer.items.length > 0 &&\n dataTransfer.items[0].webkitGetAsEntry;\n };\n\n qq.isFileChunkingSupported = function() {\n return !qq.androidStock() && //Android's stock browser cannot upload Blobs correctly\n qq.isXhrUploadSupported() &&\n (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);\n };\n\n qq.sliceBlob = function(fileOrBlob, start, end) {\n var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;\n\n return slicer.call(fileOrBlob, start, end);\n };\n\n qq.arrayBufferToHex = function(buffer) {\n var bytesAsHex = \"\",\n bytes = new Uint8Array(buffer);\n\n qq.each(bytes, function(idx, byt) {\n var byteAsHexStr = byt.toString(16);\n\n if (byteAsHexStr.length < 2) {\n byteAsHexStr = \"0\" + byteAsHexStr;\n }\n\n bytesAsHex += byteAsHexStr;\n });\n\n return bytesAsHex;\n };\n\n qq.readBlobToHex = function(blob, startOffset, length) {\n var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length),\n fileReader = new FileReader(),\n promise = new qq.Promise();\n\n fileReader.onload = function() {\n promise.success(qq.arrayBufferToHex(fileReader.result));\n };\n\n fileReader.onerror = promise.failure;\n\n fileReader.readAsArrayBuffer(initialBlob);\n\n return promise;\n };\n\n qq.extend = function(first, second, extendNested) {\n qq.each(second, function(prop, val) {\n if (extendNested && qq.isObject(val)) {\n if (first[prop] === undefined) {\n first[prop] = {};\n }\n qq.extend(first[prop], val, true);\n }\n else {\n first[prop] = val;\n }\n });\n\n return first;\n };\n\n /**\n * Allow properties in one object to override properties in another,\n * keeping track of the original values from the target object.\n *\n * Note that the pre-overriden properties to be overriden by the source will be passed into the `sourceFn` when it is invoked.\n *\n * @param target Update properties in this object from some source\n * @param sourceFn A function that, when invoked, will return properties that will replace properties with the same name in the target.\n * @returns {object} The target object\n */\n qq.override = function(target, sourceFn) {\n var super_ = {},\n source = sourceFn(super_);\n\n qq.each(source, function(srcPropName, srcPropVal) {\n if (target[srcPropName] !== undefined) {\n super_[srcPropName] = target[srcPropName];\n }\n\n target[srcPropName] = srcPropVal;\n });\n\n return target;\n };\n\n /**\n * Searches for a given element (elt) in the array, returns -1 if it is not present.\n */\n qq.indexOf = function(arr, elt, from) {\n if (arr.indexOf) {\n return arr.indexOf(elt, from);\n }\n\n from = from || 0;\n var len = arr.length;\n\n if (from < 0) {\n from += len;\n }\n\n for (; from < len; from += 1) {\n if (arr.hasOwnProperty(from) && arr[from] === elt) {\n return from;\n }\n }\n return -1;\n };\n\n //this is a version 4 UUID\n qq.getUniqueId = function() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function(c) {\n /*jslint eqeq: true, bitwise: true*/\n var r = Math.random() * 16 | 0, v = c == \"x\" ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n };\n\n //\n // Browsers and platforms detection\n qq.ie = function() {\n return navigator.userAgent.indexOf(\"MSIE\") !== -1 ||\n navigator.userAgent.indexOf(\"Trident\") !== -1;\n };\n\n qq.ie7 = function() {\n return navigator.userAgent.indexOf(\"MSIE 7\") !== -1;\n };\n\n qq.ie8 = function() {\n return navigator.userAgent.indexOf(\"MSIE 8\") !== -1;\n };\n\n qq.ie10 = function() {\n return navigator.userAgent.indexOf(\"MSIE 10\") !== -1;\n };\n\n qq.ie11 = function() {\n return qq.ie() && navigator.userAgent.indexOf(\"rv:11\") !== -1;\n };\n\n qq.edge = function() {\n return navigator.userAgent.indexOf(\"Edge\") >= 0;\n };\n\n qq.safari = function() {\n return navigator.vendor !== undefined && navigator.vendor.indexOf(\"Apple\") !== -1;\n };\n\n qq.chrome = function() {\n return navigator.vendor !== undefined && navigator.vendor.indexOf(\"Google\") !== -1;\n };\n\n qq.opera = function() {\n return navigator.vendor !== undefined && navigator.vendor.indexOf(\"Opera\") !== -1;\n };\n\n qq.firefox = function() {\n return (!qq.edge() && !qq.ie11() && navigator.userAgent.indexOf(\"Mozilla\") !== -1 && navigator.vendor !== undefined && navigator.vendor === \"\");\n };\n\n qq.windows = function() {\n return navigator.platform === \"Win32\";\n };\n\n qq.android = function() {\n return navigator.userAgent.toLowerCase().indexOf(\"android\") !== -1;\n };\n\n // We need to identify the Android stock browser via the UA string to work around various bugs in this browser,\n // such as the one that prevents a `Blob` from being uploaded.\n qq.androidStock = function() {\n return qq.android() && navigator.userAgent.toLowerCase().indexOf(\"chrome\") < 0;\n };\n\n qq.ios6 = function() {\n return qq.ios() && navigator.userAgent.indexOf(\" OS 6_\") !== -1;\n };\n\n qq.ios7 = function() {\n return qq.ios() && navigator.userAgent.indexOf(\" OS 7_\") !== -1;\n };\n\n qq.ios8 = function() {\n return qq.ios() && navigator.userAgent.indexOf(\" OS 8_\") !== -1;\n };\n\n // iOS 8.0.0\n qq.ios800 = function() {\n return qq.ios() && navigator.userAgent.indexOf(\" OS 8_0 \") !== -1;\n };\n\n qq.ios = function() {\n /*jshint -W014 */\n return navigator.userAgent.indexOf(\"iPad\") !== -1\n || navigator.userAgent.indexOf(\"iPod\") !== -1\n || navigator.userAgent.indexOf(\"iPhone\") !== -1;\n };\n\n qq.iosChrome = function() {\n return qq.ios() && navigator.userAgent.indexOf(\"CriOS\") !== -1;\n };\n\n qq.iosSafari = function() {\n return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf(\"Safari\") !== -1;\n };\n\n qq.iosSafariWebView = function() {\n return qq.ios() && !qq.iosChrome() && !qq.iosSafari();\n };\n\n //\n // Events\n\n qq.preventDefault = function(e) {\n if (e.preventDefault) {\n e.preventDefault();\n } else {\n e.returnValue = false;\n }\n };\n\n /**\n * Creates and returns element from html string\n * Uses innerHTML to create an element\n */\n qq.toElement = (function() {\n var div = document.createElement(\"div\");\n return function(html) {\n div.innerHTML = html;\n var element = div.firstChild;\n div.removeChild(element);\n return element;\n };\n }());\n\n //key and value are passed to callback for each entry in the iterable item\n qq.each = function(iterableItem, callback) {\n var keyOrIndex, retVal;\n\n if (iterableItem) {\n // Iterate through [`Storage`](http://www.w3.org/TR/webstorage/#the-storage-interface) items\n if (window.Storage && iterableItem.constructor === window.Storage) {\n for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {\n retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));\n if (retVal === false) {\n break;\n }\n }\n }\n // `DataTransferItemList` & `NodeList` objects are array-like and should be treated as arrays\n // when iterating over items inside the object.\n else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {\n for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {\n retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);\n if (retVal === false) {\n break;\n }\n }\n }\n else if (qq.isString(iterableItem)) {\n for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {\n retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));\n if (retVal === false) {\n break;\n }\n }\n }\n else {\n for (keyOrIndex in iterableItem) {\n if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {\n retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);\n if (retVal === false) {\n break;\n }\n }\n }\n }\n }\n };\n\n //include any args that should be passed to the new function after the context arg\n qq.bind = function(oldFunc, context) {\n if (qq.isFunction(oldFunc)) {\n var args = Array.prototype.slice.call(arguments, 2);\n\n return function() {\n var newArgs = qq.extend([], args);\n if (arguments.length) {\n newArgs = newArgs.concat(Array.prototype.slice.call(arguments));\n }\n return oldFunc.apply(context, newArgs);\n };\n }\n\n throw new Error(\"first parameter must be a function!\");\n };\n\n /**\n * obj2url() takes a json-object as argument and generates\n * a querystring. pretty much like jQuery.param()\n *\n * how to use:\n *\n * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`\n *\n * will result in:\n *\n * `http://any.url/upload?otherParam=value&a=b&c=d`\n *\n * @param Object JSON-Object\n * @param String current querystring-part\n * @return String encoded querystring\n */\n qq.obj2url = function(obj, temp, prefixDone) {\n /*jshint laxbreak: true*/\n var uristrings = [],\n prefix = \"&\",\n add = function(nextObj, i) {\n var nextTemp = temp\n ? (/\\[\\]$/.test(temp)) // prevent double-encoding\n ? temp\n : temp + \"[\" + i + \"]\"\n : i;\n if ((nextTemp !== \"undefined\") && (i !== \"undefined\")) {\n uristrings.push(\n (typeof nextObj === \"object\")\n ? qq.obj2url(nextObj, nextTemp, true)\n : (Object.prototype.toString.call(nextObj) === \"[object Function]\")\n ? encodeURIComponent(nextTemp) + \"=\" + encodeURIComponent(nextObj())\n : encodeURIComponent(nextTemp) + \"=\" + encodeURIComponent(nextObj)\n );\n }\n };\n\n if (!prefixDone && temp) {\n prefix = (/\\?/.test(temp)) ? (/\\?$/.test(temp)) ? \"\" : \"&\" : \"?\";\n uristrings.push(temp);\n uristrings.push(qq.obj2url(obj));\n } else if ((Object.prototype.toString.call(obj) === \"[object Array]\") && (typeof obj !== \"undefined\")) {\n qq.each(obj, function(idx, val) {\n add(val, idx);\n });\n } else if ((typeof obj !== \"undefined\") && (obj !== null) && (typeof obj === \"object\")) {\n qq.each(obj, function(prop, val) {\n add(val, prop);\n });\n } else {\n uristrings.push(encodeURIComponent(temp) + \"=\" + encodeURIComponent(obj));\n }\n\n if (temp) {\n return uristrings.join(prefix);\n } else {\n return uristrings.join(prefix)\n .replace(/^&/, \"\")\n .replace(/%20/g, \"+\");\n }\n };\n\n qq.obj2FormData = function(obj, formData, arrayKeyName) {\n if (!formData) {\n formData = new FormData();\n }\n\n qq.each(obj, function(key, val) {\n key = arrayKeyName ? arrayKeyName + \"[\" + key + \"]\" : key;\n\n if (qq.isObject(val)) {\n qq.obj2FormData(val, formData, key);\n }\n else if (qq.isFunction(val)) {\n formData.append(key, val());\n }\n else {\n formData.append(key, val);\n }\n });\n\n return formData;\n };\n\n qq.obj2Inputs = function(obj, form) {\n var input;\n\n if (!form) {\n form = document.createElement(\"form\");\n }\n\n qq.obj2FormData(obj, {\n append: function(key, val) {\n input = document.createElement(\"input\");\n input.setAttribute(\"name\", key);\n input.setAttribute(\"value\", val);\n form.appendChild(input);\n }\n });\n\n return form;\n };\n\n /**\n * Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not\n * implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js.\n */\n qq.parseJson = function(json) {\n /*jshint evil: true*/\n if (window.JSON && qq.isFunction(JSON.parse)) {\n return JSON.parse(json);\n } else {\n return eval(\"(\" + json + \")\");\n }\n };\n\n /**\n * Retrieve the extension of a file, if it exists.\n *\n * @param filename\n * @returns {string || undefined}\n */\n qq.getExtension = function(filename) {\n var extIdx = filename.lastIndexOf(\".\") + 1;\n\n if (extIdx > 0) {\n return filename.substr(extIdx, filename.length - extIdx);\n }\n };\n\n qq.getFilename = function(blobOrFileInput) {\n /*jslint regexp: true*/\n\n if (qq.isInput(blobOrFileInput)) {\n // get input value and remove path to normalize\n return blobOrFileInput.value.replace(/.*(\\/|\\\\)/, \"\");\n }\n else if (qq.isFile(blobOrFileInput)) {\n if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {\n return blobOrFileInput.fileName;\n }\n }\n\n return blobOrFileInput.name;\n };\n\n /**\n * A generic module which supports object disposing in dispose() method.\n * */\n qq.DisposeSupport = function() {\n var disposers = [];\n\n return {\n /** Run all registered disposers */\n dispose: function() {\n var disposer;\n do {\n disposer = disposers.shift();\n if (disposer) {\n disposer();\n }\n }\n while (disposer);\n },\n\n /** Attach event handler and register de-attacher as a disposer */\n attach: function() {\n var args = arguments;\n /*jslint undef:true*/\n this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));\n },\n\n /** Add disposer to the collection */\n addDisposer: function(disposeFunction) {\n disposers.push(disposeFunction);\n }\n };\n };\n}());\n","/* globals define, module, global, qq */\n(function() {\n \"use strict\";\n if (typeof define === \"function\" && define.amd) {\n define(function() {\n return qq;\n });\n }\n else if (typeof module !== \"undefined\" && module.exports) {\n module.exports = qq;\n }\n else {\n global.qq = qq;\n }\n}());\n","/* globals qq */\n/**\n * Fine Uploader top-level Error container. Inherits from `Error`.\n */\n(function() {\n \"use strict\";\n\n qq.Error = function(message) {\n this.message = \"[Fine Uploader \" + qq.version + \"] \" + message;\n };\n\n qq.Error.prototype = new Error();\n}());\n","/*global qq */\nqq.version = \"5.16.2\";\n","/* globals qq */\nqq.supportedFeatures = (function() {\n \"use strict\";\n\n var supportsUploading,\n supportsUploadingBlobs,\n supportsFileDrop,\n supportsAjaxFileUploading,\n supportsFolderDrop,\n supportsChunking,\n supportsResume,\n supportsUploadViaPaste,\n supportsUploadCors,\n supportsDeleteFileXdr,\n supportsDeleteFileCorsXhr,\n supportsDeleteFileCors,\n supportsFolderSelection,\n supportsImagePreviews,\n supportsUploadProgress;\n\n function testSupportsFileInputElement() {\n var supported = true,\n tempInput;\n\n try {\n tempInput = document.createElement(\"input\");\n tempInput.type = \"file\";\n qq(tempInput).hide();\n\n if (tempInput.disabled) {\n supported = false;\n }\n }\n catch (ex) {\n supported = false;\n }\n\n return supported;\n }\n\n //only way to test for complete Clipboard API support at this time\n function isChrome14OrHigher() {\n return (qq.chrome() || qq.opera()) &&\n navigator.userAgent.match(/Chrome\\/[1][4-9]|Chrome\\/[2-9][0-9]/) !== undefined;\n }\n\n //Ensure we can send cross-origin `XMLHttpRequest`s\n function isCrossOriginXhrSupported() {\n if (window.XMLHttpRequest) {\n var xhr = qq.createXhrInstance();\n\n //Commonly accepted test for XHR CORS support.\n return xhr.withCredentials !== undefined;\n }\n\n return false;\n }\n\n //Test for (terrible) cross-origin ajax transport fallback for IE9 and IE8\n function isXdrSupported() {\n return window.XDomainRequest !== undefined;\n }\n\n // CORS Ajax requests are supported if it is either possible to send credentialed `XMLHttpRequest`s,\n // or if `XDomainRequest` is an available alternative.\n function isCrossOriginAjaxSupported() {\n if (isCrossOriginXhrSupported()) {\n return true;\n }\n\n return isXdrSupported();\n }\n\n function isFolderSelectionSupported() {\n // We know that folder selection is only supported in Chrome via this proprietary attribute for now\n return document.createElement(\"input\").webkitdirectory !== undefined;\n }\n\n function isLocalStorageSupported() {\n try {\n return !!window.localStorage &&\n // unpatched versions of IE10/11 have buggy impls of localStorage where setItem is a string\n qq.isFunction(window.localStorage.setItem);\n }\n catch (error) {\n // probably caught a security exception, so no localStorage for you\n return false;\n }\n }\n\n function isDragAndDropSupported() {\n var span = document.createElement(\"span\");\n\n return (\"draggable\" in span || (\"ondragstart\" in span && \"ondrop\" in span)) &&\n !qq.android() && !qq.ios();\n }\n\n supportsUploading = testSupportsFileInputElement();\n\n supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();\n\n supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();\n\n supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported();\n\n // adapted from https://stackoverflow.com/a/23278460/486979\n supportsFolderDrop = supportsFileDrop && (function() {\n var input = document.createElement(\"input\");\n\n input.type = \"file\";\n return !!(\"webkitdirectory\" in (input || document.querySelectorAll(\"input[type=file]\")[0]));\n }());\n\n supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();\n\n supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();\n\n supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();\n\n supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);\n\n supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();\n\n supportsDeleteFileXdr = isXdrSupported();\n\n supportsDeleteFileCors = isCrossOriginAjaxSupported();\n\n supportsFolderSelection = isFolderSelectionSupported();\n\n supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;\n\n supportsUploadProgress = (function() {\n if (supportsAjaxFileUploading) {\n return !qq.androidStock() && !qq.iosChrome();\n }\n return false;\n }());\n\n return {\n ajaxUploading: supportsAjaxFileUploading,\n blobUploading: supportsUploadingBlobs,\n canDetermineSize: supportsAjaxFileUploading,\n chunking: supportsChunking,\n deleteFileCors: supportsDeleteFileCors,\n deleteFileCorsXdr: supportsDeleteFileXdr, //NOTE: will also return true in IE10, where XDR is also supported\n deleteFileCorsXhr: supportsDeleteFileCorsXhr,\n dialogElement: !!window.HTMLDialogElement,\n fileDrop: supportsFileDrop,\n folderDrop: supportsFolderDrop,\n folderSelection: supportsFolderSelection,\n imagePreviews: supportsImagePreviews,\n imageValidation: supportsImagePreviews,\n itemSizeValidation: supportsAjaxFileUploading,\n pause: supportsChunking,\n progressBar: supportsUploadProgress,\n resume: supportsResume,\n scaling: supportsImagePreviews && supportsUploadingBlobs,\n tiffPreviews: qq.safari(), // Not the best solution, but simple and probably accurate enough (for now)\n unlimitedScaledImageSize: !qq.ios(), // false simply indicates that there is some known limit\n uploading: supportsUploading,\n uploadCors: supportsUploadCors,\n uploadCustomHeaders: supportsAjaxFileUploading,\n uploadNonMultipart: supportsAjaxFileUploading,\n uploadViaPaste: supportsUploadViaPaste\n };\n\n}());\n","/*globals qq*/\n\n// Is the passed object a promise instance?\nqq.isGenericPromise = function(maybePromise) {\n \"use strict\";\n return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));\n};\n\nqq.Promise = function() {\n \"use strict\";\n\n var successArgs, failureArgs,\n successCallbacks = [],\n failureCallbacks = [],\n doneCallbacks = [],\n state = 0;\n\n qq.extend(this, {\n then: function(onSuccess, onFailure) {\n if (state === 0) {\n if (onSuccess) {\n successCallbacks.push(onSuccess);\n }\n if (onFailure) {\n failureCallbacks.push(onFailure);\n }\n }\n else if (state === -1) {\n onFailure && onFailure.apply(null, failureArgs);\n }\n else if (onSuccess) {\n onSuccess.apply(null, successArgs);\n }\n\n return this;\n },\n\n done: function(callback) {\n if (state === 0) {\n doneCallbacks.push(callback);\n }\n else {\n callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);\n }\n\n return this;\n },\n\n success: function() {\n state = 1;\n successArgs = arguments;\n\n if (successCallbacks.length) {\n qq.each(successCallbacks, function(idx, callback) {\n callback.apply(null, successArgs);\n });\n }\n\n if (doneCallbacks.length) {\n qq.each(doneCallbacks, function(idx, callback) {\n callback.apply(null, successArgs);\n });\n }\n\n return this;\n },\n\n failure: function() {\n state = -1;\n failureArgs = arguments;\n\n if (failureCallbacks.length) {\n qq.each(failureCallbacks, function(idx, callback) {\n callback.apply(null, failureArgs);\n });\n }\n\n if (doneCallbacks.length) {\n qq.each(doneCallbacks, function(idx, callback) {\n callback.apply(null, failureArgs);\n });\n }\n\n return this;\n }\n });\n};\n","/* globals qq */\n/**\n * Placeholder for a Blob that will be generated on-demand.\n *\n * @param referenceBlob Parent of the generated blob\n * @param onCreate Function to invoke when the blob must be created. Must be promissory.\n * @constructor\n */\nqq.BlobProxy = function(referenceBlob, onCreate) {\n \"use strict\";\n\n qq.extend(this, {\n referenceBlob: referenceBlob,\n\n create: function() {\n return onCreate(referenceBlob);\n }\n });\n};\n","/*globals qq*/\n\n/**\n * This module represents an upload or \"Select File(s)\" button. It's job is to embed an opaque `<input type=\"file\">`\n * element as a child of a provided \"container\" element. This \"container\" element (`options.element`) is used to provide\n * a custom style for the `<input type=\"file\">` element. The ability to change the style of the container element is also\n * provided here by adding CSS classes to the container on hover/focus.\n *\n * TODO Eliminate the mouseover and mouseout event handlers since the :hover CSS pseudo-class should now be\n * available on all supported browsers.\n *\n * @param o Options to override the default values\n */\nqq.UploadButton = function(o) {\n \"use strict\";\n\n var self = this,\n\n disposeSupport = new qq.DisposeSupport(),\n\n options = {\n // Corresponds to the `accept` attribute on the associated `<input type=\"file\">`\n acceptFiles: null,\n\n // \"Container\" element\n element: null,\n\n focusClass: \"qq-upload-button-focus\",\n\n // A true value allows folders to be selected, if supported by the UA\n folders: false,\n\n // **This option will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers\n hoverClass: \"qq-upload-button-hover\",\n\n ios8BrowserCrashWorkaround: false,\n\n // If true adds `multiple` attribute to `<input type=\"file\">`\n multiple: false,\n\n // `name` attribute of `<input type=\"file\">`\n name: \"qqfile\",\n\n // Called when the browser invokes the onchange handler on the `<input type=\"file\">`\n onChange: function(input) {},\n\n title: null\n },\n input, buttonId;\n\n // Overrides any of the default option values with any option values passed in during construction.\n qq.extend(options, o);\n\n buttonId = qq.getUniqueId();\n\n // Embed an opaque `<input type=\"file\">` element as a child of `options.element`.\n function createInput() {\n var input = document.createElement(\"input\");\n\n input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);\n input.setAttribute(\"title\", options.title);\n\n self.setMultiple(options.multiple, input);\n\n if (options.folders && qq.supportedFeatures.folderSelection) {\n // selecting directories is only possible in Chrome now, via a vendor-specific prefixed attribute\n input.setAttribute(\"webkitdirectory\", \"\");\n }\n\n if (options.acceptFiles) {\n input.setAttribute(\"accept\", options.acceptFiles);\n }\n\n input.setAttribute(\"type\", \"file\");\n input.setAttribute(\"name\", options.name);\n\n qq(input).css({\n position: \"absolute\",\n // in Opera only 'browse' button\n // is clickable and it is located at\n // the right side of the input\n right: 0,\n top: 0,\n fontFamily: \"Arial\",\n // It's especially important to make this an arbitrarily large value\n // to ensure the rendered input button in IE takes up the entire\n // space of the container element. Otherwise, the left side of the\n // button will require a double-click to invoke the file chooser.\n // In other browsers, this might cause other issues, so a large font-size\n // is only used in IE. There is a bug in IE8 where the opacity style is ignored\n // in some cases when the font-size is large. So, this workaround is not applied\n // to IE8.\n fontSize: qq.ie() && !qq.ie8() ? \"3500px\" : \"118px\",\n margin: 0,\n padding: 0,\n cursor: \"pointer\",\n opacity: 0\n });\n\n // Setting the file input's height to 100% in IE7 causes\n // most of the visible button to be unclickable.\n !qq.ie7() && qq(input).css({height: \"100%\"});\n\n options.element.appendChild(input);\n\n disposeSupport.attach(input, \"change\", function() {\n options.onChange(input);\n });\n\n // **These event handlers will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers\n disposeSupport.attach(input, \"mouseover\", function() {\n qq(options.element).addClass(options.hoverClass);\n });\n disposeSupport.attach(input, \"mouseout\", function() {\n qq(options.element).removeClass(options.hoverClass);\n });\n\n disposeSupport.attach(input, \"focus\", function() {\n qq(options.element).addClass(options.focusClass);\n });\n disposeSupport.attach(input, \"blur\", function() {\n qq(options.element).removeClass(options.focusClass);\n });\n\n return input;\n }\n\n // Make button suitable container for input\n qq(options.element).css({\n position: \"relative\",\n overflow: \"hidden\",\n // Make sure browse button is in the right side in Internet Explorer\n direction: \"ltr\"\n });\n\n // Exposed API\n qq.extend(this, {\n getInput: function() {\n return input;\n },\n\n getButtonId: function() {\n return buttonId;\n },\n\n setMultiple: function(isMultiple, optInput) {\n var input = optInput || this.getInput();\n\n // Temporary workaround for bug in in iOS8 UIWebView that causes the browser to crash\n // before the file chooser appears if the file input doesn't contain a multiple attribute.\n // See #1283.\n if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {\n input.setAttribute(\"multiple\", \"\");\n }\n\n else {\n if (isMultiple) {\n input.setAttribute(\"multiple\", \"\");\n }\n else {\n input.removeAttribute(\"multiple\");\n }\n }\n },\n\n setAcceptFiles: function(acceptFiles) {\n if (acceptFiles !== options.acceptFiles) {\n input.setAttribute(\"accept\", acceptFiles);\n }\n },\n\n reset: function() {\n if (input.parentNode) {\n qq(input).remove();\n }\n\n qq(options.element).removeClass(options.focusClass);\n input = null;\n input = createInput();\n }\n });\n\n input = createInput();\n};\n\nqq.UploadButton.BUTTON_ID_ATTR_NAME = \"qq-button-id\";\n","/*globals qq */\nqq.UploadData = function(uploaderProxy) {\n \"use strict\";\n\n var data = [],\n byUuid = {},\n byStatus = {},\n byProxyGroupId = {},\n byBatchId = {};\n\n function getDataByIds(idOrIds) {\n if (qq.isArray(idOrIds)) {\n var entries = [];\n\n qq.each(idOrIds, function(idx, id) {\n entries.push(data[id]);\n });\n\n return entries;\n }\n\n return data[idOrIds];\n }\n\n function getDataByUuids(uuids) {\n if (qq.isArray(uuids)) {\n var entries = [];\n\n qq.each(uuids, function(idx, uuid) {\n entries.push(data[byUuid[uuid]]);\n });\n\n return entries;\n }\n\n return data[byUuid[uuids]];\n }\n\n function getDataByStatus(status) {\n var statusResults = [],\n statuses = [].concat(status);\n\n qq.each(statuses, function(index, statusEnum) {\n var statusResultIndexes = byStatus[statusEnum];\n\n if (statusResultIndexes !== undefined) {\n qq.each(statusResultIndexes, function(i, dataIndex) {\n statusResults.push(data[dataIndex]);\n });\n }\n });\n\n return statusResults;\n }\n\n qq.extend(this, {\n /**\n * Adds a new file to the data cache for tracking purposes.\n *\n * @param spec Data that describes this file. Possible properties are:\n *\n * - uuid: Initial UUID for this file.\n * - name: Initial name of this file.\n * - size: Size of this file, omit if this cannot be determined\n * - status: Initial `qq.status` for this file. Omit for `qq.status.SUBMITTING`.\n * - batchId: ID of the batch this file belongs to\n * - proxyGroupId: ID of the proxy group associated with this file\n * - onBeforeStatusChange(fileId): callback that is executed before the status change is broadcast\n *\n * @returns {number} Internal ID for this file.\n */\n addFile: function(spec) {\n var status = spec.status || qq.status.SUBMITTING,\n id = data.push({\n name: spec.name,\n originalName: spec.name,\n uuid: spec.uuid,\n size: spec.size == null ? -1 : spec.size,\n status: status,\n file: spec.file\n }) - 1;\n\n if (spec.batchId) {\n data[id].batchId = spec.batchId;\n\n if (byBatchId[spec.batchId] === undefined) {\n byBatchId[spec.batchId] = [];\n }\n byBatchId[spec.batchId].push(id);\n }\n\n if (spec.proxyGroupId) {\n data[id].proxyGroupId = spec.proxyGroupId;\n\n if (byProxyGroupId[spec.proxyGroupId] === undefined) {\n byProxyGroupId[spec.proxyGroupId] = [];\n }\n byProxyGroupId[spec.proxyGroupId].push(id);\n }\n\n data[id].id = id;\n byUuid[spec.uuid] = id;\n\n if (byStatus[status] === undefined) {\n byStatus[status] = [];\n }\n byStatus[status].push(id);\n\n spec.onBeforeStatusChange && spec.onBeforeStatusChange(id);\n uploaderProxy.onStatusChange(id, null, status);\n\n return id;\n },\n\n retrieve: function(optionalFilter) {\n if (qq.isObject(optionalFilter) && data.length) {\n if (optionalFilter.id !== undefined) {\n return getDataByIds(optionalFilter.id);\n }\n\n else if (optionalFilter.uuid !== undefined) {\n return getDataByUuids(optionalFilter.uuid);\n }\n\n else if (optionalFilter.status) {\n return getDataByStatus(optionalFilter.status);\n }\n }\n else {\n return qq.extend([], data, true);\n }\n },\n\n removeFileRef: function(id) {\n var record = getDataByIds(id);\n\n if (record) {\n delete record.file;\n }\n },\n\n reset: function() {\n data = [];\n byUuid = {};\n byStatus = {};\n byBatchId = {};\n },\n\n setStatus: function(id, newStatus) {\n var oldStatus = data[id].status,\n byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);\n\n byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);\n\n data[id].status = newStatus;\n\n if (byStatus[newStatus] === undefined) {\n byStatus[newStatus] = [];\n }\n byStatus[newStatus].push(id);\n\n uploaderProxy.onStatusChange(id, oldStatus, newStatus);\n },\n\n uuidChanged: function(id, newUuid) {\n var oldUuid = data[id].uuid;\n\n data[id].uuid = newUuid;\n byUuid[newUuid] = id;\n delete byUuid[oldUuid];\n },\n\n updateName: function(id, newName) {\n data[id].name = newName;\n },\n\n updateSize: function(id, newSize) {\n data[id].size = newSize;\n },\n\n // Only applicable if this file has a parent that we may want to reference later.\n setParentId: function(targetId, parentId) {\n data[targetId].parentId = parentId;\n },\n\n getIdsInProxyGroup: function(id) {\n var proxyGroupId = data[id].proxyGroupId;\n\n if (proxyGroupId) {\n return byProxyGroupId[proxyGroupId];\n }\n return [];\n },\n\n getIdsInBatch: function(id) {\n var batchId = data[id].batchId;\n\n return byBatchId[batchId];\n }\n });\n};\n\nqq.status = {\n SUBMITTING: \"submitting\",\n SUBMITTED: \"submitted\",\n REJECTED: \"rejected\",\n QUEUED: \"queued\",\n CANCELED: \"canceled\",\n PAUSED: \"paused\",\n UPLOADING: \"uploading\",\n UPLOAD_FINALIZING: \"upload finalizing\",\n UPLOAD_RETRYING: \"retrying upload\",\n UPLOAD_SUCCESSFUL: \"upload successful\",\n UPLOAD_FAILED: \"upload failed\",\n DELETE_FAILED: \"delete failed\",\n DELETING: \"deleting\",\n DELETED: \"deleted\"\n};\n","/*globals qq*/\n/**\n * Defines the public API for FineUploaderBasic mode.\n */\n(function() {\n \"use strict\";\n\n qq.basePublicApi = {\n // DEPRECATED - TODO REMOVE IN NEXT MAJOR RELEASE (replaced by addFiles)\n addBlobs: function(blobDataOrArray, params, endpoint) {\n this.addFiles(blobDataOrArray, params, endpoint);\n },\n\n addInitialFiles: function(cannedFileList) {\n var self = this;\n\n qq.each(cannedFileList, function(index, cannedFile) {\n self._addCannedFile(cannedFile);\n });\n },\n\n addFiles: function(data, params, endpoint) {\n this._maybeHandleIos8SafariWorkaround();\n\n var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId,\n\n processBlob = qq.bind(function(blob) {\n this._handleNewFile({\n blob: blob,\n name: this._options.blobs.defaultName\n }, batchId, verifiedFiles);\n }, this),\n\n processBlobData = qq.bind(function(blobData) {\n this._handleNewFile(blobData, batchId, verifiedFiles);\n }, this),\n\n processCanvas = qq.bind(function(canvas) {\n var blob = qq.canvasToBlob(canvas);\n\n this._handleNewFile({\n blob: blob,\n name: this._options.blobs.defaultName + \".png\"\n }, batchId, verifiedFiles);\n }, this),\n\n processCanvasData = qq.bind(function(canvasData) {\n var normalizedQuality = canvasData.quality && canvasData.quality / 100,\n blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);\n\n this._handleNewFile({\n blob: blob,\n name: canvasData.name\n }, batchId, verifiedFiles);\n }, this),\n\n processFileOrInput = qq.bind(function(fileOrInput) {\n if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {\n var files = Array.prototype.slice.call(fileOrInput.files),\n self = this;\n\n qq.each(files, function(idx, file) {\n self._handleNewFile(file, batchId, verifiedFiles);\n });\n }\n else {\n this._handleNewFile(fileOrInput, batchId, verifiedFiles);\n }\n }, this),\n\n normalizeData = function() {\n if (qq.isFileList(data)) {\n data = Array.prototype.slice.call(data);\n }\n data = [].concat(data);\n },\n\n self = this,\n verifiedFiles = [];\n\n this._currentBatchId = batchId;\n\n if (data) {\n normalizeData();\n\n qq.each(data, function(idx, fileContainer) {\n if (qq.isFileOrInput(fileContainer)) {\n processFileOrInput(fileContainer);\n }\n else if (qq.isBlob(fileContainer)) {\n processBlob(fileContainer);\n }\n else if (qq.isObject(fileContainer)) {\n if (fileContainer.blob && fileContainer.name) {\n processBlobData(fileContainer);\n }\n else if (fileContainer.canvas && fileContainer.name) {\n processCanvasData(fileContainer);\n }\n }\n else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === \"canvas\") {\n processCanvas(fileContainer);\n }\n else {\n self.log(fileContainer + \" is not a valid file container! Ignoring!\", \"warn\");\n }\n });\n\n this.log(\"Received \" + verifiedFiles.length + \" files.\");\n this._prepareItemsForUpload(verifiedFiles, params, endpoint);\n }\n },\n\n cancel: function(id) {\n var uploadData = this._uploadData.retrieve({id: id});\n\n if (uploadData && uploadData.status === qq.status.UPLOAD_FINALIZING) {\n this.log(qq.format(\"Ignoring cancel for file ID {} ({}). Finalizing upload.\", id, this.getName(id)), \"error\");\n }\n else {\n this._handler.cancel(id);\n }\n },\n\n cancelAll: function() {\n var storedIdsCopy = [],\n self = this;\n\n qq.extend(storedIdsCopy, this._storedIds);\n qq.each(storedIdsCopy, function(idx, storedFileId) {\n self.cancel(storedFileId);\n });\n\n this._handler.cancelAll();\n },\n\n clearStoredFiles: function() {\n this._storedIds = [];\n },\n\n continueUpload: function(id) {\n var uploadData = this._uploadData.retrieve({id: id});\n\n if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {\n return false;\n }\n\n if (uploadData.status === qq.status.PAUSED) {\n this.log(qq.format(\"Paused file ID {} ({}) will be continued. Not paused.\", id, this.getName(id)));\n this._uploadFile(id);\n return true;\n }\n else {\n this.log(qq.format(\"Ignoring continue for file ID {} ({}). Not paused.\", id, this.getName(id)), \"error\");\n }\n\n return false;\n },\n\n deleteFile: function(id) {\n return this._onSubmitDelete(id);\n },\n\n // TODO document?\n doesExist: function(fileOrBlobId) {\n return this._handler.isValid(fileOrBlobId);\n },\n\n // Generate a variable size thumbnail on an img or canvas,\n // returning a promise that is fulfilled when the attempt completes.\n // Thumbnail can either be based off of a URL for an image returned\n // by the server in the upload response, or the associated `Blob`.\n drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {\n var promiseToReturn = new qq.Promise(),\n fileOrUrl, options;\n\n if (this._imageGenerator) {\n fileOrUrl = this._thumbnailUrls[fileId];\n options = {\n customResizeFunction: customResizeFunction,\n maxSize: maxSize > 0 ? maxSize : null,\n scale: maxSize > 0\n };\n\n // If client-side preview generation is possible\n // and we are not specifically looking for the image URl returned by the server...\n if (!fromServer && qq.supportedFeatures.imagePreviews) {\n fileOrUrl = this.getFile(fileId);\n }\n\n /* jshint eqeqeq:false,eqnull:true */\n if (fileOrUrl == null) {\n promiseToReturn.failure({container: imgOrCanvas, error: \"File or URL not found.\"});\n }\n else {\n this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(\n function success(modifiedContainer) {\n promiseToReturn.success(modifiedContainer);\n },\n\n function failure(container, reason) {\n promiseToReturn.failure({container: container, error: reason || \"Problem generating thumbnail\"});\n }\n );\n }\n }\n else {\n promiseToReturn.failure({container: imgOrCanvas, error: \"Missing image generator module\"});\n }\n\n return promiseToReturn;\n },\n\n getButton: function(fileId) {\n return this._getButton(this._buttonIdsForFileIds[fileId]);\n },\n\n getEndpoint: function(fileId) {\n return this._endpointStore.get(fileId);\n },\n\n getFile: function(fileOrBlobId) {\n var file = this._handler.getFile(fileOrBlobId);\n var uploadDataRecord;\n\n if (!file) {\n uploadDataRecord = this._uploadData.retrieve({id: fileOrBlobId});\n\n if (uploadDataRecord) {\n file = uploadDataRecord.file;\n }\n }\n\n return file || null;\n },\n\n getInProgress: function() {\n return this._uploadData.retrieve({\n status: [\n qq.status.UPLOADING,\n qq.status.UPLOAD_RETRYING,\n qq.status.QUEUED\n ]\n }).length;\n },\n\n getName: function(id) {\n return this._uploadData.retrieve({id: id}).name;\n },\n\n // Parent ID for a specific file, or null if this is the parent, or if it has no parent.\n getParentId: function(id) {\n var uploadDataEntry = this.getUploads({id: id}),\n parentId = null;\n\n if (uploadDataEntry) {\n if (uploadDataEntry.parentId !== undefined) {\n parentId = uploadDataEntry.parentId;\n }\n }\n\n return parentId;\n },\n\n getResumableFilesData: function() {\n return this._handler.getResumableFilesData();\n },\n\n getSize: function(id) {\n return this._uploadData.retrieve({id: id}).size;\n },\n\n getNetUploads: function() {\n return this._netUploaded;\n },\n\n getRemainingAllowedItems: function() {\n var allowedItems = this._currentItemLimit;\n\n if (allowedItems > 0) {\n return allowedItems - this._netUploadedOrQueued;\n }\n\n return null;\n },\n\n getUploads: function(optionalFilter) {\n return this._uploadData.retrieve(optionalFilter);\n },\n\n getUuid: function(id) {\n return this._uploadData.retrieve({id: id}).uuid;\n },\n\n isResumable: function(id) {\n return this._handler.hasResumeRecord(id);\n },\n\n log: function(str, level) {\n if (this._options.debug && (!level || level === \"info\")) {\n qq.log(\"[Fine Uploader \" + qq.version + \"] \" + str);\n }\n else if (level && level !== \"info\") {\n qq.log(\"[Fine Uploader \" + qq.version + \"] \" + str, level);\n\n }\n },\n\n pauseUpload: function(id) {\n var uploadData = this._uploadData.retrieve({id: id});\n\n if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {\n return false;\n }\n\n // Pause only really makes sense if the file is uploading or retrying\n if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) {\n if (this._handler.pause(id)) {\n this._uploadData.setStatus(id, qq.status.PAUSED);\n return true;\n }\n else {\n this.log(qq.format(\"Unable to pause file ID {} ({}).\", id, this.getName(id)), \"error\");\n }\n }\n else {\n this.log(qq.format(\"Ignoring pause for file ID {} ({}). Not in progress.\", id, this.getName(id)), \"error\");\n }\n\n return false;\n },\n\n removeFileRef: function(id) {\n this._handler.expunge(id);\n this._uploadData.removeFileRef(id);\n },\n\n reset: function() {\n this.log(\"Resetting uploader...\");\n\n this._handler.reset();\n this._storedIds = [];\n this._autoRetries = [];\n this._retryTimeouts = [];\n this._preventRetries = [];\n this._thumbnailUrls = [];\n\n qq.each(this._buttons, function(idx, button) {\n button.reset();\n });\n\n this._paramsStore.reset();\n this._endpointStore.reset();\n this._netUploadedOrQueued = 0;\n this._netUploaded = 0;\n this._uploadData.reset();\n this._buttonIdsForFileIds = [];\n\n this._pasteHandler && this._pasteHandler.reset();\n this._options.session.refreshOnReset && this._refreshSessionData();\n\n this._succeededSinceLastAllComplete = [];\n this._failedSinceLastAllComplete = [];\n\n this._totalProgress && this._totalProgress.reset();\n\n this._customResumeDataStore.reset();\n },\n\n retry: function(id) {\n return this._manualRetry(id);\n },\n\n scaleImage: function(id, specs) {\n var self = this;\n\n return qq.Scaler.prototype.scaleImage(id, specs, {\n log: qq.bind(self.log, self),\n getFile: qq.bind(self.getFile, self),\n uploadData: self._uploadData\n });\n },\n\n setCustomHeaders: function(headers, id) {\n this._customHeadersStore.set(headers, id);\n },\n\n setCustomResumeData: function(id, data) {\n this._customResumeDataStore.set(data, id);\n },\n\n setDeleteFileCustomHeaders: function(headers, id) {\n this._deleteFileCustomHeadersStore.set(headers, id);\n },\n\n setDeleteFileEndpoint: function(endpoint, id) {\n this._deleteFileEndpointStore.set(endpoint, id);\n },\n\n setDeleteFileParams: function(params, id) {\n this._deleteFileParamsStore.set(params, id);\n },\n\n // Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button\n setEndpoint: function(endpoint, id) {\n this._endpointStore.set(endpoint, id);\n },\n\n setForm: function(elementOrId) {\n this._updateFormSupportAndParams(elementOrId);\n },\n\n setItemLimit: function(newItemLimit) {\n this._currentItemLimit = newItemLimit;\n },\n\n setName: function(id, newName) {\n this._uploadData.updateName(id, newName);\n },\n\n setParams: function(params, id) {\n this._paramsStore.set(params, id);\n },\n\n setUuid: function(id, newUuid) {\n return this._uploadData.uuidChanged(id, newUuid);\n },\n\n /**\n * Expose the internal status of a file id to the public api for manual state changes\n * @public\n *\n * @param {Number} id,\n * @param {String} newStatus\n *\n * @todo Implement the remaining methods\n */\n setStatus: function(id, newStatus) {\n var fileRecord = this.getUploads({id: id});\n if (!fileRecord) {\n throw new qq.Error(id + \" is not a valid file ID.\");\n }\n\n switch (newStatus) {\n case qq.status.DELETED:\n this._onDeleteComplete(id, null, false);\n break;\n case qq.status.DELETE_FAILED:\n this._onDeleteComplete(id, null, true);\n break;\n default:\n var errorMessage = \"Method setStatus called on '\" + name + \"' not implemented yet for \" + newStatus;\n this.log(errorMessage);\n throw new qq.Error(errorMessage);\n }\n },\n\n uploadStoredFiles: function() {\n if (this._storedIds.length === 0) {\n this._itemError(\"noFilesError\");\n }\n else {\n this._uploadStoredFiles();\n }\n }\n };\n\n /**\n * Defines the private (internal) API for FineUploaderBasic mode.\n */\n qq.basePrivateApi = {\n // Updates internal state with a file record (not backed by a live file). Returns the assigned ID.\n _addCannedFile: function(sessionData) {\n var self = this;\n\n return this._uploadData.addFile({\n uuid: sessionData.uuid,\n name: sessionData.name,\n size: sessionData.size,\n status: qq.status.UPLOAD_SUCCESSFUL,\n onBeforeStatusChange: function(id) {\n sessionData.deleteFileEndpoint && self.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);\n sessionData.deleteFileParams && self.setDeleteFileParams(sessionData.deleteFileParams, id);\n\n if (sessionData.thumbnailUrl) {\n self._thumbnailUrls[id] = sessionData.thumbnailUrl;\n }\n\n self._netUploaded++;\n self._netUploadedOrQueued++;\n }\n });\n },\n\n _annotateWithButtonId: function(file, associatedInput) {\n if (qq.isFile(file)) {\n file.qqButtonId = this._getButtonId(associatedInput);\n }\n },\n\n _batchError: function(message) {\n this._options.callbacks.onError(null, null, message, undefined);\n },\n\n _createDeleteHandler: function() {\n var self = this;\n\n return new qq.DeleteFileAjaxRequester({\n method: this._options.deleteFile.method.toUpperCase(),\n maxConnections: this._options.maxConnections,\n uuidParamName: this._options.request.uuidName,\n customHeaders: this._deleteFileCustomHeadersStore,\n paramsStore: this._deleteFileParamsStore,\n endpointStore: this._deleteFileEndpointStore,\n cors: this._options.cors,\n log: qq.bind(self.log, self),\n onDelete: function(id) {\n self._onDelete(id);\n self._options.callbacks.onDelete(id);\n },\n onDeleteComplete: function(id, xhrOrXdr, isError) {\n self._onDeleteComplete(id, xhrOrXdr, isError);\n self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);\n }\n\n });\n },\n\n _createPasteHandler: function() {\n var self = this;\n\n return new qq.PasteSupport({\n targetElement: this._options.paste.targetElement,\n callbacks: {\n log: qq.bind(self.log, self),\n pasteReceived: function(blob) {\n self._handleCheckedCallback({\n name: \"onPasteReceived\",\n callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),\n onSuccess: qq.bind(self._handlePasteSuccess, self, blob),\n identifier: \"pasted image\"\n });\n }\n }\n });\n },\n\n _createStore: function(initialValue, _readOnlyValues_) {\n var store = {},\n catchall = initialValue,\n perIdReadOnlyValues = {},\n readOnlyValues = _readOnlyValues_,\n copy = function(orig) {\n if (qq.isObject(orig)) {\n return qq.extend({}, orig);\n }\n return orig;\n },\n getReadOnlyValues = function() {\n if (qq.isFunction(readOnlyValues)) {\n return readOnlyValues();\n }\n return readOnlyValues;\n },\n includeReadOnlyValues = function(id, existing) {\n if (readOnlyValues && qq.isObject(existing)) {\n qq.extend(existing, getReadOnlyValues());\n }\n\n if (perIdReadOnlyValues[id]) {\n qq.extend(existing, perIdReadOnlyValues[id]);\n }\n };\n\n return {\n set: function(val, id) {\n /*jshint eqeqeq: true, eqnull: true*/\n if (id == null) {\n store = {};\n catchall = copy(val);\n }\n else {\n store[id] = copy(val);\n }\n },\n\n get: function(id) {\n var values;\n\n /*jshint eqeqeq: true, eqnull: true*/\n if (id != null && store[id]) {\n values = store[id];\n }\n else {\n values = copy(catchall);\n }\n\n includeReadOnlyValues(id, values);\n\n return copy(values);\n },\n\n addReadOnly: function(id, values) {\n // Only applicable to Object stores\n if (qq.isObject(store)) {\n // If null ID, apply readonly values to all files\n if (id === null) {\n if (qq.isFunction(values)) {\n readOnlyValues = values;\n }\n else {\n readOnlyValues = readOnlyValues || {};\n qq.extend(readOnlyValues, values);\n }\n }\n else {\n perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};\n qq.extend(perIdReadOnlyValues[id], values);\n }\n }\n },\n\n remove: function(fileId) {\n return delete store[fileId];\n },\n\n reset: function() {\n store = {};\n perIdReadOnlyValues = {};\n catchall = initialValue;\n }\n };\n },\n\n _createUploadDataTracker: function() {\n var self = this;\n\n return new qq.UploadData({\n getName: function(id) {\n return self.getName(id);\n },\n getUuid: function(id) {\n return self.getUuid(id);\n },\n getSize: function(id) {\n return self.getSize(id);\n },\n onStatusChange: function(id, oldStatus, newStatus) {\n self._onUploadStatusChange(id, oldStatus, newStatus);\n self._options.callbacks.onStatusChange(id, oldStatus, newStatus);\n self._maybeAllComplete(id, newStatus);\n\n if (self._totalProgress) {\n setTimeout(function() {\n self._totalProgress.onStatusChange(id, oldStatus, newStatus);\n }, 0);\n }\n }\n });\n },\n\n /**\n * Generate a tracked upload button.\n *\n * @param spec Object containing a required `element` property\n * along with optional `multiple`, `accept`, and `folders`.\n * @returns {qq.UploadButton}\n * @private\n */\n _createUploadButton: function(spec) {\n var self = this,\n acceptFiles = spec.accept || this._options.validation.acceptFiles,\n allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions,\n button;\n\n function allowMultiple() {\n if (qq.supportedFeatures.ajaxUploading) {\n // Workaround for bug in iOS7+ (see #1039)\n if (self._options.workarounds.iosEmptyVideos &&\n qq.ios() &&\n !qq.ios6() &&\n self._isAllowedExtension(allowedExtensions, \".mov\")) {\n\n return false;\n }\n\n if (spec.multiple === undefined) {\n return self._options.multiple;\n }\n\n return spec.multiple;\n }\n\n return false;\n }\n\n button = new qq.UploadButton({\n acceptFiles: acceptFiles,\n element: spec.element,\n focusClass: this._options.classes.buttonFocus,\n folders: spec.folders,\n hoverClass: this._options.classes.buttonHover,\n ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash,\n multiple: allowMultiple(),\n name: this._options.request.inputName,\n onChange: function(input) {\n self._onInputChange(input);\n },\n title: spec.title == null ? this._options.text.fileInputTitle : spec.title\n });\n\n this._disposeSupport.addDisposer(function() {\n button.dispose();\n });\n\n self._buttons.push(button);\n\n return button;\n },\n\n _createUploadHandler: function(additionalOptions, namespace) {\n var self = this,\n lastOnProgress = {},\n options = {\n debug: this._options.debug,\n maxConnections: this._options.maxConnections,\n cors: this._options.cors,\n paramsStore: this._paramsStore,\n endpointStore: this._endpointStore,\n chunking: this._options.chunking,\n resume: this._options.resume,\n blobs: this._options.blobs,\n log: qq.bind(self.log, self),\n preventRetryParam: this._options.retry.preventRetryResponseProperty,\n onProgress: function(id, name, loaded, total) {\n if (loaded < 0 || total < 0) {\n return;\n }\n\n if (lastOnProgress[id]) {\n if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {\n self._onProgress(id, name, loaded, total);\n self._options.callbacks.onProgress(id, name, loaded, total);\n }\n }\n else {\n self._onProgress(id, name, loaded, total);\n self._options.callbacks.onProgress(id, name, loaded, total);\n }\n\n lastOnProgress[id] = {loaded: loaded, total: total};\n\n },\n onComplete: function(id, name, result, xhr) {\n delete lastOnProgress[id];\n\n var status = self.getUploads({id: id}).status,\n retVal;\n\n // This is to deal with some observed cases where the XHR readyStateChange handler is\n // invoked by the browser multiple times for the same XHR instance with the same state\n // readyState value. Higher level: don't invoke complete-related code if we've already\n // done this.\n if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {\n return;\n }\n\n retVal = self._onComplete(id, name, result, xhr);\n\n // If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback\n // until the promise has been fulfilled.\n if (retVal instanceof qq.Promise) {\n retVal.done(function() {\n self._options.callbacks.onComplete(id, name, result, xhr);\n });\n }\n else {\n self._options.callbacks.onComplete(id, name, result, xhr);\n }\n },\n onCancel: function(id, name, cancelFinalizationEffort) {\n var promise = new qq.Promise();\n\n self._handleCheckedCallback({\n name: \"onCancel\",\n callback: qq.bind(self._options.callbacks.onCancel, self, id, name),\n onFailure: promise.failure,\n onSuccess: function() {\n cancelFinalizationEffort.then(function() {\n self._onCancel(id, name);\n });\n\n promise.success();\n },\n identifier: id\n });\n\n return promise;\n },\n onUploadPrep: qq.bind(this._onUploadPrep, this),\n onUpload: function(id, name) {\n self._onUpload(id, name);\n var onUploadResult = self._options.callbacks.onUpload(id, name);\n\n if (qq.isGenericPromise(onUploadResult)) {\n self.log(qq.format(\"onUpload for {} returned a Promise - waiting for resolution.\", id));\n return onUploadResult;\n }\n\n return new qq.Promise().success();\n },\n onUploadChunk: function(id, name, chunkData) {\n self._onUploadChunk(id, chunkData);\n var onUploadChunkResult = self._options.callbacks.onUploadChunk(id, name, chunkData);\n\n if (qq.isGenericPromise(onUploadChunkResult)) {\n self.log(qq.format(\"onUploadChunk for {}.{} returned a Promise - waiting for resolution.\", id, chunkData.partIndex));\n return onUploadChunkResult;\n }\n\n return new qq.Promise().success();\n },\n onUploadChunkSuccess: function(id, chunkData, result, xhr) {\n self._onUploadChunkSuccess(id, chunkData);\n self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);\n },\n onResume: function(id, name, chunkData, customResumeData) {\n return self._options.callbacks.onResume(id, name, chunkData, customResumeData);\n },\n onAutoRetry: function(id, name, responseJSON, xhr) {\n return self._onAutoRetry.apply(self, arguments);\n },\n onUuidChanged: function(id, newUuid) {\n self.log(\"Server requested UUID change from '\" + self.getUuid(id) + \"' to '\" + newUuid + \"'\");\n self.setUuid(id, newUuid);\n },\n getName: qq.bind(self.getName, self),\n getUuid: qq.bind(self.getUuid, self),\n getSize: qq.bind(self.getSize, self),\n setSize: qq.bind(self._setSize, self),\n getDataByUuid: function(uuid) {\n return self.getUploads({uuid: uuid});\n },\n isQueued: function(id) {\n var status = self.getUploads({id: id}).status;\n return status === qq.status.QUEUED ||\n status === qq.status.SUBMITTED ||\n status === qq.status.UPLOAD_RETRYING ||\n status === qq.status.PAUSED;\n },\n getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,\n getIdsInBatch: self._uploadData.getIdsInBatch,\n isInProgress: function(id) {\n return self.getUploads({id: id}).status === qq.status.UPLOADING;\n },\n getCustomResumeData: qq.bind(self._getCustomResumeData, self),\n setStatus: function(id, status) {\n self._uploadData.setStatus(id, status);\n }\n };\n\n qq.each(this._options.request, function(prop, val) {\n options[prop] = val;\n });\n\n options.customHeaders = this._customHeadersStore;\n\n if (additionalOptions) {\n qq.each(additionalOptions, function(key, val) {\n options[key] = val;\n });\n }\n\n return new qq.UploadHandlerController(options, namespace);\n },\n\n _fileOrBlobRejected: function(id) {\n this._netUploadedOrQueued--;\n this._uploadData.setStatus(id, qq.status.REJECTED);\n },\n\n _formatSize: function(bytes) {\n if (bytes === 0) {\n return bytes + this._options.text.sizeSymbols[0];\n }\n var i = -1;\n do {\n bytes = bytes / 1000;\n i++;\n } while (bytes > 999);\n\n return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i];\n },\n\n // Creates an internal object that tracks various properties of each extra button,\n // and then actually creates the extra button.\n _generateExtraButtonSpecs: function() {\n var self = this;\n\n this._extraButtonSpecs = {};\n\n qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {\n var multiple = extraButtonOptionEntry.multiple,\n validation = qq.extend({}, self._options.validation, true),\n extraButtonSpec = qq.extend({}, extraButtonOptionEntry);\n\n if (multiple === undefined) {\n multiple = self._options.multiple;\n }\n\n if (extraButtonSpec.validation) {\n qq.extend(validation, extraButtonOptionEntry.validation, true);\n }\n\n qq.extend(extraButtonSpec, {\n multiple: multiple,\n validation: validation\n }, true);\n\n self._initExtraButton(extraButtonSpec);\n });\n },\n\n _getButton: function(buttonId) {\n var extraButtonsSpec = this._extraButtonSpecs[buttonId];\n\n if (extraButtonsSpec) {\n return extraButtonsSpec.element;\n }\n else if (buttonId === this._defaultButtonId) {\n return this._options.button;\n }\n },\n\n /**\n * Gets the internally used tracking ID for a button.\n *\n * @param buttonOrFileInputOrFile `File`, `<input type=\"file\">`, or a button container element\n * @returns {*} The button's ID, or undefined if no ID is recoverable\n * @private\n */\n _getButtonId: function(buttonOrFileInputOrFile) {\n var inputs, fileInput,\n fileBlobOrInput = buttonOrFileInputOrFile;\n\n // We want the reference file/blob here if this is a proxy (a file that will be generated on-demand later)\n if (fileBlobOrInput instanceof qq.BlobProxy) {\n fileBlobOrInput = fileBlobOrInput.referenceBlob;\n }\n\n // If the item is a `Blob` it will never be associated with a button or drop zone.\n if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {\n if (qq.isFile(fileBlobOrInput)) {\n return fileBlobOrInput.qqButtonId;\n }\n else if (fileBlobOrInput.tagName.toLowerCase() === \"input\" &&\n fileBlobOrInput.type.toLowerCase() === \"file\") {\n\n return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);\n }\n\n inputs = fileBlobOrInput.getElementsByTagName(\"input\");\n\n qq.each(inputs, function(idx, input) {\n if (input.getAttribute(\"type\") === \"file\") {\n fileInput = input;\n return false;\n }\n });\n\n if (fileInput) {\n return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);\n }\n }\n },\n\n _getCustomResumeData: function(fileId) {\n return this._customResumeDataStore.get(fileId);\n },\n\n _getNotFinished: function() {\n return this._uploadData.retrieve({\n status: [\n qq.status.UPLOADING,\n qq.status.UPLOAD_RETRYING,\n qq.status.QUEUED,\n qq.status.SUBMITTING,\n qq.status.SUBMITTED,\n qq.status.PAUSED\n ]\n }).length;\n },\n\n // Get the validation options for this button. Could be the default validation option\n // or a specific one assigned to this particular button.\n _getValidationBase: function(buttonId) {\n var extraButtonSpec = this._extraButtonSpecs[buttonId];\n\n return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;\n },\n\n _getValidationDescriptor: function(fileWrapper) {\n if (fileWrapper.file instanceof qq.BlobProxy) {\n return {\n name: qq.getFilename(fileWrapper.file.referenceBlob),\n size: fileWrapper.file.referenceBlob.size\n };\n }\n\n return {\n name: this.getUploads({id: fileWrapper.id}).name,\n size: this.getUploads({id: fileWrapper.id}).size\n };\n },\n\n _getValidationDescriptors: function(fileWrappers) {\n var self = this,\n fileDescriptors = [];\n\n qq.each(fileWrappers, function(idx, fileWrapper) {\n fileDescriptors.push(self._getValidationDescriptor(fileWrapper));\n });\n\n return fileDescriptors;\n },\n\n // Allows camera access on either the default or an extra button for iOS devices.\n _handleCameraAccess: function() {\n if (this._options.camera.ios && qq.ios()) {\n var acceptIosCamera = \"image/*;capture=camera\",\n button = this._options.camera.button,\n buttonId = button ? this._getButtonId(button) : this._defaultButtonId,\n optionRoot = this._options;\n\n // If we are not targeting the default button, it is an \"extra\" button\n if (buttonId && buttonId !== this._defaultButtonId) {\n optionRoot = this._extraButtonSpecs[buttonId];\n }\n\n // Camera access won't work in iOS if the `multiple` attribute is present on the file input\n optionRoot.multiple = false;\n\n // update the options\n if (optionRoot.validation.acceptFiles === null) {\n optionRoot.validation.acceptFiles = acceptIosCamera;\n }\n else {\n optionRoot.validation.acceptFiles += \",\" + acceptIosCamera;\n }\n\n // update the already-created button\n qq.each(this._buttons, function(idx, button) {\n if (button.getButtonId() === buttonId) {\n button.setMultiple(optionRoot.multiple);\n button.setAcceptFiles(optionRoot.acceptFiles);\n\n return false;\n }\n });\n }\n },\n\n _handleCheckedCallback: function(details) {\n var self = this,\n callbackRetVal = details.callback();\n\n if (qq.isGenericPromise(callbackRetVal)) {\n this.log(details.name + \" - waiting for \" + details.name + \" promise to be fulfilled for \" + details.identifier);\n return callbackRetVal.then(\n function(successParam) {\n self.log(details.name + \" promise success for \" + details.identifier);\n details.onSuccess(successParam);\n },\n function() {\n if (details.onFailure) {\n self.log(details.name + \" promise failure for \" + details.identifier);\n details.onFailure();\n }\n else {\n self.log(details.name + \" promise failure for \" + details.identifier);\n }\n });\n }\n\n if (callbackRetVal !== false) {\n details.onSuccess(callbackRetVal);\n }\n else {\n if (details.onFailure) {\n this.log(details.name + \" - return value was 'false' for \" + details.identifier + \". Invoking failure callback.\");\n details.onFailure();\n }\n else {\n this.log(details.name + \" - return value was 'false' for \" + details.identifier + \". Will not proceed.\");\n }\n }\n\n return callbackRetVal;\n },\n\n // Updates internal state when a new file has been received, and adds it along with its ID to a passed array.\n _handleNewFile: function(file, batchId, newFileWrapperList) {\n var self = this,\n uuid = qq.getUniqueId(),\n size = -1,\n name = qq.getFilename(file),\n actualFile = file.blob || file,\n handler = this._customNewFileHandler ?\n this._customNewFileHandler :\n qq.bind(self._handleNewFileGeneric, self);\n\n if (!qq.isInput(actualFile) && actualFile.size >= 0) {\n size = actualFile.size;\n }\n\n handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {\n uploadData: self._uploadData,\n paramsStore: self._paramsStore,\n addFileToHandler: function(id, file) {\n self._handler.add(id, file);\n self._netUploadedOrQueued++;\n self._trackButton(id);\n }\n });\n },\n\n _handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {\n var id = this._uploadData.addFile({\n uuid: uuid,\n name: name,\n size: size,\n batchId: batchId,\n file: file\n });\n\n this._handler.add(id, file);\n\n this._trackButton(id);\n\n this._netUploadedOrQueued++;\n\n fileList.push({id: id, file: file});\n },\n\n _handlePasteSuccess: function(blob, extSuppliedName) {\n var extension = blob.type.split(\"/\")[1],\n name = extSuppliedName;\n\n /*jshint eqeqeq: true, eqnull: true*/\n if (name == null) {\n name = this._options.paste.defaultName;\n }\n\n name += \".\" + extension;\n\n this.addFiles({\n name: name,\n blob: blob\n });\n },\n\n _handleDeleteSuccess: function(id) {\n if (this.getUploads({id: id}).status !== qq.status.DELETED) {\n var name = this.getName(id);\n\n this._netUploadedOrQueued--;\n this._netUploaded--;\n this._handler.expunge(id);\n this._uploadData.setStatus(id, qq.status.DELETED);\n this.log(\"Delete request for '\" + name + \"' has succeeded.\");\n }\n },\n\n _handleDeleteFailed: function(id, xhrOrXdr) {\n var name = this.getName(id);\n\n this._uploadData.setStatus(id, qq.status.DELETE_FAILED);\n this.log(\"Delete request for '\" + name + \"' has failed.\", \"error\");\n\n // Check first if xhrOrXdr is actually passed or valid\n // For error reporting, we only have access to the response status if this is not\n // an `XDomainRequest`.\n if (!xhrOrXdr || xhrOrXdr.withCredentials === undefined) {\n this._options.callbacks.onError(id, name, \"Delete request failed\", xhrOrXdr);\n }\n else {\n this._options.callbacks.onError(id, name, \"Delete request failed with response code \" + xhrOrXdr.status, xhrOrXdr);\n }\n },\n\n // Creates an extra button element\n _initExtraButton: function(spec) {\n var button = this._createUploadButton({\n accept: spec.validation.acceptFiles,\n allowedExtensions: spec.validation.allowedExtensions,\n element: spec.element,\n folders: spec.folders,\n multiple: spec.multiple,\n title: spec.fileInputTitle\n });\n\n this._extraButtonSpecs[button.getButtonId()] = spec;\n },\n\n _initFormSupportAndParams: function() {\n this._formSupport = qq.FormSupport && new qq.FormSupport(\n this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)\n );\n\n if (this._formSupport && this._formSupport.attachedToForm) {\n this._paramsStore = this._createStore(\n this._options.request.params, this._formSupport.getFormInputsAsObject\n );\n\n this._options.autoUpload = this._formSupport.newAutoUpload;\n if (this._formSupport.newEndpoint) {\n this._options.request.endpoint = this._formSupport.newEndpoint;\n }\n }\n else {\n this._paramsStore = this._createStore(this._options.request.params);\n }\n },\n\n _isDeletePossible: function() {\n if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {\n return false;\n }\n\n if (this._options.cors.expected) {\n if (qq.supportedFeatures.deleteFileCorsXhr) {\n return true;\n }\n\n if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {\n return true;\n }\n\n return false;\n }\n\n return true;\n },\n\n _isAllowedExtension: function(allowed, fileName) {\n var valid = false;\n\n if (!allowed.length) {\n return true;\n }\n\n qq.each(allowed, function(idx, allowedExt) {\n /**\n * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the\n * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.\n */\n if (qq.isString(allowedExt)) {\n /*jshint eqeqeq: true, eqnull: true*/\n var extRegex = new RegExp(\"\\\\.\" + allowedExt + \"$\", \"i\");\n\n if (fileName.match(extRegex) != null) {\n valid = true;\n return false;\n }\n }\n });\n\n return valid;\n },\n\n /**\n * Constructs and returns a message that describes an item/file error. Also calls `onError` callback.\n *\n * @param code REQUIRED - a code that corresponds to a stock message describing this type of error\n * @param maybeNameOrNames names of the items that have failed, if applicable\n * @param item `File`, `Blob`, or `<input type=\"file\">`\n * @private\n */\n _itemError: function(code, maybeNameOrNames, item) {\n var message = this._options.messages[code],\n allowedExtensions = [],\n names = [].concat(maybeNameOrNames),\n name = names[0],\n buttonId = this._getButtonId(item),\n validationBase = this._getValidationBase(buttonId),\n extensionsForMessage, placeholderMatch;\n\n function r(name, replacement) { message = message.replace(name, replacement); }\n\n qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {\n /**\n * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the\n * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.\n */\n if (qq.isString(allowedExtension)) {\n allowedExtensions.push(allowedExtension);\n }\n });\n\n extensionsForMessage = allowedExtensions.join(\", \").toLowerCase();\n\n r(\"{file}\", this._options.formatFileName(name));\n r(\"{extensions}\", extensionsForMessage);\n r(\"{sizeLimit}\", this._formatSize(validationBase.sizeLimit));\n r(\"{minSizeLimit}\", this._formatSize(validationBase.minSizeLimit));\n\n placeholderMatch = message.match(/(\\{\\w+\\})/g);\n if (placeholderMatch !== null) {\n qq.each(placeholderMatch, function(idx, placeholder) {\n r(placeholder, names[idx]);\n });\n }\n\n this._options.callbacks.onError(null, name, message, undefined);\n\n return message;\n },\n\n /**\n * Conditionally orders a manual retry of a failed upload.\n *\n * @param id File ID of the failed upload\n * @param callback Optional callback to invoke if a retry is prudent.\n * In lieu of asking the upload handler to retry.\n * @returns {boolean} true if a manual retry will occur\n * @private\n */\n _manualRetry: function(id, callback) {\n if (this._onBeforeManualRetry(id)) {\n this._netUploadedOrQueued++;\n this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);\n\n if (callback) {\n callback(id);\n }\n else {\n this._handler.retry(id);\n }\n\n return true;\n }\n },\n\n _maybeAllComplete: function(id, status) {\n var self = this,\n notFinished = this._getNotFinished();\n\n if (status === qq.status.UPLOAD_SUCCESSFUL) {\n this._succeededSinceLastAllComplete.push(id);\n }\n else if (status === qq.status.UPLOAD_FAILED) {\n this._failedSinceLastAllComplete.push(id);\n }\n\n if (notFinished === 0 &&\n (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {\n // Attempt to ensure onAllComplete is not invoked before other callbacks, such as onCancel & onComplete\n setTimeout(function() {\n self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);\n }, 0);\n }\n },\n\n _maybeHandleIos8SafariWorkaround: function() {\n var self = this;\n\n if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {\n setTimeout(function() {\n window.alert(self._options.messages.unsupportedBrowserIos8Safari);\n }, 0);\n throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);\n }\n },\n\n _maybeParseAndSendUploadError: function(id, name, response, xhr) {\n // Assuming no one will actually set the response code to something other than 200\n // and still set 'success' to true...\n if (!response.success) {\n if (xhr && xhr.status !== 200 && !response.error) {\n this._options.callbacks.onError(id, name, \"XHR returned response code \" + xhr.status, xhr);\n }\n else {\n var errorReason = response.error ? response.error : this._options.text.defaultResponseError;\n this._options.callbacks.onError(id, name, errorReason, xhr);\n }\n }\n },\n\n _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {\n var self = this;\n\n if (items.length > index) {\n if (validItem || !this._options.validation.stopOnFirstInvalidFile) {\n //use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks\n setTimeout(function() {\n var validationDescriptor = self._getValidationDescriptor(items[index]),\n buttonId = self._getButtonId(items[index].file),\n button = self._getButton(buttonId);\n\n self._handleCheckedCallback({\n name: \"onValidate\",\n callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),\n onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),\n onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),\n identifier: \"Item '\" + validationDescriptor.name + \"', size: \" + validationDescriptor.size\n });\n }, 0);\n }\n else if (!validItem) {\n for (; index < items.length; index++) {\n self._fileOrBlobRejected(items[index].id);\n }\n }\n }\n },\n\n _onAllComplete: function(successful, failed) {\n this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);\n\n this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));\n\n this._succeededSinceLastAllComplete = [];\n this._failedSinceLastAllComplete = [];\n },\n\n /**\n * Attempt to automatically retry a failed upload.\n *\n * @param id The file ID of the failed upload\n * @param name The name of the file associated with the failed upload\n * @param responseJSON Response from the server, parsed into a javascript object\n * @param xhr Ajax transport used to send the failed request\n * @param callback Optional callback to be invoked if a retry is prudent.\n * Invoked in lieu of asking the upload handler to retry.\n * @returns {boolean} true if an auto-retry will occur\n * @private\n */\n _onAutoRetry: function(id, name, responseJSON, xhr, callback) {\n var self = this;\n\n self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];\n\n if (self._shouldAutoRetry(id)) {\n var retryWaitPeriod = self._options.retry.autoAttemptDelay * 1000;\n\n self._maybeParseAndSendUploadError.apply(self, arguments);\n self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);\n self._onBeforeAutoRetry(id, name);\n\n self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);\n self._retryTimeouts[id] = setTimeout(function() {\n self.log(\"Starting retry for \" + name + \"...\");\n\n if (callback) {\n callback(id);\n }\n else {\n self._handler.retry(id);\n }\n }, retryWaitPeriod);\n\n return true;\n }\n },\n\n _onBeforeAutoRetry: function(id, name) {\n this.log(\"Waiting \" + this._options.retry.autoAttemptDelay + \" seconds before retrying \" + name + \"...\");\n },\n\n //return false if we should not attempt the requested retry\n _onBeforeManualRetry: function(id) {\n var itemLimit = this._currentItemLimit,\n fileName;\n\n if (this._preventRetries[id]) {\n this.log(\"Retries are forbidden for id \" + id, \"warn\");\n return false;\n }\n else if (this._handler.isValid(id)) {\n fileName = this.getName(id);\n\n if (this._options.callbacks.onManualRetry(id, fileName) === false) {\n return false;\n }\n\n if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {\n this._itemError(\"retryFailTooManyItems\");\n return false;\n }\n\n this.log(\"Retrying upload for '\" + fileName + \"' (id: \" + id + \")...\");\n return true;\n }\n else {\n this.log(\"'\" + id + \"' is not a valid file ID\", \"error\");\n return false;\n }\n },\n\n _onCancel: function(id, name) {\n this._netUploadedOrQueued--;\n\n clearTimeout(this._retryTimeouts[id]);\n\n var storedItemIndex = qq.indexOf(this._storedIds, id);\n if (!this._options.autoUpload && storedItemIndex >= 0) {\n this._storedIds.splice(storedItemIndex, 1);\n }\n\n this._uploadData.setStatus(id, qq.status.CANCELED);\n },\n\n _onComplete: function(id, name, result, xhr) {\n if (!result.success) {\n this._netUploadedOrQueued--;\n this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);\n\n if (result[this._options.retry.preventRetryResponseProperty] === true) {\n this._preventRetries[id] = true;\n }\n }\n else {\n if (result.thumbnailUrl) {\n this._thumbnailUrls[id] = result.thumbnailUrl;\n }\n\n this._netUploaded++;\n this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);\n }\n\n this._maybeParseAndSendUploadError(id, name, result, xhr);\n\n return result.success ? true : false;\n },\n\n _onDelete: function(id) {\n this._uploadData.setStatus(id, qq.status.DELETING);\n },\n\n _onDeleteComplete: function(id, xhrOrXdr, isError) {\n var name = this.getName(id);\n\n if (isError) {\n this._handleDeleteFailed(id, xhrOrXdr);\n }\n else {\n this._handleDeleteSuccess(id);\n }\n },\n\n _onInputChange: function(input) {\n var fileIndex;\n\n if (qq.supportedFeatures.ajaxUploading) {\n for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {\n this._annotateWithButtonId(input.files[fileIndex], input);\n }\n\n this.addFiles(input.files);\n }\n // Android 2.3.x will fire `onchange` even if no file has been selected\n else if (input.value.length > 0) {\n this.addFiles(input);\n }\n\n qq.each(this._buttons, function(idx, button) {\n button.reset();\n });\n },\n\n _onProgress: function(id, name, loaded, total) {\n this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);\n },\n\n _onSubmit: function(id, name) {\n //nothing to do yet in core uploader\n },\n\n _onSubmitCallbackSuccess: function(id, name) {\n this._onSubmit.apply(this, arguments);\n this._uploadData.setStatus(id, qq.status.SUBMITTED);\n this._onSubmitted.apply(this, arguments);\n\n if (this._options.autoUpload) {\n this._options.callbacks.onSubmitted.apply(this, arguments);\n this._uploadFile(id);\n }\n else {\n this._storeForLater(id);\n this._options.callbacks.onSubmitted.apply(this, arguments);\n }\n },\n\n _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {\n var uuid = this.getUuid(id),\n adjustedOnSuccessCallback;\n\n if (onSuccessCallback) {\n adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);\n }\n\n if (this._isDeletePossible()) {\n this._handleCheckedCallback({\n name: \"onSubmitDelete\",\n callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),\n onSuccess: adjustedOnSuccessCallback ||\n qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),\n identifier: id\n });\n return true;\n }\n else {\n this.log(\"Delete request ignored for ID \" + id + \", delete feature is disabled or request not possible \" +\n \"due to CORS on a user agent that does not support pre-flighting.\", \"warn\");\n return false;\n }\n },\n\n _onSubmitted: function(id) {\n //nothing to do in the base uploader\n },\n\n _onTotalProgress: function(loaded, total) {\n this._options.callbacks.onTotalProgress(loaded, total);\n },\n\n _onUploadPrep: function(id) {\n // nothing to do in the core uploader for now\n },\n\n _onUpload: function(id, name) {\n this._uploadData.setStatus(id, qq.status.UPLOADING);\n },\n\n _onUploadChunk: function(id, chunkData) {\n //nothing to do in the base uploader\n },\n\n _onUploadChunkSuccess: function(id, chunkData) {\n if (!this._preventRetries[id] && this._options.retry.enableAuto) {\n this._autoRetries[id] = 0;\n }\n },\n\n _onUploadStatusChange: function(id, oldStatus, newStatus) {\n // Make sure a \"queued\" retry attempt is canceled if the upload has been paused\n if (newStatus === qq.status.PAUSED) {\n clearTimeout(this._retryTimeouts[id]);\n }\n },\n\n _onValidateBatchCallbackFailure: function(fileWrappers) {\n var self = this;\n\n qq.each(fileWrappers, function(idx, fileWrapper) {\n self._fileOrBlobRejected(fileWrapper.id);\n });\n },\n\n _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {\n var errorMessage,\n itemLimit = this._currentItemLimit,\n proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;\n\n if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {\n if (items.length > 0) {\n this._handleCheckedCallback({\n name: \"onValidate\",\n callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),\n onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),\n onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),\n identifier: \"Item '\" + items[0].file.name + \"', size: \" + items[0].file.size\n });\n }\n else {\n this._itemError(\"noFilesError\");\n }\n }\n else {\n this._onValidateBatchCallbackFailure(items);\n errorMessage = this._options.messages.tooManyItemsError\n .replace(/\\{netItems\\}/g, proposedNetFilesUploadedOrQueued)\n .replace(/\\{itemLimit\\}/g, itemLimit);\n this._batchError(errorMessage);\n }\n },\n\n _onValidateCallbackFailure: function(items, index, params, endpoint) {\n var nextIndex = index + 1;\n\n this._fileOrBlobRejected(items[index].id, items[index].file.name);\n\n this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);\n },\n\n _onValidateCallbackSuccess: function(items, index, params, endpoint) {\n var self = this,\n nextIndex = index + 1,\n validationDescriptor = this._getValidationDescriptor(items[index]);\n\n this._validateFileOrBlobData(items[index], validationDescriptor)\n .then(\n function() {\n self._upload(items[index].id, params, endpoint);\n self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);\n },\n function() {\n self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);\n }\n );\n },\n\n _prepareItemsForUpload: function(items, params, endpoint) {\n if (items.length === 0) {\n this._itemError(\"noFilesError\");\n return;\n }\n\n var validationDescriptors = this._getValidationDescriptors(items),\n buttonId = this._getButtonId(items[0].file),\n button = this._getButton(buttonId);\n\n this._handleCheckedCallback({\n name: \"onValidateBatch\",\n callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),\n onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),\n onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),\n identifier: \"batch validation\"\n });\n },\n\n _preventLeaveInProgress: function() {\n var self = this;\n\n this._disposeSupport.attach(window, \"beforeunload\", function(e) {\n if (self.getInProgress()) {\n e = e || window.event;\n // for ie, ff\n e.returnValue = self._options.messages.onLeave;\n // for webkit\n return self._options.messages.onLeave;\n }\n });\n },\n\n // Attempts to refresh session data only if the `qq.Session` module exists\n // and a session endpoint has been specified. The `onSessionRequestComplete`\n // callback will be invoked once the refresh is complete.\n _refreshSessionData: function() {\n var self = this,\n options = this._options.session;\n\n /* jshint eqnull:true */\n if (qq.Session && this._options.session.endpoint != null) {\n if (!this._session) {\n qq.extend(options, {cors: this._options.cors});\n\n options.log = qq.bind(this.log, this);\n options.addFileRecord = qq.bind(this._addCannedFile, this);\n\n this._session = new qq.Session(options);\n }\n\n setTimeout(function() {\n self._session.refresh().then(function(response, xhrOrXdr) {\n self._sessionRequestComplete();\n self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);\n\n }, function(response, xhrOrXdr) {\n\n self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);\n });\n }, 0);\n }\n },\n\n _sessionRequestComplete: function() {},\n\n _setSize: function(id, newSize) {\n this._uploadData.updateSize(id, newSize);\n this._totalProgress && this._totalProgress.onNewSize(id);\n },\n\n _shouldAutoRetry: function(id) {\n var uploadData = this._uploadData.retrieve({id: id});\n\n /*jshint laxbreak: true */\n if (!this._preventRetries[id]\n && this._options.retry.enableAuto\n && uploadData.status !== qq.status.PAUSED) {\n\n if (this._autoRetries[id] === undefined) {\n this._autoRetries[id] = 0;\n }\n\n if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {\n this._autoRetries[id] += 1;\n return true;\n }\n }\n\n return false;\n },\n\n _storeForLater: function(id) {\n this._storedIds.push(id);\n },\n\n // Maps a file with the button that was used to select it.\n _trackButton: function(id) {\n var buttonId;\n\n if (qq.supportedFeatures.ajaxUploading) {\n buttonId = this._handler.getFile(id).qqButtonId;\n }\n else {\n buttonId = this._getButtonId(this._handler.getInput(id));\n }\n\n if (buttonId) {\n this._buttonIdsForFileIds[id] = buttonId;\n }\n },\n\n _updateFormSupportAndParams: function(formElementOrId) {\n this._options.form.element = formElementOrId;\n\n this._formSupport = qq.FormSupport && new qq.FormSupport(\n this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)\n );\n\n if (this._formSupport && this._formSupport.attachedToForm) {\n this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject);\n\n this._options.autoUpload = this._formSupport.newAutoUpload;\n if (this._formSupport.newEndpoint) {\n this.setEndpoint(this._formSupport.newEndpoint);\n }\n }\n },\n\n _upload: function(id, params, endpoint) {\n var name = this.getName(id);\n\n if (params) {\n this.setParams(params, id);\n }\n\n if (endpoint) {\n this.setEndpoint(endpoint, id);\n }\n\n this._handleCheckedCallback({\n name: \"onSubmit\",\n callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),\n onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),\n onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),\n identifier: id\n });\n },\n\n _uploadFile: function(id) {\n if (!this._handler.upload(id)) {\n this._uploadData.setStatus(id, qq.status.QUEUED);\n }\n },\n\n _uploadStoredFiles: function() {\n var idToUpload, stillSubmitting,\n self = this;\n\n while (this._storedIds.length) {\n idToUpload = this._storedIds.shift();\n this._uploadFile(idToUpload);\n }\n\n // If we are still waiting for some files to clear validation, attempt to upload these again in a bit\n stillSubmitting = this.getUploads({status: qq.status.SUBMITTING}).length;\n if (stillSubmitting) {\n qq.log(\"Still waiting for \" + stillSubmitting + \" files to clear submit queue. Will re-parse stored IDs array shortly.\");\n setTimeout(function() {\n self._uploadStoredFiles();\n }, 1000);\n }\n },\n\n /**\n * Performs some internal validation checks on an item, defined in the `validation` option.\n *\n * @param fileWrapper Wrapper containing a `file` along with an `id`\n * @param validationDescriptor Normalized information about the item (`size`, `name`).\n * @returns qq.Promise with appropriate callbacks invoked depending on the validity of the file\n * @private\n */\n _validateFileOrBlobData: function(fileWrapper, validationDescriptor) {\n var self = this,\n file = (function() {\n if (fileWrapper.file instanceof qq.BlobProxy) {\n return fileWrapper.file.referenceBlob;\n }\n return fileWrapper.file;\n }()),\n name = validationDescriptor.name,\n size = validationDescriptor.size,\n buttonId = this._getButtonId(fileWrapper.file),\n validationBase = this._getValidationBase(buttonId),\n validityChecker = new qq.Promise();\n\n validityChecker.then(\n function() {},\n function() {\n self._fileOrBlobRejected(fileWrapper.id, name);\n });\n\n if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {\n this._itemError(\"typeError\", name, file);\n return validityChecker.failure();\n }\n\n if (!this._options.validation.allowEmpty && size === 0) {\n this._itemError(\"emptyError\", name, file);\n return validityChecker.failure();\n }\n\n if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {\n this._itemError(\"sizeError\", name, file);\n return validityChecker.failure();\n }\n\n if (size > 0 && size < validationBase.minSizeLimit) {\n this._itemError(\"minSizeError\", name, file);\n return validityChecker.failure();\n }\n\n if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {\n new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(\n validityChecker.success,\n function(errorCode) {\n self._itemError(errorCode + \"ImageError\", name, file);\n validityChecker.failure();\n }\n );\n }\n else {\n validityChecker.success();\n }\n\n return validityChecker;\n },\n\n _wrapCallbacks: function() {\n var self, safeCallback, prop;\n\n self = this;\n\n safeCallback = function(name, callback, args) {\n var errorMsg;\n\n try {\n return callback.apply(self, args);\n }\n catch (exception) {\n errorMsg = exception.message || exception.toString();\n self.log(\"Caught exception in '\" + name + \"' callback - \" + errorMsg, \"error\");\n }\n };\n\n /* jshint forin: false, loopfunc: true */\n for (prop in this._options.callbacks) {\n (function() {\n var callbackName, callbackFunc;\n callbackName = prop;\n callbackFunc = self._options.callbacks[callbackName];\n self._options.callbacks[callbackName] = function() {\n return safeCallback(callbackName, callbackFunc, arguments);\n };\n }());\n }\n }\n };\n}());\n","/*globals qq*/\n(function() {\n \"use strict\";\n\n qq.FineUploaderBasic = function(o) {\n var self = this;\n\n // These options define FineUploaderBasic mode.\n this._options = {\n debug: false,\n button: null,\n multiple: true,\n maxConnections: 3,\n disableCancelForFormUploads: false,\n autoUpload: true,\n warnBeforeUnload: true,\n\n request: {\n customHeaders: {},\n endpoint: \"/server/upload\",\n filenameParam: \"qqfilename\",\n forceMultipart: true,\n inputName: \"qqfile\",\n method: \"POST\",\n omitDefaultParams: false,\n params: {},\n paramsInBody: true,\n requireSuccessJson: true,\n totalFileSizeName: \"qqtotalfilesize\",\n uuidName: \"qquuid\"\n },\n\n validation: {\n allowedExtensions: [],\n sizeLimit: 0,\n minSizeLimit: 0,\n itemLimit: 0,\n stopOnFirstInvalidFile: true,\n acceptFiles: null,\n image: {\n maxHeight: 0,\n maxWidth: 0,\n minHeight: 0,\n minWidth: 0\n },\n allowEmpty: false\n },\n\n callbacks: {\n onSubmit: function(id, name) {},\n onSubmitted: function(id, name) {},\n onComplete: function(id, name, responseJSON, maybeXhr) {},\n onAllComplete: function(successful, failed) {},\n onCancel: function(id, name) {},\n onUpload: function(id, name) {},\n onUploadChunk: function(id, name, chunkData) {},\n onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},\n onResume: function(id, fileName, chunkData, customResumeData) {},\n onProgress: function(id, name, loaded, total) {},\n onTotalProgress: function(loaded, total) {},\n onError: function(id, name, reason, maybeXhrOrXdr) {},\n onAutoRetry: function(id, name, attemptNumber) {},\n onManualRetry: function(id, name) {},\n onValidateBatch: function(fileOrBlobData) {},\n onValidate: function(fileOrBlobData) {},\n onSubmitDelete: function(id) {},\n onDelete: function(id) {},\n onDeleteComplete: function(id, xhrOrXdr, isError) {},\n onPasteReceived: function(blob) {},\n onStatusChange: function(id, oldStatus, newStatus) {},\n onSessionRequestComplete: function(response, success, xhrOrXdr) {}\n },\n\n messages: {\n typeError: \"{file} has an invalid extension. Valid extension(s): {extensions}.\",\n sizeError: \"{file} is too large, maximum file size is {sizeLimit}.\",\n minSizeError: \"{file} is too small, minimum file size is {minSizeLimit}.\",\n emptyError: \"{file} is empty, please select files again without it.\",\n noFilesError: \"No files to upload.\",\n tooManyItemsError: \"Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.\",\n maxHeightImageError: \"Image is too tall.\",\n maxWidthImageError: \"Image is too wide.\",\n minHeightImageError: \"Image is not tall enough.\",\n minWidthImageError: \"Image is not wide enough.\",\n retryFailTooManyItems: \"Retry failed - you have reached your file limit.\",\n onLeave: \"The files are being uploaded, if you leave now the upload will be canceled.\",\n unsupportedBrowserIos8Safari: \"Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues.\"\n },\n\n retry: {\n enableAuto: false,\n maxAutoAttempts: 3,\n autoAttemptDelay: 5,\n preventRetryResponseProperty: \"preventRetry\"\n },\n\n classes: {\n buttonHover: \"qq-upload-button-hover\",\n buttonFocus: \"qq-upload-button-focus\"\n },\n\n chunking: {\n enabled: false,\n concurrent: {\n enabled: false\n },\n mandatory: false,\n paramNames: {\n partIndex: \"qqpartindex\",\n partByteOffset: \"qqpartbyteoffset\",\n chunkSize: \"qqchunksize\",\n totalFileSize: \"qqtotalfilesize\",\n totalParts: \"qqtotalparts\"\n },\n partSize: function(id) {\n return 2000000;\n },\n // only relevant for traditional endpoints, only required when concurrent.enabled === true\n success: {\n endpoint: null,\n\n headers: function(id) {\n return null;\n },\n\n jsonPayload: false,\n\n method: \"POST\",\n\n params: function(id) {\n return null;\n },\n\n resetOnStatus: []\n }\n },\n\n resume: {\n enabled: false,\n recordsExpireIn: 7, //days\n paramNames: {\n resuming: \"qqresume\"\n },\n customKeys: function(fileId) {\n return [];\n }\n },\n\n formatFileName: function(fileOrBlobName) {\n return fileOrBlobName;\n },\n\n text: {\n defaultResponseError: \"Upload failure reason unknown\",\n fileInputTitle: \"file input\",\n sizeSymbols: [\"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"]\n },\n\n deleteFile: {\n enabled: false,\n method: \"DELETE\",\n endpoint: \"/server/upload\",\n customHeaders: {},\n params: {}\n },\n\n cors: {\n expected: false,\n sendCredentials: false,\n allowXdr: false\n },\n\n blobs: {\n defaultName: \"misc_data\"\n },\n\n paste: {\n targetElement: null,\n defaultName: \"pasted_image\"\n },\n\n camera: {\n ios: false,\n\n // if ios is true: button is null means target the default button, otherwise target the button specified\n button: null\n },\n\n // This refers to additional upload buttons to be handled by Fine Uploader.\n // Each element is an object, containing `element` as the only required\n // property. The `element` must be a container that will ultimately\n // contain an invisible `<input type=\"file\">` created by Fine Uploader.\n // Optional properties of each object include `multiple`, `validation`,\n // and `folders`.\n extraButtons: [],\n\n // Depends on the session module. Used to query the server for an initial file list\n // during initialization and optionally after a `reset`.\n session: {\n endpoint: null,\n params: {},\n customHeaders: {},\n refreshOnReset: true\n },\n\n // Send parameters associated with an existing form along with the files\n form: {\n // Element ID, HTMLElement, or null\n element: \"qq-form\",\n\n // Overrides the base `autoUpload`, unless `element` is null.\n autoUpload: false,\n\n // true = upload files on form submission (and squelch submit event)\n interceptSubmit: true\n },\n\n // scale images client side, upload a new file for each scaled version\n scaling: {\n customResizer: null,\n\n // send the original file as well\n sendOriginal: true,\n\n // fox orientation for scaled images\n orient: true,\n\n // If null, scaled image type will match reference image type. This value will be referred to\n // for any size record that does not specific a type.\n defaultType: null,\n\n defaultQuality: 80,\n\n failureText: \"Failed to scale\",\n\n includeExif: false,\n\n // metadata about each requested scaled version\n sizes: []\n },\n\n workarounds: {\n iosEmptyVideos: true,\n ios8SafariUploads: true,\n ios8BrowserCrash: false\n }\n };\n\n // Replace any default options with user defined ones\n qq.extend(this._options, o, true);\n\n this._buttons = [];\n this._extraButtonSpecs = {};\n this._buttonIdsForFileIds = [];\n\n this._wrapCallbacks();\n this._disposeSupport = new qq.DisposeSupport();\n\n this._storedIds = [];\n this._autoRetries = [];\n this._retryTimeouts = [];\n this._preventRetries = [];\n this._thumbnailUrls = [];\n\n this._netUploadedOrQueued = 0;\n this._netUploaded = 0;\n this._uploadData = this._createUploadDataTracker();\n\n this._initFormSupportAndParams();\n\n this._customHeadersStore = this._createStore(this._options.request.customHeaders);\n this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);\n\n this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);\n\n this._endpointStore = this._createStore(this._options.request.endpoint);\n this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);\n\n this._handler = this._createUploadHandler();\n\n this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();\n\n if (this._options.button) {\n this._defaultButtonId = this._createUploadButton({\n element: this._options.button,\n title: this._options.text.fileInputTitle\n }).getButtonId();\n }\n\n this._generateExtraButtonSpecs();\n\n this._handleCameraAccess();\n\n if (this._options.paste.targetElement) {\n if (qq.PasteSupport) {\n this._pasteHandler = this._createPasteHandler();\n }\n else {\n this.log(\"Paste support module not found\", \"error\");\n }\n }\n\n this._options.warnBeforeUnload && this._preventLeaveInProgress();\n\n this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));\n this._refreshSessionData();\n\n this._succeededSinceLastAllComplete = [];\n this._failedSinceLastAllComplete = [];\n\n this._scaler = (qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this))) || {};\n if (this._scaler.enabled) {\n this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);\n }\n\n if (qq.TotalProgress && qq.supportedFeatures.progressBar) {\n this._totalProgress = new qq.TotalProgress(\n qq.bind(this._onTotalProgress, this),\n\n function(id) {\n var entry = self._uploadData.retrieve({id: id});\n return (entry && entry.size) || 0;\n }\n );\n }\n\n this._currentItemLimit = this._options.validation.itemLimit;\n\n this._customResumeDataStore = this._createStore();\n };\n\n // Define the private & public API methods.\n qq.FineUploaderBasic.prototype = qq.basePublicApi;\n qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);\n}());\n","/*globals qq, XDomainRequest*/\n/** Generic class for sending non-upload ajax requests and handling the associated responses **/\nqq.AjaxRequester = function(o) {\n \"use strict\";\n\n var log, shouldParamsBeInQueryString,\n queue = [],\n requestData = {},\n options = {\n acceptHeader: null,\n validMethods: [\"PATCH\", \"POST\", \"PUT\"],\n method: \"POST\",\n contentType: \"application/x-www-form-urlencoded\",\n maxConnections: 3,\n customHeaders: {},\n endpointStore: {},\n paramsStore: {},\n mandatedParams: {},\n allowXRequestedWithAndCacheControl: true,\n successfulResponseCodes: {\n DELETE: [200, 202, 204],\n PATCH: [200, 201, 202, 203, 204],\n POST: [200, 201, 202, 203, 204],\n PUT: [200, 201, 202, 203, 204],\n GET: [200]\n },\n cors: {\n expected: false,\n sendCredentials: false\n },\n log: function(str, level) {},\n onSend: function(id) {},\n onComplete: function(id, xhrOrXdr, isError) {},\n onProgress: null\n };\n\n qq.extend(options, o);\n log = options.log;\n\n if (qq.indexOf(options.validMethods, options.method) < 0) {\n throw new Error(\"'\" + options.method + \"' is not a supported method for this type of request!\");\n }\n\n // [Simple methods](http://www.w3.org/TR/cors/#simple-method)\n // are defined by the W3C in the CORS spec as a list of methods that, in part,\n // make a CORS request eligible to be exempt from preflighting.\n function isSimpleMethod() {\n return qq.indexOf([\"GET\", \"POST\", \"HEAD\"], options.method) >= 0;\n }\n\n // [Simple headers](http://www.w3.org/TR/cors/#simple-header)\n // are defined by the W3C in the CORS spec as a list of headers that, in part,\n // make a CORS request eligible to be exempt from preflighting.\n function containsNonSimpleHeaders(headers) {\n var containsNonSimple = false;\n\n qq.each(containsNonSimple, function(idx, header) {\n if (qq.indexOf([\"Accept\", \"Accept-Language\", \"Content-Language\", \"Content-Type\"], header) < 0) {\n containsNonSimple = true;\n return false;\n }\n });\n\n return containsNonSimple;\n }\n\n function isXdr(xhr) {\n //The `withCredentials` test is a commonly accepted way to determine if XHR supports CORS.\n return options.cors.expected && xhr.withCredentials === undefined;\n }\n\n // Returns either a new `XMLHttpRequest` or `XDomainRequest` instance.\n function getCorsAjaxTransport() {\n var xhrOrXdr;\n\n if (window.XMLHttpRequest || window.ActiveXObject) {\n xhrOrXdr = qq.createXhrInstance();\n\n if (xhrOrXdr.withCredentials === undefined) {\n xhrOrXdr = new XDomainRequest();\n // Workaround for XDR bug in IE9 - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment\n xhrOrXdr.onload = function() {};\n xhrOrXdr.onerror = function() {};\n xhrOrXdr.ontimeout = function() {};\n xhrOrXdr.onprogress = function() {};\n }\n }\n\n return xhrOrXdr;\n }\n\n // Returns either a new XHR/XDR instance, or an existing one for the associated `File` or `Blob`.\n function getXhrOrXdr(id, suppliedXhr) {\n var xhrOrXdr = requestData[id] && requestData[id].xhr;\n\n if (!xhrOrXdr) {\n if (suppliedXhr) {\n xhrOrXdr = suppliedXhr;\n }\n else {\n if (options.cors.expected) {\n xhrOrXdr = getCorsAjaxTransport();\n }\n else {\n xhrOrXdr = qq.createXhrInstance();\n }\n }\n\n requestData[id].xhr = xhrOrXdr;\n }\n\n return xhrOrXdr;\n }\n\n // Removes element from queue, sends next request\n function dequeue(id) {\n var i = qq.indexOf(queue, id),\n max = options.maxConnections,\n nextId;\n\n delete requestData[id];\n queue.splice(i, 1);\n\n if (queue.length >= max && i < max) {\n nextId = queue[max - 1];\n sendRequest(nextId);\n }\n }\n\n function onComplete(id, xdrError) {\n var xhr = getXhrOrXdr(id),\n method = options.method,\n isError = xdrError === true;\n\n dequeue(id);\n\n if (isError) {\n log(method + \" request for \" + id + \" has failed\", \"error\");\n }\n else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {\n isError = true;\n log(method + \" request for \" + id + \" has failed - response code \" + xhr.status, \"error\");\n }\n\n options.onComplete(id, xhr, isError);\n }\n\n function getParams(id) {\n var onDemandParams = requestData[id].additionalParams,\n mandatedParams = options.mandatedParams,\n params;\n\n if (options.paramsStore.get) {\n params = options.paramsStore.get(id);\n }\n\n if (onDemandParams) {\n qq.each(onDemandParams, function(name, val) {\n params = params || {};\n params[name] = val;\n });\n }\n\n if (mandatedParams) {\n qq.each(mandatedParams, function(name, val) {\n params = params || {};\n params[name] = val;\n });\n }\n\n return params;\n }\n\n function sendRequest(id, optXhr) {\n var xhr = getXhrOrXdr(id, optXhr),\n method = options.method,\n params = getParams(id),\n payload = requestData[id].payload,\n url;\n\n options.onSend(id);\n\n url = createUrl(id, params, requestData[id].additionalQueryParams);\n\n // XDR and XHR status detection APIs differ a bit.\n if (isXdr(xhr)) {\n xhr.onload = getXdrLoadHandler(id);\n xhr.onerror = getXdrErrorHandler(id);\n }\n else {\n xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);\n }\n\n registerForUploadProgress(id);\n\n // The last parameter is assumed to be ignored if we are actually using `XDomainRequest`.\n xhr.open(method, url, true);\n\n // Instruct the transport to send cookies along with the CORS request,\n // unless we are using `XDomainRequest`, which is not capable of this.\n if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {\n xhr.withCredentials = true;\n }\n\n setHeaders(id);\n\n log(\"Sending \" + method + \" request for \" + id);\n\n if (payload) {\n xhr.send(payload);\n }\n else if (shouldParamsBeInQueryString || !params) {\n xhr.send();\n }\n else if (params && options.contentType && options.contentType.toLowerCase().indexOf(\"application/x-www-form-urlencoded\") >= 0) {\n xhr.send(qq.obj2url(params, \"\"));\n }\n else if (params && options.contentType && options.contentType.toLowerCase().indexOf(\"application/json\") >= 0) {\n xhr.send(JSON.stringify(params));\n }\n else {\n xhr.send(params);\n }\n\n return xhr;\n }\n\n function createUrl(id, params, additionalQueryParams) {\n var endpoint = options.endpointStore.get(id),\n addToPath = requestData[id].addToPath;\n\n /*jshint -W116,-W041 */\n if (addToPath != undefined) {\n endpoint += \"/\" + addToPath;\n }\n\n if (shouldParamsBeInQueryString && params) {\n endpoint = qq.obj2url(params, endpoint);\n }\n\n if (additionalQueryParams) {\n endpoint = qq.obj2url(additionalQueryParams, endpoint);\n }\n\n return endpoint;\n }\n\n // Invoked by the UA to indicate a number of possible states that describe\n // a live `XMLHttpRequest` transport.\n function getXhrReadyStateChangeHandler(id) {\n return function() {\n if (getXhrOrXdr(id).readyState === 4) {\n onComplete(id);\n }\n };\n }\n\n function registerForUploadProgress(id) {\n var onProgress = options.onProgress;\n\n if (onProgress) {\n getXhrOrXdr(id).upload.onprogress = function(e) {\n if (e.lengthComputable) {\n onProgress(id, e.loaded, e.total);\n }\n };\n }\n }\n\n // This will be called by IE to indicate **success** for an associated\n // `XDomainRequest` transported request.\n function getXdrLoadHandler(id) {\n return function() {\n onComplete(id);\n };\n }\n\n // This will be called by IE to indicate **failure** for an associated\n // `XDomainRequest` transported request.\n function getXdrErrorHandler(id) {\n return function() {\n onComplete(id, true);\n };\n }\n\n function setHeaders(id) {\n var xhr = getXhrOrXdr(id),\n customHeaders = options.customHeaders,\n onDemandHeaders = requestData[id].additionalHeaders || {},\n method = options.method,\n allHeaders = {};\n\n // If XDomainRequest is being used, we can't set headers, so just ignore this block.\n if (!isXdr(xhr)) {\n options.acceptHeader && xhr.setRequestHeader(\"Accept\", options.acceptHeader);\n\n // Only attempt to add X-Requested-With & Cache-Control if permitted\n if (options.allowXRequestedWithAndCacheControl) {\n // Do not add X-Requested-With & Cache-Control if this is a cross-origin request\n // OR the cross-origin request contains a non-simple method or header.\n // This is done to ensure a preflight is not triggered exclusively based on the\n // addition of these 2 non-simple headers.\n if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\n xhr.setRequestHeader(\"Cache-Control\", \"no-cache\");\n }\n }\n\n if (options.contentType && (method === \"POST\" || method === \"PUT\")) {\n xhr.setRequestHeader(\"Content-Type\", options.contentType);\n }\n\n qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);\n qq.extend(allHeaders, onDemandHeaders);\n\n qq.each(allHeaders, function(name, val) {\n xhr.setRequestHeader(name, val);\n });\n }\n }\n\n function isResponseSuccessful(responseCode) {\n return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;\n }\n\n function prepareToSend(id, optXhr, addToPath, additionalParams, additionalQueryParams, additionalHeaders, payload) {\n requestData[id] = {\n addToPath: addToPath,\n additionalParams: additionalParams,\n additionalQueryParams: additionalQueryParams,\n additionalHeaders: additionalHeaders,\n payload: payload\n };\n\n var len = queue.push(id);\n\n // if too many active connections, wait...\n if (len <= options.maxConnections) {\n return sendRequest(id, optXhr);\n }\n }\n\n shouldParamsBeInQueryString = options.method === \"GET\" || options.method === \"DELETE\";\n\n qq.extend(this, {\n // Start the process of sending the request. The ID refers to the file associated with the request.\n initTransport: function(id) {\n var path, params, headers, payload, cacheBuster, additionalQueryParams;\n\n return {\n // Optionally specify the end of the endpoint path for the request.\n withPath: function(appendToPath) {\n path = appendToPath;\n return this;\n },\n\n // Optionally specify additional parameters to send along with the request.\n // These will be added to the query string for GET/DELETE requests or the payload\n // for POST/PUT requests. The Content-Type of the request will be used to determine\n // how these parameters should be formatted as well.\n withParams: function(additionalParams) {\n params = additionalParams;\n return this;\n },\n\n withQueryParams: function(_additionalQueryParams_) {\n additionalQueryParams = _additionalQueryParams_;\n return this;\n },\n\n // Optionally specify additional headers to send along with the request.\n withHeaders: function(additionalHeaders) {\n headers = additionalHeaders;\n return this;\n },\n\n // Optionally specify a payload/body for the request.\n withPayload: function(thePayload) {\n payload = thePayload;\n return this;\n },\n\n // Appends a cache buster (timestamp) to the request URL as a query parameter (only if GET or DELETE)\n withCacheBuster: function() {\n cacheBuster = true;\n return this;\n },\n\n // Send the constructed request.\n send: function(optXhr) {\n if (cacheBuster && qq.indexOf([\"GET\", \"DELETE\"], options.method) >= 0) {\n params.qqtimestamp = new Date().getTime();\n }\n\n return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload);\n }\n };\n },\n\n canceled: function(id) {\n dequeue(id);\n }\n });\n};\n","/* globals qq */\n/**\n * Common upload handler functions.\n *\n * @constructor\n */\nqq.UploadHandler = function(spec) {\n \"use strict\";\n\n var proxy = spec.proxy,\n fileState = {},\n onCancel = proxy.onCancel,\n getName = proxy.getName;\n\n qq.extend(this, {\n add: function(id, fileItem) {\n fileState[id] = fileItem;\n fileState[id].temp = {};\n },\n\n cancel: function(id) {\n var self = this,\n cancelFinalizationEffort = new qq.Promise(),\n onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);\n\n onCancelRetVal.then(function() {\n if (self.isValid(id)) {\n fileState[id].canceled = true;\n self.expunge(id);\n }\n cancelFinalizationEffort.success();\n });\n },\n\n expunge: function(id) {\n delete fileState[id];\n },\n\n getThirdPartyFileId: function(id) {\n return fileState[id].key;\n },\n\n isValid: function(id) {\n return fileState[id] !== undefined;\n },\n\n reset: function() {\n fileState = {};\n },\n\n _getFileState: function(id) {\n return fileState[id];\n },\n\n _setThirdPartyFileId: function(id, thirdPartyFileId) {\n fileState[id].key = thirdPartyFileId;\n },\n\n _wasCanceled: function(id) {\n return !!fileState[id].canceled;\n }\n });\n};\n","/*globals qq*/\n/**\n * Base upload handler module. Controls more specific handlers.\n *\n * @param o Options. Passed along to the specific handler submodule as well.\n * @param namespace [optional] Namespace for the specific handler.\n */\nqq.UploadHandlerController = function(o, namespace) {\n \"use strict\";\n\n var controller = this,\n chunkingPossible = false,\n concurrentChunkingPossible = false,\n chunking, preventRetryResponse, log, handler,\n\n options = {\n paramsStore: {},\n maxConnections: 3, // maximum number of concurrent uploads\n chunking: {\n enabled: false,\n multiple: {\n enabled: false\n }\n },\n log: function(str, level) {},\n onProgress: function(id, fileName, loaded, total) {},\n onComplete: function(id, fileName, response, xhr) {},\n onCancel: function(id, fileName) {},\n onUploadPrep: function(id) {}, // Called if non-trivial operations will be performed before onUpload\n onUpload: function(id, fileName) {},\n onUploadChunk: function(id, fileName, chunkData) {},\n onUploadChunkSuccess: function(id, chunkData, response, xhr) {},\n onAutoRetry: function(id, fileName, response, xhr) {},\n onResume: function(id, fileName, chunkData, customResumeData) {},\n onUuidChanged: function(id, newUuid) {},\n getName: function(id) {},\n setSize: function(id, newSize) {},\n isQueued: function(id) {},\n getIdsInProxyGroup: function(id) {},\n getIdsInBatch: function(id) {},\n isInProgress: function(id) {}\n },\n\n chunked = {\n // Called when each chunk has uploaded successfully\n done: function(id, chunkIdx, response, xhr) {\n var chunkData = handler._getChunkData(id, chunkIdx);\n\n handler._getFileState(id).attemptingResume = false;\n\n delete handler._getFileState(id).temp.chunkProgress[chunkIdx];\n handler._getFileState(id).loaded += chunkData.size;\n\n options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);\n },\n\n // Called when all chunks have been successfully uploaded and we want to ask the handler to perform any\n // logic associated with closing out the file, such as combining the chunks.\n finalize: function(id) {\n var size = options.getSize(id),\n name = options.getName(id);\n\n log(\"All chunks have been uploaded for \" + id + \" - finalizing....\");\n handler.finalizeChunks(id).then(\n function(response, xhr) {\n log(\"Finalize successful for \" + id);\n\n var normaizedResponse = upload.normalizeResponse(response, true);\n\n options.onProgress(id, name, size, size);\n handler._maybeDeletePersistedChunkData(id);\n upload.cleanup(id, normaizedResponse, xhr);\n },\n function(response, xhr) {\n var normalizedResponse = upload.normalizeResponse(response, false);\n\n log(\"Problem finalizing chunks for file ID \" + id + \" - \" + normalizedResponse.error, \"error\");\n\n if (\n normalizedResponse.reset ||\n (xhr && options.chunking.success.resetOnStatus.indexOf(xhr.status) >= 0)\n ) {\n chunked.reset(id);\n }\n\n if (!options.onAutoRetry(id, name, normalizedResponse, xhr)) {\n upload.cleanup(id, normalizedResponse, xhr);\n }\n }\n );\n },\n\n handleFailure: function(chunkIdx, id, response, xhr) {\n var name = options.getName(id);\n\n log(\"Chunked upload request failed for \" + id + \", chunk \" + chunkIdx);\n\n handler.clearCachedChunk(id, chunkIdx);\n\n var responseToReport = upload.normalizeResponse(response, false),\n inProgressIdx;\n\n if (responseToReport.reset) {\n chunked.reset(id);\n }\n else {\n var inProgressChunksArray = handler._getFileState(id).chunking.inProgress;\n\n inProgressIdx = inProgressChunksArray ? qq.indexOf(inProgressChunksArray, chunkIdx) : -1;\n if (inProgressIdx >= 0) {\n handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);\n handler._getFileState(id).chunking.remaining.unshift(chunkIdx);\n }\n }\n\n // We may have aborted all other in-progress chunks for this file due to a failure.\n // If so, ignore the failures associated with those aborts.\n if (!handler._getFileState(id).temp.ignoreFailure) {\n // If this chunk has failed, we want to ignore all other failures of currently in-progress\n // chunks since they will be explicitly aborted\n if (concurrentChunkingPossible) {\n handler._getFileState(id).temp.ignoreFailure = true;\n\n log(qq.format(\"Going to attempt to abort these chunks: {}. These are currently in-progress: {}.\", JSON.stringify(Object.keys(handler._getXhrs(id))), JSON.stringify(handler._getFileState(id).chunking.inProgress)));\n qq.each(handler._getXhrs(id), function(ckid, ckXhr) {\n log(qq.format(\"Attempting to abort file {}.{}. XHR readyState {}. \", id, ckid, ckXhr.readyState));\n ckXhr.abort();\n // Flag the transport, in case we are waiting for some other async operation\n // to complete before attempting to upload the chunk\n ckXhr._cancelled = true;\n });\n\n // We must indicate that all aborted chunks are no longer in progress\n handler.moveInProgressToRemaining(id);\n\n // Free up any connections used by these chunks, but don't allow any\n // other files to take up the connections (until we have exhausted all auto-retries)\n connectionManager.free(id, true);\n }\n\n if (!options.onAutoRetry(id, name, responseToReport, xhr)) {\n // If one chunk fails, abort all of the others to avoid odd race conditions that occur\n // if a chunk succeeds immediately after one fails before we have determined if the upload\n // is a failure or not.\n upload.cleanup(id, responseToReport, xhr);\n }\n }\n },\n\n hasMoreParts: function(id) {\n return !!handler._getFileState(id).chunking.remaining.length;\n },\n\n nextPart: function(id) {\n var nextIdx = handler._getFileState(id).chunking.remaining.shift();\n\n if (nextIdx >= handler._getTotalChunks(id)) {\n nextIdx = null;\n }\n\n return nextIdx;\n },\n\n reset: function(id) {\n log(\"Server or callback has ordered chunking effort to be restarted on next attempt for item ID \" + id, \"error\");\n\n handler._maybeDeletePersistedChunkData(id);\n handler.reevaluateChunking(id);\n handler._getFileState(id).loaded = 0;\n handler._getFileState(id).attemptingResume = false;\n },\n\n sendNext: function(id) {\n var size = options.getSize(id),\n name = options.getName(id),\n chunkIdx = chunked.nextPart(id),\n chunkData = handler._getChunkData(id, chunkIdx),\n fileState = handler._getFileState(id),\n resuming = fileState.attemptingResume,\n inProgressChunks = fileState.chunking.inProgress || [];\n\n if (fileState.loaded == null) {\n fileState.loaded = 0;\n }\n\n // Don't follow-through with the resume attempt if the integrator returns false from onResume\n if (resuming && options.onResume(id, name, chunkData, fileState.customResumeData) === false) {\n chunked.reset(id);\n chunkIdx = chunked.nextPart(id);\n chunkData = handler._getChunkData(id, chunkIdx);\n resuming = false;\n }\n\n // If all chunks have already uploaded successfully, we must be re-attempting the finalize step.\n if (chunkIdx == null && inProgressChunks.length === 0) {\n chunked.finalize(id);\n }\n\n // Send the next chunk\n else {\n inProgressChunks.push(chunkIdx);\n handler._getFileState(id).chunking.inProgress = inProgressChunks;\n\n if (concurrentChunkingPossible) {\n connectionManager.open(id, chunkIdx);\n }\n\n if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {\n chunked.sendNext(id);\n }\n\n if (chunkData.blob.size === 0) {\n log(qq.format(\"Chunk {} for file {} will not be uploaded, zero sized chunk.\", chunkIdx, id), \"error\");\n chunked.handleFailure(chunkIdx, id, \"File is no longer available\", null);\n }\n\n var onUploadChunkPromise = options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));\n\n onUploadChunkPromise.then(\n function(requestOverrides) {\n if (!options.isInProgress(id)) {\n log(qq.format(\"Not sending chunked upload request for item {}.{} - no longer in progress.\", id, chunkIdx));\n }\n else {\n log(qq.format(\"Sending chunked upload request for item {}.{}, bytes {}-{} of {}.\", id, chunkIdx, chunkData.start + 1, chunkData.end, size));\n\n var uploadChunkData = {\n chunkIdx: chunkIdx,\n id: id,\n overrides: requestOverrides,\n resuming: resuming\n };\n\n handler.uploadChunk(uploadChunkData).then(\n // upload chunk success\n function success(response, xhr) {\n log(\"Chunked upload request succeeded for \" + id + \", chunk \" + chunkIdx);\n\n handler.clearCachedChunk(id, chunkIdx);\n\n var inProgressChunks = handler._getFileState(id).chunking.inProgress || [],\n responseToReport = upload.normalizeResponse(response, true),\n inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);\n\n log(qq.format(\"Chunk {} for file {} uploaded successfully.\", chunkIdx, id));\n\n chunked.done(id, chunkIdx, responseToReport, xhr);\n\n if (inProgressChunkIdx >= 0) {\n inProgressChunks.splice(inProgressChunkIdx, 1);\n }\n\n handler._maybePersistChunkedState(id);\n\n if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {\n chunked.finalize(id);\n }\n else if (chunked.hasMoreParts(id)) {\n chunked.sendNext(id);\n }\n else {\n log(qq.format(\"File ID {} has no more chunks to send and these chunk indexes are still marked as in-progress: {}\", id, JSON.stringify(inProgressChunks)));\n }\n },\n\n // upload chunk failure\n function failure(response, xhr) {\n chunked.handleFailure(chunkIdx, id, response, xhr);\n }\n )\n .done(function () {\n handler.clearXhr(id, chunkIdx);\n });\n }\n },\n\n function(error) {\n chunked.handleFailure(chunkIdx, id, error, null);\n }\n );\n }\n }\n },\n\n connectionManager = {\n _open: [],\n _openChunks: {},\n _waiting: [],\n\n available: function() {\n var max = options.maxConnections,\n openChunkEntriesCount = 0,\n openChunksCount = 0;\n\n qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {\n openChunkEntriesCount++;\n openChunksCount += openChunkIndexes.length;\n });\n\n return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);\n },\n\n /**\n * Removes element from queue, starts upload of next\n */\n free: function(id, dontAllowNext) {\n var allowNext = !dontAllowNext,\n waitingIndex = qq.indexOf(connectionManager._waiting, id),\n connectionsIndex = qq.indexOf(connectionManager._open, id),\n nextId;\n\n delete connectionManager._openChunks[id];\n\n if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {\n log(\"Generated blob upload has ended for \" + id + \", disposing generated blob.\");\n delete handler._getFileState(id).file;\n }\n\n // If this file was not consuming a connection, it was just waiting, so remove it from the waiting array\n if (waitingIndex >= 0) {\n connectionManager._waiting.splice(waitingIndex, 1);\n }\n // If this file was consuming a connection, allow the next file to be uploaded\n else if (allowNext && connectionsIndex >= 0) {\n connectionManager._open.splice(connectionsIndex, 1);\n\n nextId = connectionManager._waiting.shift();\n if (nextId >= 0) {\n connectionManager._open.push(nextId);\n upload.start(nextId);\n }\n }\n },\n\n getWaitingOrConnected: function() {\n var waitingOrConnected = [];\n\n // Chunked files may have multiple connections open per chunk (if concurrent chunking is enabled)\n // We need to grab the file ID of any file that has at least one chunk consuming a connection.\n qq.each(connectionManager._openChunks, function(fileId, chunks) {\n if (chunks && chunks.length) {\n waitingOrConnected.push(parseInt(fileId));\n }\n });\n\n // For non-chunked files, only one connection will be consumed per file.\n // This is where we aggregate those file IDs.\n qq.each(connectionManager._open, function(idx, fileId) {\n if (!connectionManager._openChunks[fileId]) {\n waitingOrConnected.push(parseInt(fileId));\n }\n });\n\n // There may be files waiting for a connection.\n waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);\n\n return waitingOrConnected;\n },\n\n isUsingConnection: function(id) {\n return qq.indexOf(connectionManager._open, id) >= 0;\n },\n\n open: function(id, chunkIdx) {\n if (chunkIdx == null) {\n connectionManager._waiting.push(id);\n }\n\n if (connectionManager.available()) {\n if (chunkIdx == null) {\n connectionManager._waiting.pop();\n connectionManager._open.push(id);\n }\n else {\n (function() {\n var openChunksEntry = connectionManager._openChunks[id] || [];\n openChunksEntry.push(chunkIdx);\n connectionManager._openChunks[id] = openChunksEntry;\n }());\n }\n\n return true;\n }\n\n return false;\n },\n\n reset: function() {\n connectionManager._waiting = [];\n connectionManager._open = [];\n }\n },\n\n simple = {\n send: function(id, name) {\n var fileState = handler._getFileState(id);\n\n if (!fileState) {\n log(\"Ignoring send request as this upload may have been cancelled, File ID \" + id, \"warn\");\n return;\n }\n\n fileState.loaded = 0;\n\n log(\"Sending simple upload request for \" + id);\n handler.uploadFile(id).then(\n function(response, optXhr) {\n log(\"Simple upload request succeeded for \" + id);\n\n var responseToReport = upload.normalizeResponse(response, true),\n size = options.getSize(id);\n\n options.onProgress(id, name, size, size);\n upload.maybeNewUuid(id, responseToReport);\n upload.cleanup(id, responseToReport, optXhr);\n },\n\n function(response, optXhr) {\n log(\"Simple upload request failed for \" + id);\n\n var responseToReport = upload.normalizeResponse(response, false);\n\n if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {\n upload.cleanup(id, responseToReport, optXhr);\n }\n }\n );\n }\n },\n\n upload = {\n cancel: function(id) {\n log(\"Cancelling \" + id);\n options.paramsStore.remove(id);\n connectionManager.free(id);\n },\n\n cleanup: function(id, response, optXhr) {\n var name = options.getName(id);\n\n options.onComplete(id, name, response, optXhr);\n\n if (handler._getFileState(id)) {\n handler._clearXhrs && handler._clearXhrs(id);\n }\n\n connectionManager.free(id);\n },\n\n // Returns a qq.BlobProxy, or an actual File/Blob if no proxy is involved, or undefined\n // if none of these are available for the ID\n getProxyOrBlob: function(id) {\n return (handler.getProxy && handler.getProxy(id)) ||\n (handler.getFile && handler.getFile(id));\n },\n\n initHandler: function() {\n var handlerType = namespace ? qq[namespace] : qq.traditional,\n handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? \"Xhr\" : \"Form\";\n\n handler = new handlerType[handlerModuleSubtype + \"UploadHandler\"](\n options,\n {\n getCustomResumeData: options.getCustomResumeData,\n getDataByUuid: options.getDataByUuid,\n getName: options.getName,\n getSize: options.getSize,\n getUuid: options.getUuid,\n log: log,\n onCancel: options.onCancel,\n onProgress: options.onProgress,\n onUuidChanged: options.onUuidChanged,\n onFinalizing: function(id) {\n options.setStatus(id, qq.status.UPLOAD_FINALIZING);\n }\n }\n );\n\n if (handler._removeExpiredChunkingRecords) {\n handler._removeExpiredChunkingRecords();\n }\n },\n\n isDeferredEligibleForUpload: function(id) {\n return options.isQueued(id);\n },\n\n // For Blobs that are part of a group of generated images, along with a reference image,\n // this will ensure the blobs in the group are uploaded in the order they were triggered,\n // even if some async processing must be completed on one or more Blobs first.\n maybeDefer: function(id, blob) {\n // If we don't have a file/blob yet & no file/blob exists for this item, request it,\n // and then submit the upload to the specific handler once the blob is available.\n // ASSUMPTION: This condition will only ever be true if XHR uploading is supported.\n if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {\n\n // Blob creation may take some time, so the caller may want to update the\n // UI to indicate that an operation is in progress, even before the actual\n // upload begins and an onUpload callback is invoked.\n options.onUploadPrep(id);\n\n log(\"Attempting to generate a blob on-demand for \" + id);\n blob.create().then(function(generatedBlob) {\n log(\"Generated an on-demand blob for \" + id);\n\n // Update record associated with this file by providing the generated Blob\n handler.updateBlob(id, generatedBlob);\n\n // Propagate the size for this generated Blob\n options.setSize(id, generatedBlob.size);\n\n // Order handler to recalculate chunking possibility, if applicable\n handler.reevaluateChunking(id);\n\n upload.maybeSendDeferredFiles(id);\n },\n\n // Blob could not be generated. Fail the upload & attempt to prevent retries. Also bubble error message.\n function(errorMessage) {\n var errorResponse = {};\n\n if (errorMessage) {\n errorResponse.error = errorMessage;\n }\n\n log(qq.format(\"Failed to generate blob for ID {}. Error message: {}.\", id, errorMessage), \"error\");\n\n options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);\n upload.maybeSendDeferredFiles(id);\n connectionManager.free(id);\n });\n }\n else {\n return upload.maybeSendDeferredFiles(id);\n }\n\n return false;\n },\n\n // Upload any grouped blobs, in the proper order, that are ready to be uploaded\n maybeSendDeferredFiles: function(id) {\n var idsInGroup = options.getIdsInProxyGroup(id),\n uploadedThisId = false;\n\n if (idsInGroup && idsInGroup.length) {\n log(\"Maybe ready to upload proxy group file \" + id);\n\n qq.each(idsInGroup, function(idx, idInGroup) {\n if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {\n uploadedThisId = idInGroup === id;\n upload.now(idInGroup);\n }\n else if (upload.isDeferredEligibleForUpload(idInGroup)) {\n return false;\n }\n });\n }\n else {\n uploadedThisId = true;\n upload.now(id);\n }\n\n return uploadedThisId;\n },\n\n maybeNewUuid: function(id, response) {\n if (response.newUuid !== undefined) {\n options.onUuidChanged(id, response.newUuid);\n }\n },\n\n // The response coming from handler implementations may be in various formats.\n // Instead of hoping a promise nested 5 levels deep will always return an object\n // as its first param, let's just normalize the response here.\n normalizeResponse: function(originalResponse, successful) {\n var response = originalResponse;\n\n // The passed \"response\" param may not be a response at all.\n // It could be a string, detailing the error, for example.\n if (!qq.isObject(originalResponse)) {\n response = {};\n\n if (qq.isString(originalResponse) && !successful) {\n response.error = originalResponse;\n }\n }\n\n response.success = successful;\n\n return response;\n },\n\n now: function(id) {\n var name = options.getName(id);\n\n if (!controller.isValid(id)) {\n throw new qq.Error(id + \" is not a valid file ID to upload!\");\n }\n\n options.onUpload(id, name).then(\n function(response) {\n if (response && response.pause) {\n options.setStatus(id, qq.status.PAUSED);\n handler.pause(id);\n connectionManager.free(id);\n }\n else {\n if (chunkingPossible && handler._shouldChunkThisFile(id)) {\n chunked.sendNext(id);\n }\n else {\n simple.send(id, name);\n }\n }\n },\n\n function(error) {\n error = error || {};\n\n log(id + \" upload start aborted due to rejected onUpload Promise - details: \" + error, \"error\");\n\n if (!options.onAutoRetry(id, name, error.responseJSON || {})) {\n var response = upload.normalizeResponse(error.responseJSON, false);\n upload.cleanup(id, response);\n }\n }\n );\n },\n\n start: function(id) {\n var blobToUpload = upload.getProxyOrBlob(id);\n\n if (blobToUpload) {\n return upload.maybeDefer(id, blobToUpload);\n }\n else {\n upload.now(id);\n return true;\n }\n }\n };\n\n qq.extend(this, {\n /**\n * Adds file or file input to the queue\n **/\n add: function(id, file) {\n handler.add.apply(this, arguments);\n },\n\n /**\n * Sends the file identified by id\n */\n upload: function(id) {\n if (connectionManager.open(id)) {\n return upload.start(id);\n }\n return false;\n },\n\n retry: function(id) {\n // On retry, if concurrent chunking has been enabled, we may have aborted all other in-progress chunks\n // for a file when encountering a failed chunk upload. We then signaled the controller to ignore\n // all failures associated with these aborts. We are now retrying, so we don't want to ignore\n // any more failures at this point.\n if (concurrentChunkingPossible) {\n handler._getFileState(id).temp.ignoreFailure = false;\n }\n\n // If we are attempting to retry a file that is already consuming a connection, this is likely an auto-retry.\n // Just go ahead and ask the handler to upload again.\n if (connectionManager.isUsingConnection(id)) {\n return upload.start(id);\n }\n\n // If we are attempting to retry a file that is not currently consuming a connection,\n // this is likely a manual retry attempt. We will need to ensure a connection is available\n // before the retry commences.\n else {\n return controller.upload(id);\n }\n },\n\n /**\n * Cancels file upload by id\n */\n cancel: function(id) {\n var cancelRetVal = handler.cancel(id);\n\n if (qq.isGenericPromise(cancelRetVal)) {\n cancelRetVal.then(function() {\n upload.cancel(id);\n });\n }\n else if (cancelRetVal !== false) {\n upload.cancel(id);\n }\n },\n\n /**\n * Cancels all queued or in-progress uploads\n */\n cancelAll: function() {\n var waitingOrConnected = connectionManager.getWaitingOrConnected(),\n i;\n\n // ensure files are cancelled in reverse order which they were added\n // to avoid a flash of time where a queued file begins to upload before it is canceled\n if (waitingOrConnected.length) {\n for (i = waitingOrConnected.length - 1; i >= 0; i--) {\n controller.cancel(waitingOrConnected[i]);\n }\n }\n\n connectionManager.reset();\n },\n\n // Returns a File, Blob, or the Blob/File for the reference/parent file if the targeted blob is a proxy.\n // Undefined if no file record is available.\n getFile: function(id) {\n if (handler.getProxy && handler.getProxy(id)) {\n return handler.getProxy(id).referenceBlob;\n }\n\n return handler.getFile && handler.getFile(id);\n },\n\n // Returns true if the Blob associated with the ID is related to a proxy s\n isProxied: function(id) {\n return !!(handler.getProxy && handler.getProxy(id));\n },\n\n getInput: function(id) {\n if (handler.getInput) {\n return handler.getInput(id);\n }\n },\n\n reset: function() {\n log(\"Resetting upload handler\");\n controller.cancelAll();\n connectionManager.reset();\n handler.reset();\n },\n\n expunge: function(id) {\n if (controller.isValid(id)) {\n return handler.expunge(id);\n }\n },\n\n /**\n * Determine if the file exists.\n */\n isValid: function(id) {\n return handler.isValid(id);\n },\n\n hasResumeRecord: function(id) {\n var key = handler.isValid(id) &&\n handler._getLocalStorageId &&\n handler._getLocalStorageId(id);\n\n if (key) {\n return !!localStorage.getItem(key);\n }\n\n return false;\n },\n\n getResumableFilesData: function() {\n if (handler.getResumableFilesData) {\n return handler.getResumableFilesData();\n }\n return [];\n },\n\n /**\n * This may or may not be implemented, depending on the handler. For handlers where a third-party ID is\n * available (such as the \"key\" for Amazon S3), this will return that value. Otherwise, the return value\n * will be undefined.\n *\n * @param id Internal file ID\n * @returns {*} Some identifier used by a 3rd-party service involved in the upload process\n */\n getThirdPartyFileId: function(id) {\n if (controller.isValid(id)) {\n return handler.getThirdPartyFileId(id);\n }\n },\n\n /**\n * Attempts to pause the associated upload if the specific handler supports this and the file is \"valid\".\n * @param id ID of the upload/file to pause\n * @returns {boolean} true if the upload was paused\n */\n pause: function(id) {\n if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {\n connectionManager.free(id);\n handler.moveInProgressToRemaining(id);\n return true;\n }\n return false;\n },\n\n isAttemptingResume: function(id) {\n return !!handler.isAttemptingResume && handler.isAttemptingResume(id);\n },\n\n // True if the file is eligible for pause/resume.\n isResumable: function(id) {\n return !!handler.isResumable && handler.isResumable(id);\n }\n });\n\n qq.extend(options, o);\n log = options.log;\n chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;\n concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;\n\n preventRetryResponse = (function() {\n var response = {};\n\n response[options.preventRetryParam] = true;\n\n return response;\n }());\n\n upload.initHandler();\n};\n","/*globals qq */\n/*jshint -W117 */\nqq.WindowReceiveMessage = function(o) {\n \"use strict\";\n\n var options = {\n log: function(message, level) {}\n },\n callbackWrapperDetachers = {};\n\n qq.extend(options, o);\n\n qq.extend(this, {\n receiveMessage: function(id, callback) {\n var onMessageCallbackWrapper = function(event) {\n callback(event.data);\n };\n\n if (window.postMessage) {\n callbackWrapperDetachers[id] = qq(window).attach(\"message\", onMessageCallbackWrapper);\n }\n else {\n log(\"iframe message passing not supported in this browser!\", \"error\");\n }\n },\n\n stopReceivingMessages: function(id) {\n if (window.postMessage) {\n var detacher = callbackWrapperDetachers[id];\n if (detacher) {\n detacher();\n }\n }\n }\n });\n};\n","/* globals qq */\n/**\n * Common APIs exposed to creators of upload via form/iframe handlers. This is reused and possibly overridden\n * in some cases by specific form upload handlers.\n *\n * @constructor\n */\nqq.FormUploadHandler = function(spec) {\n \"use strict\";\n\n var options = spec.options,\n handler = this,\n proxy = spec.proxy,\n formHandlerInstanceId = qq.getUniqueId(),\n onloadCallbacks = {},\n detachLoadEvents = {},\n postMessageCallbackTimers = {},\n isCors = options.isCors,\n inputName = options.inputName,\n getUuid = proxy.getUuid,\n log = proxy.log,\n corsMessageReceiver = new qq.WindowReceiveMessage({log: log});\n\n /**\n * Remove any trace of the file from the handler.\n *\n * @param id ID of the associated file\n */\n function expungeFile(id) {\n delete detachLoadEvents[id];\n\n // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe.\n // In that case, terminate the timer waiting for a message from the loaded iframe\n // and stop listening for any more messages coming from this iframe.\n if (isCors) {\n clearTimeout(postMessageCallbackTimers[id]);\n delete postMessageCallbackTimers[id];\n corsMessageReceiver.stopReceivingMessages(id);\n }\n\n var iframe = document.getElementById(handler._getIframeName(id));\n if (iframe) {\n // To cancel request set src to something else. We use src=\"javascript:false;\"\n // because it doesn't trigger ie6 prompt on https\n /* jshint scripturl:true */\n iframe.setAttribute(\"src\", \"javascript:false;\");\n\n qq(iframe).remove();\n }\n }\n\n /**\n * @param iframeName `document`-unique Name of the associated iframe\n * @returns {*} ID of the associated file\n */\n function getFileIdForIframeName(iframeName) {\n return iframeName.split(\"_\")[0];\n }\n\n /**\n * Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe\n * to the current `document`. Note that the iframe is hidden from view.\n *\n * @param name Name of the iframe.\n * @returns {HTMLIFrameElement} The created iframe\n */\n function initIframeForUpload(name) {\n var iframe = qq.toElement(\"<iframe src='javascript:false;' name='\" + name + \"' />\");\n\n iframe.setAttribute(\"id\", name);\n\n iframe.style.display = \"none\";\n document.body.appendChild(iframe);\n\n return iframe;\n }\n\n /**\n * If we are in CORS mode, we must listen for messages (containing the server response) from the associated\n * iframe, since we cannot directly parse the content of the iframe due to cross-origin restrictions.\n *\n * @param iframe Listen for messages on this iframe.\n * @param callback Invoke this callback with the message from the iframe.\n */\n function registerPostMessageCallback(iframe, callback) {\n var iframeName = iframe.id,\n fileId = getFileIdForIframeName(iframeName),\n uuid = getUuid(fileId);\n\n onloadCallbacks[uuid] = callback;\n\n // When the iframe has loaded (after the server responds to an upload request)\n // declare the attempt a failure if we don't receive a valid message shortly after the response comes in.\n detachLoadEvents[fileId] = qq(iframe).attach(\"load\", function() {\n if (handler.getInput(fileId)) {\n log(\"Received iframe load event for CORS upload request (iframe name \" + iframeName + \")\");\n\n postMessageCallbackTimers[iframeName] = setTimeout(function() {\n var errorMessage = \"No valid message received from loaded iframe for iframe name \" + iframeName;\n log(errorMessage, \"error\");\n callback({\n error: errorMessage\n });\n }, 1000);\n }\n });\n\n // Listen for messages coming from this iframe. When a message has been received, cancel the timer\n // that declares the upload a failure if a message is not received within a reasonable amount of time.\n corsMessageReceiver.receiveMessage(iframeName, function(message) {\n log(\"Received the following window message: '\" + message + \"'\");\n var fileId = getFileIdForIframeName(iframeName),\n response = handler._parseJsonResponse(message),\n uuid = response.uuid,\n onloadCallback;\n\n if (uuid && onloadCallbacks[uuid]) {\n log(\"Handling response for iframe name \" + iframeName);\n clearTimeout(postMessageCallbackTimers[iframeName]);\n delete postMessageCallbackTimers[iframeName];\n\n handler._detachLoadEvent(iframeName);\n\n onloadCallback = onloadCallbacks[uuid];\n\n delete onloadCallbacks[uuid];\n corsMessageReceiver.stopReceivingMessages(iframeName);\n onloadCallback(response);\n }\n else if (!uuid) {\n log(\"'\" + message + \"' does not contain a UUID - ignoring.\");\n }\n });\n }\n\n qq.extend(this, new qq.UploadHandler(spec));\n\n qq.override(this, function(super_) {\n return {\n /**\n * Adds File or Blob to the queue\n **/\n add: function(id, fileInput) {\n super_.add(id, {input: fileInput});\n\n fileInput.setAttribute(\"name\", inputName);\n\n // remove file input from DOM\n if (fileInput.parentNode) {\n qq(fileInput).remove();\n }\n },\n\n expunge: function(id) {\n expungeFile(id);\n super_.expunge(id);\n },\n\n isValid: function(id) {\n return super_.isValid(id) &&\n handler._getFileState(id).input !== undefined;\n }\n };\n });\n\n qq.extend(this, {\n getInput: function(id) {\n return handler._getFileState(id).input;\n },\n\n /**\n * This function either delegates to a more specific message handler if CORS is involved,\n * or simply registers a callback when the iframe has been loaded that invokes the passed callback\n * after determining if the content of the iframe is accessible.\n *\n * @param iframe Associated iframe\n * @param callback Callback to invoke after we have determined if the iframe content is accessible.\n */\n _attachLoadEvent: function(iframe, callback) {\n /*jslint eqeq: true*/\n var responseDescriptor;\n\n if (isCors) {\n registerPostMessageCallback(iframe, callback);\n }\n else {\n detachLoadEvents[iframe.id] = qq(iframe).attach(\"load\", function() {\n log(\"Received response for \" + iframe.id);\n\n // when we remove iframe from dom\n // the request stops, but in IE load\n // event fires\n if (!iframe.parentNode) {\n return;\n }\n\n try {\n // fixing Opera 10.53\n if (iframe.contentDocument &&\n iframe.contentDocument.body &&\n iframe.contentDocument.body.innerHTML == \"false\") {\n // In Opera event is fired second time\n // when body.innerHTML changed from false\n // to server response approx. after 1 sec\n // when we upload file with iframe\n return;\n }\n }\n catch (error) {\n //IE may throw an \"access is denied\" error when attempting to access contentDocument on the iframe in some cases\n log(\"Error when attempting to access iframe during handling of upload response (\" + error.message + \")\", \"error\");\n responseDescriptor = {success: false};\n }\n\n callback(responseDescriptor);\n });\n }\n },\n\n /**\n * Creates an iframe with a specific document-unique name.\n *\n * @param id ID of the associated file\n * @returns {HTMLIFrameElement}\n */\n _createIframe: function(id) {\n var iframeName = handler._getIframeName(id);\n\n return initIframeForUpload(iframeName);\n },\n\n /**\n * Called when we are no longer interested in being notified when an iframe has loaded.\n *\n * @param id Associated file ID\n */\n _detachLoadEvent: function(id) {\n if (detachLoadEvents[id] !== undefined) {\n detachLoadEvents[id]();\n delete detachLoadEvents[id];\n }\n },\n\n /**\n * @param fileId ID of the associated file\n * @returns {string} The `document`-unique name of the iframe\n */\n _getIframeName: function(fileId) {\n return fileId + \"_\" + formHandlerInstanceId;\n },\n\n /**\n * Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted.\n * The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Note\n * that the form is hidden from view.\n *\n * @param spec An object containing various properties to be used when constructing the form. Required properties are\n * currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`.\n * @returns {HTMLFormElement} The created form\n */\n _initFormForUpload: function(spec) {\n var method = spec.method,\n endpoint = spec.endpoint,\n params = spec.params,\n paramsInBody = spec.paramsInBody,\n targetName = spec.targetName,\n form = qq.toElement(\"<form method='\" + method + \"' enctype='multipart/form-data'></form>\"),\n url = endpoint;\n\n if (paramsInBody) {\n qq.obj2Inputs(params, form);\n }\n else {\n url = qq.obj2url(params, endpoint);\n }\n\n form.setAttribute(\"action\", url);\n form.setAttribute(\"target\", targetName);\n form.style.display = \"none\";\n document.body.appendChild(form);\n\n return form;\n },\n\n /**\n * @param innerHtmlOrMessage JSON message\n * @returns {*} The parsed response, or an empty object if the response could not be parsed\n */\n _parseJsonResponse: function(innerHtmlOrMessage) {\n var response = {};\n\n try {\n response = qq.parseJson(innerHtmlOrMessage);\n }\n catch (error) {\n log(\"Error when attempting to parse iframe upload response (\" + error.message + \")\", \"error\");\n }\n\n return response;\n }\n });\n};\n","/* globals qq */\n/**\n * Common API exposed to creators of XHR handlers. This is reused and possibly overriding in some cases by specific\n * XHR upload handlers.\n *\n * @constructor\n */\nqq.XhrUploadHandler = function(spec) {\n \"use strict\";\n\n var handler = this,\n namespace = spec.options.namespace,\n proxy = spec.proxy,\n chunking = spec.options.chunking,\n getChunkSize = function(id) {\n var fileState = handler._getFileState(id);\n\n if (fileState.chunkSize) {\n return fileState.chunkSize;\n }\n\n else {\n var chunkSize = chunking.partSize;\n\n if (qq.isFunction(chunkSize)) {\n chunkSize = chunkSize(id, getSize(id));\n }\n\n fileState.chunkSize = chunkSize;\n return chunkSize;\n }\n },\n resume = spec.options.resume,\n chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking,\n resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume,\n getName = proxy.getName,\n getSize = proxy.getSize,\n getUuid = proxy.getUuid,\n getEndpoint = proxy.getEndpoint,\n getDataByUuid = proxy.getDataByUuid,\n onUuidChanged = proxy.onUuidChanged,\n onProgress = proxy.onProgress,\n log = proxy.log,\n getCustomResumeData = proxy.getCustomResumeData;\n\n function abort(id) {\n qq.each(handler._getXhrs(id), function(xhrId, xhr) {\n var ajaxRequester = handler._getAjaxRequester(id, xhrId);\n\n xhr.onreadystatechange = null;\n xhr.upload.onprogress = null;\n xhr.abort();\n ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);\n });\n }\n\n qq.extend(this, new qq.UploadHandler(spec));\n\n qq.override(this, function(super_) {\n return {\n /**\n * Adds File or Blob to the queue\n **/\n add: function(id, blobOrProxy) {\n if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {\n super_.add(id, {file: blobOrProxy});\n }\n else if (blobOrProxy instanceof qq.BlobProxy) {\n super_.add(id, {proxy: blobOrProxy});\n }\n else {\n throw new Error(\"Passed obj is not a File, Blob, or proxy\");\n }\n\n handler._initTempState(id);\n resumeEnabled && handler._maybePrepareForResume(id);\n },\n\n expunge: function(id) {\n abort(id);\n handler._maybeDeletePersistedChunkData(id);\n handler._clearXhrs(id);\n super_.expunge(id);\n }\n };\n });\n\n qq.extend(this, {\n // Clear the cached chunk `Blob` after we are done with it, just in case the `Blob` bytes are stored in memory.\n clearCachedChunk: function(id, chunkIdx) {\n var fileState = handler._getFileState(id);\n\n if (fileState) {\n delete fileState.temp.cachedChunks[chunkIdx];\n }\n },\n\n clearXhr: function(id, chunkIdx) {\n var tempState = handler._getFileState(id).temp;\n\n if (tempState.xhrs) {\n delete tempState.xhrs[chunkIdx];\n }\n if (tempState.ajaxRequesters) {\n delete tempState.ajaxRequesters[chunkIdx];\n }\n },\n\n // Called when all chunks have been successfully uploaded. Expected promissory return type.\n // This defines the default behavior if nothing further is required when all chunks have been uploaded.\n finalizeChunks: function(id, responseParser) {\n var lastChunkIdx = handler._getTotalChunks(id) - 1,\n xhr = handler._getXhr(id, lastChunkIdx);\n\n if (responseParser) {\n return new qq.Promise().success(responseParser(xhr), xhr);\n }\n\n return new qq.Promise().success({}, xhr);\n },\n\n getFile: function(id) {\n return handler.isValid(id) && handler._getFileState(id).file;\n },\n\n getProxy: function(id) {\n return handler.isValid(id) && handler._getFileState(id).proxy;\n },\n\n /**\n * @returns {Array} Array of objects containing properties useful to integrators\n * when it is important to determine which files are potentially resumable.\n */\n getResumableFilesData: function() {\n var resumableFilesData = [];\n\n handler._iterateResumeRecords(function(key, uploadData) {\n handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);\n\n var data = {\n name: uploadData.name,\n remaining: uploadData.chunking.remaining,\n size: uploadData.size,\n uuid: uploadData.uuid\n };\n\n if (uploadData.key) {\n data.key = uploadData.key;\n }\n\n if (uploadData.customResumeData) {\n data.customResumeData = uploadData.customResumeData;\n }\n\n resumableFilesData.push(data);\n });\n\n return resumableFilesData;\n },\n\n isAttemptingResume: function(id) {\n return handler._getFileState(id).attemptingResume;\n },\n\n isResumable: function(id) {\n return !!chunking && handler.isValid(id) &&\n !handler._getFileState(id).notResumable;\n },\n\n moveInProgressToRemaining: function(id, optInProgress, optRemaining) {\n var fileState = handler._getFileState(id) || {},\n chunkingState = fileState.chunking || {},\n inProgress = optInProgress || chunkingState.inProgress,\n remaining = optRemaining || chunkingState.remaining;\n\n if (inProgress) {\n log(qq.format(\"Moving these chunks from in-progress {}, to remaining.\", JSON.stringify(inProgress)));\n inProgress.reverse();\n qq.each(inProgress, function(idx, chunkIdx) {\n remaining.unshift(chunkIdx);\n });\n inProgress.length = 0;\n }\n },\n\n pause: function(id) {\n if (handler.isValid(id)) {\n log(qq.format(\"Aborting XHR upload for {} '{}' due to pause instruction.\", id, getName(id)));\n handler._getFileState(id).paused = true;\n abort(id);\n return true;\n }\n },\n\n reevaluateChunking: function(id) {\n if (chunking && handler.isValid(id)) {\n var state = handler._getFileState(id),\n totalChunks,\n i;\n\n delete state.chunking;\n\n state.chunking = {};\n totalChunks = handler._getTotalChunks(id);\n if (totalChunks > 1 || chunking.mandatory) {\n state.chunking.enabled = true;\n state.chunking.parts = totalChunks;\n state.chunking.remaining = [];\n\n for (i = 0; i < totalChunks; i++) {\n state.chunking.remaining.push(i);\n }\n\n handler._initTempState(id);\n }\n else {\n state.chunking.enabled = false;\n }\n }\n },\n\n updateBlob: function(id, newBlob) {\n if (handler.isValid(id)) {\n handler._getFileState(id).file = newBlob;\n }\n },\n\n _clearXhrs: function(id) {\n var tempState = handler._getFileState(id).temp;\n\n qq.each(tempState.ajaxRequesters, function(chunkId) {\n delete tempState.ajaxRequesters[chunkId];\n });\n\n qq.each(tempState.xhrs, function(chunkId) {\n delete tempState.xhrs[chunkId];\n });\n },\n\n /**\n * Creates an XHR instance for this file and stores it in the fileState.\n *\n * @param id File ID\n * @param optChunkIdx The chunk index associated with this XHR, if applicable\n * @returns {XMLHttpRequest}\n */\n _createXhr: function(id, optChunkIdx) {\n return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());\n },\n\n _getAjaxRequester: function(id, optChunkIdx) {\n var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;\n return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];\n },\n\n _getChunkData: function(id, chunkIndex) {\n var chunkSize = getChunkSize(id),\n fileSize = getSize(id),\n fileOrBlob = handler.getFile(id),\n startBytes = chunkSize * chunkIndex,\n endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize,\n totalChunks = handler._getTotalChunks(id),\n cachedChunks = this._getFileState(id).temp.cachedChunks,\n\n // To work around a Webkit GC bug, we must keep each chunk `Blob` in scope until we are done with it.\n // See https://github.com/FineUploader/fine-uploader/issues/937#issuecomment-41418760\n blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);\n\n cachedChunks[chunkIndex] = blob;\n\n return {\n part: chunkIndex,\n start: startBytes,\n end: endBytes,\n count: totalChunks,\n blob: blob,\n size: endBytes - startBytes\n };\n },\n\n _getChunkDataForCallback: function(chunkData) {\n return {\n partIndex: chunkData.part,\n startByte: chunkData.start + 1,\n endByte: chunkData.end,\n totalParts: chunkData.count\n };\n },\n\n /**\n * @param id File ID\n * @returns {string} Identifier for this item that may appear in the browser's local storage\n */\n _getLocalStorageId: function(id) {\n var formatVersion = \"5.0\",\n name = getName(id),\n size = getSize(id),\n chunkSize = getChunkSize(id),\n endpoint = getEndpoint(id),\n customKeys = resume.customKeys(id),\n localStorageId = qq.format(\"qq{}resume{}-{}-{}-{}-{}\", namespace, formatVersion, name, size, chunkSize, endpoint);\n\n customKeys.forEach(function(key) {\n localStorageId += \"-\" + key;\n });\n\n return localStorageId;\n },\n\n _getMimeType: function(id) {\n return handler.getFile(id).type;\n },\n\n _getPersistableData: function(id) {\n return handler._getFileState(id).chunking;\n },\n\n /**\n * @param id ID of the associated file\n * @returns {number} Number of parts this file can be divided into, or undefined if chunking is not supported in this UA\n */\n _getTotalChunks: function(id) {\n if (chunking) {\n var fileSize = getSize(id),\n chunkSize = getChunkSize(id);\n\n return Math.ceil(fileSize / chunkSize);\n }\n },\n\n _getXhr: function(id, optChunkIdx) {\n var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;\n return handler._getFileState(id).temp.xhrs[chunkIdx];\n },\n\n _getXhrs: function(id) {\n return handler._getFileState(id).temp.xhrs;\n },\n\n // Iterates through all XHR handler-created resume records (in local storage),\n // invoking the passed callback and passing in the key and value of each local storage record.\n _iterateResumeRecords: function(callback) {\n if (resumeEnabled) {\n qq.each(localStorage, function(key, item) {\n if (key.indexOf(qq.format(\"qq{}resume\", namespace)) === 0) {\n var uploadData = JSON.parse(item);\n callback(key, uploadData);\n }\n });\n }\n },\n\n _initTempState: function(id) {\n handler._getFileState(id).temp = {\n ajaxRequesters: {},\n chunkProgress: {},\n xhrs: {},\n cachedChunks: {}\n };\n },\n\n _markNotResumable: function(id) {\n handler._getFileState(id).notResumable = true;\n },\n\n // Removes a chunked upload record from local storage, if possible.\n // Returns true if the item was removed, false otherwise.\n _maybeDeletePersistedChunkData: function(id) {\n var localStorageId;\n\n if (resumeEnabled && handler.isResumable(id)) {\n localStorageId = handler._getLocalStorageId(id);\n\n if (localStorageId && localStorage.getItem(localStorageId)) {\n localStorage.removeItem(localStorageId);\n return true;\n }\n }\n\n return false;\n },\n\n // If this is a resumable upload, grab the relevant data from storage and items in memory that track this upload\n // so we can pick up from where we left off.\n _maybePrepareForResume: function(id) {\n var state = handler._getFileState(id),\n localStorageId, persistedData;\n\n // Resume is enabled and possible and this is the first time we've tried to upload this file in this session,\n // so prepare for a resume attempt.\n if (resumeEnabled && state.key === undefined) {\n localStorageId = handler._getLocalStorageId(id);\n persistedData = localStorage.getItem(localStorageId);\n\n // If we found this item in local storage, maybe we should resume it.\n if (persistedData) {\n persistedData = JSON.parse(persistedData);\n\n // If we found a resume record but we have already handled this file in this session,\n // don't try to resume it & ensure we don't persist future check data\n if (getDataByUuid(persistedData.uuid)) {\n handler._markNotResumable(id);\n }\n else {\n log(qq.format(\"Identified file with ID {} and name of {} as resumable.\", id, getName(id)));\n\n onUuidChanged(id, persistedData.uuid);\n\n state.key = persistedData.key;\n state.chunking = persistedData.chunking;\n state.loaded = persistedData.loaded;\n state.customResumeData = persistedData.customResumeData;\n state.attemptingResume = true;\n\n handler.moveInProgressToRemaining(id);\n }\n }\n }\n },\n\n // Persist any data needed to resume this upload in a new session.\n _maybePersistChunkedState: function(id) {\n var state = handler._getFileState(id),\n localStorageId, persistedData;\n\n // If local storage isn't supported by the browser, or if resume isn't enabled or possible, give up\n if (resumeEnabled && handler.isResumable(id)) {\n var customResumeData = getCustomResumeData(id);\n\n localStorageId = handler._getLocalStorageId(id);\n\n persistedData = {\n name: getName(id),\n size: getSize(id),\n uuid: getUuid(id),\n key: state.key,\n chunking: state.chunking,\n loaded: state.loaded,\n lastUpdated: Date.now(),\n };\n\n if (customResumeData) {\n persistedData.customResumeData = customResumeData;\n }\n\n try {\n localStorage.setItem(localStorageId, JSON.stringify(persistedData));\n }\n catch (error) {\n log(qq.format(\"Unable to save resume data for '{}' due to error: '{}'.\", id, error.toString()), \"warn\");\n }\n }\n },\n\n _registerProgressHandler: function(id, chunkIdx, chunkSize) {\n var xhr = handler._getXhr(id, chunkIdx),\n name = getName(id),\n progressCalculator = {\n simple: function(loaded, total) {\n var fileSize = getSize(id);\n\n if (loaded === total) {\n onProgress(id, name, fileSize, fileSize);\n }\n else {\n onProgress(id, name, (loaded >= fileSize ? fileSize - 1 : loaded), fileSize);\n }\n },\n\n chunked: function(loaded, total) {\n var chunkProgress = handler._getFileState(id).temp.chunkProgress,\n totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded,\n loadedForRequest = loaded,\n totalForRequest = total,\n totalFileSize = getSize(id),\n estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize),\n totalLoadedForFile = totalSuccessfullyLoadedForFile;\n\n chunkProgress[chunkIdx] = estActualChunkLoaded;\n\n qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {\n totalLoadedForFile += chunkLoaded;\n });\n\n onProgress(id, name, totalLoadedForFile, totalFileSize);\n }\n };\n\n xhr.upload.onprogress = function(e) {\n if (e.lengthComputable) {\n /* jshint eqnull: true */\n var type = chunkSize == null ? \"simple\" : \"chunked\";\n progressCalculator[type](e.loaded, e.total);\n }\n };\n },\n\n /**\n * Registers an XHR transport instance created elsewhere.\n *\n * @param id ID of the associated file\n * @param optChunkIdx The chunk index associated with this XHR, if applicable\n * @param xhr XMLHttpRequest object instance\n * @param optAjaxRequester `qq.AjaxRequester` associated with this request, if applicable.\n * @returns {XMLHttpRequest}\n */\n _registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {\n var xhrsId = optChunkIdx == null ? -1 : optChunkIdx,\n tempState = handler._getFileState(id).temp;\n\n tempState.xhrs = tempState.xhrs || {};\n tempState.ajaxRequesters = tempState.ajaxRequesters || {};\n\n tempState.xhrs[xhrsId] = xhr;\n\n if (optAjaxRequester) {\n tempState.ajaxRequesters[xhrsId] = optAjaxRequester;\n }\n\n return xhr;\n },\n\n // Deletes any local storage records that are \"expired\".\n _removeExpiredChunkingRecords: function() {\n var expirationDays = resume.recordsExpireIn;\n\n handler._iterateResumeRecords(function(key, uploadData) {\n var expirationDate = new Date(uploadData.lastUpdated);\n\n // transform updated date into expiration date\n expirationDate.setDate(expirationDate.getDate() + expirationDays);\n\n if (expirationDate.getTime() <= Date.now()) {\n log(\"Removing expired resume record with key \" + key);\n localStorage.removeItem(key);\n }\n });\n },\n\n /**\n * Determine if the associated file should be chunked.\n *\n * @param id ID of the associated file\n * @returns {*} true if chunking is enabled, possible, and the file can be split into more than 1 part\n */\n _shouldChunkThisFile: function(id) {\n var state = handler._getFileState(id);\n\n // file may no longer be available if it was recently cancelled\n if (state) {\n if (!state.chunking) {\n handler.reevaluateChunking(id);\n }\n\n return state.chunking.enabled;\n }\n }\n });\n};\n","/*globals qq, XMLHttpRequest*/\nqq.DeleteFileAjaxRequester = function(o) {\n \"use strict\";\n\n var requester,\n options = {\n method: \"DELETE\",\n uuidParamName: \"qquuid\",\n endpointStore: {},\n maxConnections: 3,\n customHeaders: function(id) {return {};},\n paramsStore: {},\n cors: {\n expected: false,\n sendCredentials: false\n },\n log: function(str, level) {},\n onDelete: function(id) {},\n onDeleteComplete: function(id, xhrOrXdr, isError) {}\n };\n\n qq.extend(options, o);\n\n function getMandatedParams() {\n if (options.method.toUpperCase() === \"POST\") {\n return {\n _method: \"DELETE\"\n };\n }\n\n return {};\n }\n\n requester = qq.extend(this, new qq.AjaxRequester({\n acceptHeader: \"application/json\",\n validMethods: [\"POST\", \"DELETE\"],\n method: options.method,\n endpointStore: options.endpointStore,\n paramsStore: options.paramsStore,\n mandatedParams: getMandatedParams(),\n maxConnections: options.maxConnections,\n customHeaders: function(id) {\n return options.customHeaders.get(id);\n },\n log: options.log,\n onSend: options.onDelete,\n onComplete: options.onDeleteComplete,\n cors: options.cors\n }));\n\n qq.extend(this, {\n sendDelete: function(id, uuid, additionalMandatedParams) {\n var additionalOptions = additionalMandatedParams || {};\n\n options.log(\"Submitting delete file request for \" + id);\n\n if (options.method === \"DELETE\") {\n requester.initTransport(id)\n .withPath(uuid)\n .withParams(additionalOptions)\n .send();\n }\n else {\n additionalOptions[options.uuidParamName] = uuid;\n requester.initTransport(id)\n .withParams(additionalOptions)\n .send();\n }\n }\n });\n};\n","/*global qq, define */\n/*jshint strict:false,bitwise:false,nonew:false,asi:true,-W064,-W116,-W089 */\n/**\n * Mega pixel image rendering library for iOS6+\n *\n * Fixes iOS6+'s image file rendering issue for large size image (over mega-pixel),\n * which causes unexpected subsampling when drawing it in canvas.\n * By using this library, you can safely render the image with proper stretching.\n *\n * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>\n * Released under the MIT license\n *\n * Heavily modified by Widen for Fine Uploader\n */\n(function() {\n\n /**\n * Detect subsampling in loaded image.\n * In iOS, larger images than 2M pixels may be subsampled in rendering.\n */\n function detectSubsampling(img) {\n var iw = img.naturalWidth,\n ih = img.naturalHeight,\n canvas = document.createElement(\"canvas\"),\n ctx;\n\n if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image\n canvas.width = canvas.height = 1;\n ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, -iw + 1, 0);\n // subsampled image becomes half smaller in rendering size.\n // check alpha channel value to confirm image is covering edge pixel or not.\n // if alpha value is 0 image is not covering, hence subsampled.\n return ctx.getImageData(0, 0, 1, 1).data[3] === 0;\n } else {\n return false;\n }\n }\n\n /**\n * Detecting vertical squash in loaded image.\n * Fixes a bug which squash image vertically while drawing into canvas for some images.\n */\n function detectVerticalSquash(img, iw, ih) {\n var canvas = document.createElement(\"canvas\"),\n sy = 0,\n ey = ih,\n py = ih,\n ctx, data, alpha, ratio;\n\n canvas.width = 1;\n canvas.height = ih;\n ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0);\n data = ctx.getImageData(0, 0, 1, ih).data;\n\n // search image edge pixel position in case it is squashed vertically.\n while (py > sy) {\n alpha = data[(py - 1) * 4 + 3];\n if (alpha === 0) {\n ey = py;\n } else {\n sy = py;\n }\n py = (ey + sy) >> 1;\n }\n\n ratio = (py / ih);\n return (ratio === 0) ? 1 : ratio;\n }\n\n /**\n * Rendering image element (with resizing) and get its data URL\n */\n function renderImageToDataURL(img, blob, options, doSquash) {\n var canvas = document.createElement(\"canvas\"),\n mime = options.mime || \"image/jpeg\",\n promise = new qq.Promise();\n\n renderImageToCanvas(img, blob, canvas, options, doSquash)\n .then(function() {\n promise.success(\n canvas.toDataURL(mime, options.quality || 0.8)\n );\n });\n\n return promise;\n }\n\n function maybeCalculateDownsampledDimensions(spec) {\n var maxPixels = 5241000; //iOS specific value\n\n if (!qq.ios()) {\n throw new qq.Error(\"Downsampled dimensions can only be reliably calculated for iOS!\");\n }\n\n if (spec.origHeight * spec.origWidth > maxPixels) {\n return {\n newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),\n newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))\n };\n }\n }\n\n /**\n * Rendering image element (with resizing) into the canvas element\n */\n function renderImageToCanvas(img, blob, canvas, options, doSquash) {\n var iw = img.naturalWidth,\n ih = img.naturalHeight,\n width = options.width,\n height = options.height,\n ctx = canvas.getContext(\"2d\"),\n promise = new qq.Promise(),\n modifiedDimensions;\n\n ctx.save();\n\n if (options.resize) {\n return renderImageToCanvasWithCustomResizer({\n blob: blob,\n canvas: canvas,\n image: img,\n imageHeight: ih,\n imageWidth: iw,\n orientation: options.orientation,\n resize: options.resize,\n targetHeight: height,\n targetWidth: width\n });\n }\n\n if (!qq.supportedFeatures.unlimitedScaledImageSize) {\n modifiedDimensions = maybeCalculateDownsampledDimensions({\n origWidth: width,\n origHeight: height\n });\n\n if (modifiedDimensions) {\n qq.log(qq.format(\"Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h\",\n width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight),\n \"warn\");\n\n width = modifiedDimensions.newWidth;\n height = modifiedDimensions.newHeight;\n }\n }\n\n transformCoordinate(canvas, width, height, options.orientation);\n\n // Fine Uploader specific: Save some CPU cycles if not using iOS\n // Assumption: This logic is only needed to overcome iOS image sampling issues\n if (qq.ios()) {\n (function() {\n if (detectSubsampling(img)) {\n iw /= 2;\n ih /= 2;\n }\n\n var d = 1024, // size of tiling canvas\n tmpCanvas = document.createElement(\"canvas\"),\n vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1,\n dw = Math.ceil(d * width / iw),\n dh = Math.ceil(d * height / ih / vertSquashRatio),\n sy = 0,\n dy = 0,\n tmpCtx, sx, dx;\n\n tmpCanvas.width = tmpCanvas.height = d;\n tmpCtx = tmpCanvas.getContext(\"2d\");\n\n while (sy < ih) {\n sx = 0;\n dx = 0;\n while (sx < iw) {\n tmpCtx.clearRect(0, 0, d, d);\n tmpCtx.drawImage(img, -sx, -sy);\n ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);\n sx += d;\n dx += dw;\n }\n sy += d;\n dy += dh;\n }\n ctx.restore();\n tmpCanvas = tmpCtx = null;\n }());\n }\n else {\n ctx.drawImage(img, 0, 0, width, height);\n }\n\n canvas.qqImageRendered && canvas.qqImageRendered();\n promise.success();\n\n return promise;\n }\n\n function renderImageToCanvasWithCustomResizer(resizeInfo) {\n var blob = resizeInfo.blob,\n image = resizeInfo.image,\n imageHeight = resizeInfo.imageHeight,\n imageWidth = resizeInfo.imageWidth,\n orientation = resizeInfo.orientation,\n promise = new qq.Promise(),\n resize = resizeInfo.resize,\n sourceCanvas = document.createElement(\"canvas\"),\n sourceCanvasContext = sourceCanvas.getContext(\"2d\"),\n targetCanvas = resizeInfo.canvas,\n targetHeight = resizeInfo.targetHeight,\n targetWidth = resizeInfo.targetWidth;\n\n transformCoordinate(sourceCanvas, imageWidth, imageHeight, orientation);\n\n targetCanvas.height = targetHeight;\n targetCanvas.width = targetWidth;\n\n sourceCanvasContext.drawImage(image, 0, 0);\n\n resize({\n blob: blob,\n height: targetHeight,\n image: image,\n sourceCanvas: sourceCanvas,\n targetCanvas: targetCanvas,\n width: targetWidth\n })\n .then(\n function success() {\n targetCanvas.qqImageRendered && targetCanvas.qqImageRendered();\n promise.success();\n },\n promise.failure\n );\n\n return promise;\n }\n\n /**\n * Transform canvas coordination according to specified frame size and orientation\n * Orientation value is from EXIF tag\n */\n function transformCoordinate(canvas, width, height, orientation) {\n switch (orientation) {\n case 5:\n case 6:\n case 7:\n case 8:\n canvas.width = height;\n canvas.height = width;\n break;\n default:\n canvas.width = width;\n canvas.height = height;\n }\n var ctx = canvas.getContext(\"2d\");\n switch (orientation) {\n case 2:\n // horizontal flip\n ctx.translate(width, 0);\n ctx.scale(-1, 1);\n break;\n case 3:\n // 180 rotate left\n ctx.translate(width, height);\n ctx.rotate(Math.PI);\n break;\n case 4:\n // vertical flip\n ctx.translate(0, height);\n ctx.scale(1, -1);\n break;\n case 5:\n // vertical flip + 90 rotate right\n ctx.rotate(0.5 * Math.PI);\n ctx.scale(1, -1);\n break;\n case 6:\n // 90 rotate right\n ctx.rotate(0.5 * Math.PI);\n ctx.translate(0, -height);\n break;\n case 7:\n // horizontal flip + 90 rotate right\n ctx.rotate(0.5 * Math.PI);\n ctx.translate(width, -height);\n ctx.scale(-1, 1);\n break;\n case 8:\n // 90 rotate left\n ctx.rotate(-0.5 * Math.PI);\n ctx.translate(-width, 0);\n break;\n default:\n break;\n }\n }\n\n /**\n * MegaPixImage class\n */\n function MegaPixImage(srcImage, errorCallback) {\n var self = this;\n\n if (window.Blob && srcImage instanceof Blob) {\n (function() {\n var img = new Image(),\n URL = window.URL && window.URL.createObjectURL ? window.URL :\n window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;\n if (!URL) { throw Error(\"No createObjectURL function found to create blob url\"); }\n img.src = URL.createObjectURL(srcImage);\n self.blob = srcImage;\n srcImage = img;\n }());\n }\n if (!srcImage.naturalWidth && !srcImage.naturalHeight) {\n srcImage.onload = function() {\n var listeners = self.imageLoadListeners;\n if (listeners) {\n self.imageLoadListeners = null;\n // IE11 doesn't reliably report actual image dimensions immediately after onload for small files,\n // so let's push this to the end of the UI thread queue.\n setTimeout(function() {\n for (var i = 0, len = listeners.length; i < len; i++) {\n listeners[i]();\n }\n }, 0);\n }\n };\n srcImage.onerror = errorCallback;\n this.imageLoadListeners = [];\n }\n this.srcImage = srcImage;\n }\n\n /**\n * Rendering megapix image into specified target element\n */\n MegaPixImage.prototype.render = function(target, options) {\n options = options || {};\n\n var self = this,\n imgWidth = this.srcImage.naturalWidth,\n imgHeight = this.srcImage.naturalHeight,\n width = options.width,\n height = options.height,\n maxWidth = options.maxWidth,\n maxHeight = options.maxHeight,\n doSquash = !this.blob || this.blob.type === \"image/jpeg\",\n tagName = target.tagName.toLowerCase(),\n opt;\n\n if (this.imageLoadListeners) {\n this.imageLoadListeners.push(function() { self.render(target, options); });\n return;\n }\n\n if (width && !height) {\n height = (imgHeight * width / imgWidth) << 0;\n } else if (height && !width) {\n width = (imgWidth * height / imgHeight) << 0;\n } else {\n width = imgWidth;\n height = imgHeight;\n }\n if (maxWidth && width > maxWidth) {\n width = maxWidth;\n height = (imgHeight * width / imgWidth) << 0;\n }\n if (maxHeight && height > maxHeight) {\n height = maxHeight;\n width = (imgWidth * height / imgHeight) << 0;\n }\n\n opt = { width: width, height: height },\n qq.each(options, function(optionsKey, optionsValue) {\n opt[optionsKey] = optionsValue;\n });\n\n if (tagName === \"img\") {\n (function() {\n var oldTargetSrc = target.src;\n renderImageToDataURL(self.srcImage, self.blob, opt, doSquash)\n .then(function(dataUri) {\n target.src = dataUri;\n oldTargetSrc === target.src && target.onload();\n });\n }());\n } else if (tagName === \"canvas\") {\n renderImageToCanvas(this.srcImage, this.blob, target, opt, doSquash);\n }\n if (typeof this.onrender === \"function\") {\n this.onrender(target);\n }\n };\n\n qq.MegaPixImage = MegaPixImage;\n})();\n","/*globals qq */\n/**\n * Draws a thumbnail of a Blob/File/URL onto an <img> or <canvas>.\n *\n * @constructor\n */\nqq.ImageGenerator = function(log) {\n \"use strict\";\n\n function isImg(el) {\n return el.tagName.toLowerCase() === \"img\";\n }\n\n function isCanvas(el) {\n return el.tagName.toLowerCase() === \"canvas\";\n }\n\n function isImgCorsSupported() {\n return new Image().crossOrigin !== undefined;\n }\n\n function isCanvasSupported() {\n var canvas = document.createElement(\"canvas\");\n\n return canvas.getContext && canvas.getContext(\"2d\");\n }\n\n // This is only meant to determine the MIME type of a renderable image file.\n // It is used to ensure images drawn from a URL that have transparent backgrounds\n // are rendered correctly, among other things.\n function determineMimeOfFileName(nameWithPath) {\n /*jshint -W015 */\n var pathSegments = nameWithPath.split(\"/\"),\n name = pathSegments[pathSegments.length - 1].split(\"?\")[0],\n extension = qq.getExtension(name);\n\n extension = extension && extension.toLowerCase();\n\n switch (extension) {\n case \"jpeg\":\n case \"jpg\":\n return \"image/jpeg\";\n case \"png\":\n return \"image/png\";\n case \"bmp\":\n return \"image/bmp\";\n case \"gif\":\n return \"image/gif\";\n case \"tiff\":\n case \"tif\":\n return \"image/tiff\";\n }\n }\n\n // This will likely not work correctly in IE8 and older.\n // It's only used as part of a formula to determine\n // if a canvas can be used to scale a server-hosted thumbnail.\n // If canvas isn't supported by the UA (IE8 and older)\n // this method should not even be called.\n function isCrossOrigin(url) {\n var targetAnchor = document.createElement(\"a\"),\n targetProtocol, targetHostname, targetPort;\n\n targetAnchor.href = url;\n\n targetProtocol = targetAnchor.protocol;\n targetPort = targetAnchor.port;\n targetHostname = targetAnchor.hostname;\n\n if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {\n return true;\n }\n\n if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {\n return true;\n }\n\n // IE doesn't take ports into consideration when determining if two endpoints are same origin.\n if (targetPort !== window.location.port && !qq.ie()) {\n return true;\n }\n\n return false;\n }\n\n function registerImgLoadListeners(img, promise) {\n img.onload = function() {\n img.onload = null;\n img.onerror = null;\n promise.success(img);\n };\n\n img.onerror = function() {\n img.onload = null;\n img.onerror = null;\n log(\"Problem drawing thumbnail!\", \"error\");\n promise.failure(img, \"Problem drawing thumbnail!\");\n };\n }\n\n function registerCanvasDrawImageListener(canvas, promise) {\n // The image is drawn on the canvas by a third-party library,\n // and we want to know when this is completed. Since the library\n // may invoke drawImage many times in a loop, we need to be called\n // back when the image is fully rendered. So, we are expecting the\n // code that draws this image to follow a convention that involves a\n // function attached to the canvas instance be invoked when it is done.\n canvas.qqImageRendered = function() {\n promise.success(canvas);\n };\n }\n\n // Fulfills a `qq.Promise` when an image has been drawn onto the target,\n // whether that is a <canvas> or an <img>. The attempt is considered a\n // failure if the target is not an <img> or a <canvas>, or if the drawing\n // attempt was not successful.\n function registerThumbnailRenderedListener(imgOrCanvas, promise) {\n var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);\n\n if (isImg(imgOrCanvas)) {\n registerImgLoadListeners(imgOrCanvas, promise);\n }\n else if (isCanvas(imgOrCanvas)) {\n registerCanvasDrawImageListener(imgOrCanvas, promise);\n }\n else {\n promise.failure(imgOrCanvas);\n log(qq.format(\"Element container of type {} is not supported!\", imgOrCanvas.tagName), \"error\");\n }\n\n return registered;\n }\n\n // Draw a preview iff the current UA can natively display it.\n // Also rotate the image if necessary.\n function draw(fileOrBlob, container, options) {\n var drawPreview = new qq.Promise(),\n identifier = new qq.Identify(fileOrBlob, log),\n maxSize = options.maxSize,\n // jshint eqnull:true\n orient = options.orient == null ? true : options.orient,\n megapixErrorHandler = function() {\n container.onerror = null;\n container.onload = null;\n log(\"Could not render preview, file may be too large!\", \"error\");\n drawPreview.failure(container, \"Browser cannot render image!\");\n };\n\n identifier.isPreviewable().then(\n function(mime) {\n // If options explicitly specify that Orientation is not desired,\n // replace the orient task with a dummy promise that \"succeeds\" immediately.\n var dummyExif = {\n parse: function() {\n return new qq.Promise().success();\n }\n },\n exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif,\n mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);\n\n if (registerThumbnailRenderedListener(container, drawPreview)) {\n exif.parse().then(\n function(exif) {\n var orientation = exif && exif.Orientation;\n\n mpImg.render(container, {\n maxWidth: maxSize,\n maxHeight: maxSize,\n orientation: orientation,\n mime: mime,\n resize: options.customResizeFunction\n });\n },\n\n function(failureMsg) {\n log(qq.format(\"EXIF data could not be parsed ({}). Assuming orientation = 1.\", failureMsg));\n\n mpImg.render(container, {\n maxWidth: maxSize,\n maxHeight: maxSize,\n mime: mime,\n resize: options.customResizeFunction\n });\n }\n );\n }\n },\n\n function() {\n log(\"Not previewable\");\n drawPreview.failure(container, \"Not previewable\");\n }\n );\n\n return drawPreview;\n }\n\n function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize, customResizeFunction) {\n var tempImg = new Image(),\n tempImgRender = new qq.Promise();\n\n registerThumbnailRenderedListener(tempImg, tempImgRender);\n\n if (isCrossOrigin(url)) {\n tempImg.crossOrigin = \"anonymous\";\n }\n\n tempImg.src = url;\n\n tempImgRender.then(\n function rendered() {\n registerThumbnailRenderedListener(canvasOrImg, draw);\n\n var mpImg = new qq.MegaPixImage(tempImg);\n mpImg.render(canvasOrImg, {\n maxWidth: maxSize,\n maxHeight: maxSize,\n mime: determineMimeOfFileName(url),\n resize: customResizeFunction\n });\n },\n\n draw.failure\n );\n }\n\n function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {\n registerThumbnailRenderedListener(img, draw);\n // NOTE: The fact that maxWidth/height is set on the thumbnail for scaled images\n // that must drop back to CSS is known and exploited by the templating module.\n // In this module, we pre-render \"waiting\" thumbs for all files immediately after they\n // are submitted, and we must be sure to pass any style associated with the \"waiting\" preview.\n qq(img).css({\n maxWidth: maxSize + \"px\",\n maxHeight: maxSize + \"px\"\n });\n\n img.src = url;\n }\n\n // Draw a (server-hosted) thumbnail given a URL.\n // This will optionally scale the thumbnail as well.\n // It attempts to use <canvas> to scale, but will fall back\n // to max-width and max-height style properties if the UA\n // doesn't support canvas or if the images is cross-domain and\n // the UA doesn't support the crossorigin attribute on img tags,\n // which is required to scale a cross-origin image using <canvas> &\n // then export it back to an <img>.\n function drawFromUrl(url, container, options) {\n var draw = new qq.Promise(),\n scale = options.scale,\n maxSize = scale ? options.maxSize : null;\n\n // container is an img, scaling needed\n if (scale && isImg(container)) {\n // Iff canvas is available in this UA, try to use it for scaling.\n // Otherwise, fall back to CSS scaling\n if (isCanvasSupported()) {\n // Attempt to use <canvas> for image scaling,\n // but we must fall back to scaling via CSS/styles\n // if this is a cross-origin image and the UA doesn't support <img> CORS.\n if (isCrossOrigin(url) && !isImgCorsSupported()) {\n drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);\n }\n else {\n drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);\n }\n }\n else {\n drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);\n }\n }\n // container is a canvas, scaling optional\n else if (isCanvas(container)) {\n drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);\n }\n // container is an img & no scaling: just set the src attr to the passed url\n else if (registerThumbnailRenderedListener(container, draw)) {\n container.src = url;\n }\n\n return draw;\n }\n\n qq.extend(this, {\n /**\n * Generate a thumbnail. Depending on the arguments, this may either result in\n * a client-side rendering of an image (if a `Blob` is supplied) or a server-generated\n * image that may optionally be scaled client-side using <canvas> or CSS/styles (as a fallback).\n *\n * @param fileBlobOrUrl a `File`, `Blob`, or a URL pointing to the image\n * @param container <img> or <canvas> to contain the preview\n * @param options possible properties include `maxSize` (int), `orient` (bool - default true), resize` (bool - default true), and `customResizeFunction`.\n * @returns qq.Promise fulfilled when the preview has been drawn, or the attempt has failed\n */\n generate: function(fileBlobOrUrl, container, options) {\n if (qq.isString(fileBlobOrUrl)) {\n log(\"Attempting to update thumbnail based on server response.\");\n return drawFromUrl(fileBlobOrUrl, container, options || {});\n }\n else {\n log(\"Attempting to draw client-side image preview.\");\n return draw(fileBlobOrUrl, container, options || {});\n }\n }\n });\n\n /*<testing>*/\n this._testing = {};\n this._testing.isImg = isImg;\n this._testing.isCanvas = isCanvas;\n this._testing.isCrossOrigin = isCrossOrigin;\n this._testing.determineMimeOfFileName = determineMimeOfFileName;\n /*</testing>*/\n};\n","/*globals qq */\n/**\n * EXIF image data parser. Currently only parses the Orientation tag value,\n * but this may be expanded to other tags in the future.\n *\n * @param fileOrBlob Attempt to parse EXIF data in this `Blob`\n * @constructor\n */\nqq.Exif = function(fileOrBlob, log) {\n \"use strict\";\n\n // Orientation is the only tag parsed here at this time.\n var TAG_IDS = [274],\n TAG_INFO = {\n 274: {\n name: \"Orientation\",\n bytes: 2\n }\n };\n\n // Convert a little endian (hex string) to big endian (decimal).\n function parseLittleEndian(hex) {\n var result = 0,\n pow = 0;\n\n while (hex.length > 0) {\n result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);\n hex = hex.substring(2, hex.length);\n pow += 8;\n }\n\n return result;\n }\n\n // Find the byte offset, of Application Segment 1 (EXIF).\n // External callers need not supply any arguments.\n function seekToApp1(offset, promise) {\n var theOffset = offset,\n thePromise = promise;\n if (theOffset === undefined) {\n theOffset = 2;\n thePromise = new qq.Promise();\n }\n\n qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {\n var match = /^ffe([0-9])/.exec(hex),\n segmentLength;\n\n if (match) {\n if (match[1] !== \"1\") {\n segmentLength = parseInt(hex.slice(4, 8), 16);\n seekToApp1(theOffset + segmentLength + 2, thePromise);\n }\n else {\n thePromise.success(theOffset);\n }\n }\n else {\n thePromise.failure(\"No EXIF header to be found!\");\n }\n });\n\n return thePromise;\n }\n\n // Find the byte offset of Application Segment 1 (EXIF) for valid JPEGs only.\n function getApp1Offset() {\n var promise = new qq.Promise();\n\n qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {\n if (hex.indexOf(\"ffd8\") !== 0) {\n promise.failure(\"Not a valid JPEG!\");\n }\n else {\n seekToApp1().then(function(offset) {\n promise.success(offset);\n },\n function(error) {\n promise.failure(error);\n });\n }\n });\n\n return promise;\n }\n\n // Determine the byte ordering of the EXIF header.\n function isLittleEndian(app1Start) {\n var promise = new qq.Promise();\n\n qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {\n promise.success(hex === \"4949\");\n });\n\n return promise;\n }\n\n // Determine the number of directory entries in the EXIF header.\n function getDirEntryCount(app1Start, littleEndian) {\n var promise = new qq.Promise();\n\n qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {\n if (littleEndian) {\n return promise.success(parseLittleEndian(hex));\n }\n else {\n promise.success(parseInt(hex, 16));\n }\n });\n\n return promise;\n }\n\n // Get the IFD portion of the EXIF header as a hex string.\n function getIfd(app1Start, dirEntries) {\n var offset = app1Start + 20,\n bytes = dirEntries * 12;\n\n return qq.readBlobToHex(fileOrBlob, offset, bytes);\n }\n\n // Obtain an array of all directory entries (as hex strings) in the EXIF header.\n function getDirEntries(ifdHex) {\n var entries = [],\n offset = 0;\n\n while (offset + 24 <= ifdHex.length) {\n entries.push(ifdHex.slice(offset, offset + 24));\n offset += 24;\n }\n\n return entries;\n }\n\n // Obtain values for all relevant tags and return them.\n function getTagValues(littleEndian, dirEntries) {\n var TAG_VAL_OFFSET = 16,\n tagsToFind = qq.extend([], TAG_IDS),\n vals = {};\n\n qq.each(dirEntries, function(idx, entry) {\n var idHex = entry.slice(0, 4),\n id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16),\n tagsToFindIdx = tagsToFind.indexOf(id),\n tagValHex, tagName, tagValLength;\n\n if (tagsToFindIdx >= 0) {\n tagName = TAG_INFO[id].name;\n tagValLength = TAG_INFO[id].bytes;\n tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength * 2));\n vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);\n\n tagsToFind.splice(tagsToFindIdx, 1);\n }\n\n if (tagsToFind.length === 0) {\n return false;\n }\n });\n\n return vals;\n }\n\n qq.extend(this, {\n /**\n * Attempt to parse the EXIF header for the `Blob` associated with this instance.\n *\n * @returns {qq.Promise} To be fulfilled when the parsing is complete.\n * If successful, the parsed EXIF header as an object will be included.\n */\n parse: function() {\n var parser = new qq.Promise(),\n onParseFailure = function(message) {\n log(qq.format(\"EXIF header parse failed: '{}' \", message));\n parser.failure(message);\n };\n\n getApp1Offset().then(function(app1Offset) {\n log(qq.format(\"Moving forward with EXIF header parsing for '{}'\", fileOrBlob.name === undefined ? \"blob\" : fileOrBlob.name));\n\n isLittleEndian(app1Offset).then(function(littleEndian) {\n\n log(qq.format(\"EXIF Byte order is {} endian\", littleEndian ? \"little\" : \"big\"));\n\n getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {\n\n log(qq.format(\"Found {} APP1 directory entries\", dirEntryCount));\n\n getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {\n var dirEntries = getDirEntries(ifdHex),\n tagValues = getTagValues(littleEndian, dirEntries);\n\n log(\"Successfully parsed some EXIF tags\");\n\n parser.success(tagValues);\n }, onParseFailure);\n }, onParseFailure);\n }, onParseFailure);\n }, onParseFailure);\n\n return parser;\n }\n });\n\n /*<testing>*/\n this._testing = {};\n this._testing.parseLittleEndian = parseLittleEndian;\n /*</testing>*/\n};\n","/*globals qq */\nqq.Identify = function(fileOrBlob, log) {\n \"use strict\";\n\n function isIdentifiable(magicBytes, questionableBytes) {\n var identifiable = false,\n magicBytesEntries = [].concat(magicBytes);\n\n qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {\n if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {\n identifiable = true;\n return false;\n }\n });\n\n return identifiable;\n }\n\n qq.extend(this, {\n /**\n * Determines if a Blob can be displayed natively in the current browser. This is done by reading magic\n * bytes in the beginning of the file, so this is an asynchronous operation. Before we attempt to read the\n * file, we will examine the blob's type attribute to save CPU cycles.\n *\n * @returns {qq.Promise} Promise that is fulfilled when identification is complete.\n * If successful, the MIME string is passed to the success handler.\n */\n isPreviewable: function() {\n var self = this,\n identifier = new qq.Promise(),\n previewable = false,\n name = fileOrBlob.name === undefined ? \"blob\" : fileOrBlob.name;\n\n log(qq.format(\"Attempting to determine if {} can be rendered in this browser\", name));\n\n log(\"First pass: check type attribute of blob object.\");\n\n if (this.isPreviewableSync()) {\n log(\"Second pass: check for magic bytes in file header.\");\n\n qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {\n qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {\n if (isIdentifiable(bytes, hex)) {\n // Safari is the only supported browser that can deal with TIFFs natively,\n // so, if this is a TIFF and the UA isn't Safari, declare this file \"non-previewable\".\n if (mime !== \"image/tiff\" || qq.supportedFeatures.tiffPreviews) {\n previewable = true;\n identifier.success(mime);\n }\n\n return false;\n }\n });\n\n log(qq.format(\"'{}' is {} able to be rendered in this browser\", name, previewable ? \"\" : \"NOT\"));\n\n if (!previewable) {\n identifier.failure();\n }\n },\n function() {\n log(\"Error reading file w/ name '\" + name + \"'. Not able to be rendered in this browser.\");\n identifier.failure();\n });\n }\n else {\n identifier.failure();\n }\n\n return identifier;\n },\n\n /**\n * Determines if a Blob can be displayed natively in the current browser. This is done by checking the\n * blob's type attribute. This is a synchronous operation, useful for situations where an asynchronous operation\n * would be challenging to support. Note that the blob's type property is not as accurate as reading the\n * file's magic bytes.\n *\n * @returns {Boolean} true if the blob can be rendered in the current browser\n */\n isPreviewableSync: function() {\n var fileMime = fileOrBlob.type,\n // Assumption: This will only ever be executed in browsers that support `Object.keys`.\n isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0,\n previewable = false,\n name = fileOrBlob.name === undefined ? \"blob\" : fileOrBlob.name;\n\n if (isRecognizedImage) {\n if (fileMime === \"image/tiff\") {\n previewable = qq.supportedFeatures.tiffPreviews;\n }\n else {\n previewable = true;\n }\n }\n\n !previewable && log(name + \" is not previewable in this browser per the blob's type attr\");\n\n return previewable;\n }\n });\n};\n\nqq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {\n \"image/jpeg\": \"ffd8ff\",\n \"image/gif\": \"474946\",\n \"image/png\": \"89504e\",\n \"image/bmp\": \"424d\",\n \"image/tiff\": [\"49492a00\", \"4d4d002a\"]\n};\n","/*globals qq*/\n/**\n * Attempts to validate an image, wherever possible.\n *\n * @param blob File or Blob representing a user-selecting image.\n * @param log Uses this to post log messages to the console.\n * @constructor\n */\nqq.ImageValidation = function(blob, log) {\n \"use strict\";\n\n /**\n * @param limits Object with possible image-related limits to enforce.\n * @returns {boolean} true if at least one of the limits has a non-zero value\n */\n function hasNonZeroLimits(limits) {\n var atLeastOne = false;\n\n qq.each(limits, function(limit, value) {\n if (value > 0) {\n atLeastOne = true;\n return false;\n }\n });\n\n return atLeastOne;\n }\n\n /**\n * @returns {qq.Promise} The promise is a failure if we can't obtain the width & height.\n * Otherwise, `success` is called on the returned promise with an object containing\n * `width` and `height` properties.\n */\n function getWidthHeight() {\n var sizeDetermination = new qq.Promise();\n\n new qq.Identify(blob, log).isPreviewable().then(function() {\n var image = new Image(),\n url = window.URL && window.URL.createObjectURL ? window.URL :\n window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL :\n null;\n\n if (url) {\n image.onerror = function() {\n log(\"Cannot determine dimensions for image. May be too large.\", \"error\");\n sizeDetermination.failure();\n };\n\n image.onload = function() {\n sizeDetermination.success({\n width: this.width,\n height: this.height\n });\n };\n\n image.src = url.createObjectURL(blob);\n }\n else {\n log(\"No createObjectURL function available to generate image URL!\", \"error\");\n sizeDetermination.failure();\n }\n }, sizeDetermination.failure);\n\n return sizeDetermination;\n }\n\n /**\n *\n * @param limits Object with possible image-related limits to enforce.\n * @param dimensions Object containing `width` & `height` properties for the image to test.\n * @returns {String || undefined} The name of the failing limit. Undefined if no failing limits.\n */\n function getFailingLimit(limits, dimensions) {\n var failingLimit;\n\n qq.each(limits, function(limitName, limitValue) {\n if (limitValue > 0) {\n var limitMatcher = /(max|min)(Width|Height)/.exec(limitName),\n dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1),\n actualValue = dimensions[dimensionPropName];\n\n /*jshint -W015*/\n switch (limitMatcher[1]) {\n case \"min\":\n if (actualValue < limitValue) {\n failingLimit = limitName;\n return false;\n }\n break;\n case \"max\":\n if (actualValue > limitValue) {\n failingLimit = limitName;\n return false;\n }\n break;\n }\n }\n });\n\n return failingLimit;\n }\n\n /**\n * Validate the associated blob.\n *\n * @param limits\n * @returns {qq.Promise} `success` is called on the promise is the image is valid or\n * if the blob is not an image, or if the image is not verifiable.\n * Otherwise, `failure` with the name of the failing limit.\n */\n this.validate = function(limits) {\n var validationEffort = new qq.Promise();\n\n log(\"Attempting to validate image.\");\n\n if (hasNonZeroLimits(limits)) {\n getWidthHeight().then(function(dimensions) {\n var failingLimit = getFailingLimit(limits, dimensions);\n\n if (failingLimit) {\n validationEffort.failure(failingLimit);\n }\n else {\n validationEffort.success();\n }\n }, validationEffort.success);\n }\n else {\n validationEffort.success();\n }\n\n return validationEffort;\n };\n};\n","/* globals qq */\n/**\n * Module used to control populating the initial list of files.\n *\n * @constructor\n */\nqq.Session = function(spec) {\n \"use strict\";\n\n var options = {\n endpoint: null,\n params: {},\n customHeaders: {},\n cors: {},\n addFileRecord: function(sessionData) {},\n log: function(message, level) {}\n };\n\n qq.extend(options, spec, true);\n\n function isJsonResponseValid(response) {\n if (qq.isArray(response)) {\n return true;\n }\n\n options.log(\"Session response is not an array.\", \"error\");\n }\n\n function handleFileItems(fileItems, success, xhrOrXdr, promise) {\n var someItemsIgnored = false;\n\n success = success && isJsonResponseValid(fileItems);\n\n if (success) {\n qq.each(fileItems, function(idx, fileItem) {\n /* jshint eqnull:true */\n if (fileItem.uuid == null) {\n someItemsIgnored = true;\n options.log(qq.format(\"Session response item {} did not include a valid UUID - ignoring.\", idx), \"error\");\n }\n else if (fileItem.name == null) {\n someItemsIgnored = true;\n options.log(qq.format(\"Session response item {} did not include a valid name - ignoring.\", idx), \"error\");\n }\n else {\n try {\n options.addFileRecord(fileItem);\n return true;\n }\n catch (err) {\n someItemsIgnored = true;\n options.log(err.message, \"error\");\n }\n }\n\n return false;\n });\n }\n\n promise[success && !someItemsIgnored ? \"success\" : \"failure\"](fileItems, xhrOrXdr);\n }\n\n // Initiate a call to the server that will be used to populate the initial file list.\n // Returns a `qq.Promise`.\n this.refresh = function() {\n /*jshint indent:false */\n var refreshEffort = new qq.Promise(),\n refreshCompleteCallback = function(response, success, xhrOrXdr) {\n handleFileItems(response, success, xhrOrXdr, refreshEffort);\n },\n requesterOptions = qq.extend({}, options),\n requester = new qq.SessionAjaxRequester(\n qq.extend(requesterOptions, {onComplete: refreshCompleteCallback})\n );\n\n requester.queryServer();\n\n return refreshEffort;\n };\n};\n","/*globals qq, XMLHttpRequest*/\n/**\n * Thin module used to send GET requests to the server, expecting information about session\n * data used to initialize an uploader instance.\n *\n * @param spec Various options used to influence the associated request.\n * @constructor\n */\nqq.SessionAjaxRequester = function(spec) {\n \"use strict\";\n\n var requester,\n options = {\n endpoint: null,\n customHeaders: {},\n params: {},\n cors: {\n expected: false,\n sendCredentials: false\n },\n onComplete: function(response, success, xhrOrXdr) {},\n log: function(str, level) {}\n };\n\n qq.extend(options, spec);\n\n function onComplete(id, xhrOrXdr, isError) {\n var response = null;\n\n /* jshint eqnull:true */\n if (xhrOrXdr.responseText != null) {\n try {\n response = qq.parseJson(xhrOrXdr.responseText);\n }\n catch (err) {\n options.log(\"Problem parsing session response: \" + err.message, \"error\");\n isError = true;\n }\n }\n\n options.onComplete(response, !isError, xhrOrXdr);\n }\n\n requester = qq.extend(this, new qq.AjaxRequester({\n acceptHeader: \"application/json\",\n validMethods: [\"GET\"],\n method: \"GET\",\n endpointStore: {\n get: function() {\n return options.endpoint;\n }\n },\n customHeaders: options.customHeaders,\n log: options.log,\n onComplete: onComplete,\n cors: options.cors\n }));\n\n qq.extend(this, {\n queryServer: function() {\n var params = qq.extend({}, options.params);\n\n options.log(\"Session query request.\");\n\n requester.initTransport(\"sessionRefresh\")\n .withParams(params)\n .withCacheBuster()\n .send();\n }\n });\n};\n","/* globals qq, ExifRestorer */\n/**\n * Controls generation of scaled images based on a reference image encapsulated in a `File` or `Blob`.\n * Scaled images are generated and converted to blobs on-demand.\n * Multiple scaled images per reference image with varying sizes and other properties are supported.\n *\n * @param spec Information about the scaled images to generate.\n * @param log Logger instance\n * @constructor\n */\nqq.Scaler = function(spec, log) {\n \"use strict\";\n\n var self = this,\n customResizeFunction = spec.customResizer,\n includeOriginal = spec.sendOriginal,\n orient = spec.orient,\n defaultType = spec.defaultType,\n defaultQuality = spec.defaultQuality / 100,\n failedToScaleText = spec.failureText,\n includeExif = spec.includeExif,\n sizes = this._getSortedSizes(spec.sizes);\n\n // Revealed API for instances of this module\n qq.extend(this, {\n // If no targeted sizes have been declared or if this browser doesn't support\n // client-side image preview generation, there is no scaling to do.\n enabled: qq.supportedFeatures.scaling && sizes.length > 0,\n\n getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {\n var self = this,\n records = [],\n originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData,\n identifier = new qq.Identify(originalBlob, log);\n\n // If the reference file cannot be rendered natively, we can't create scaled versions.\n if (identifier.isPreviewableSync()) {\n // Create records for each scaled version & add them to the records array, smallest first.\n qq.each(sizes, function(idx, sizeRecord) {\n var outputType = self._determineOutputType({\n defaultType: defaultType,\n requestedType: sizeRecord.type,\n refType: originalBlob.type\n });\n\n records.push({\n uuid: qq.getUniqueId(),\n name: self._getName(originalFileName, {\n name: sizeRecord.name,\n type: outputType,\n refType: originalBlob.type\n }),\n blob: new qq.BlobProxy(originalBlob,\n qq.bind(self._generateScaledImage, self, {\n customResizeFunction: customResizeFunction,\n maxSize: sizeRecord.maxSize,\n orient: orient,\n type: outputType,\n quality: defaultQuality,\n failedText: failedToScaleText,\n includeExif: includeExif,\n log: log\n }))\n });\n });\n\n records.push({\n uuid: originalFileUuid,\n name: originalFileName,\n size: originalBlob.size,\n blob: includeOriginal ? originalBlob : null\n });\n }\n else {\n records.push({\n uuid: originalFileUuid,\n name: originalFileName,\n size: originalBlob.size,\n blob: originalBlob\n });\n }\n\n return records;\n },\n\n handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {\n var self = this,\n buttonId = file.qqButtonId || (file.blob && file.blob.qqButtonId),\n scaledIds = [],\n originalId = null,\n addFileToHandler = api.addFileToHandler,\n uploadData = api.uploadData,\n paramsStore = api.paramsStore,\n proxyGroupId = qq.getUniqueId();\n\n qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {\n var blobSize = record.size,\n id;\n\n if (record.blob instanceof qq.BlobProxy) {\n blobSize = -1;\n }\n\n id = uploadData.addFile({\n uuid: record.uuid,\n name: record.name,\n size: blobSize,\n batchId: batchId,\n proxyGroupId: proxyGroupId\n });\n\n if (record.blob instanceof qq.BlobProxy) {\n scaledIds.push(id);\n }\n else {\n originalId = id;\n }\n\n if (record.blob) {\n addFileToHandler(id, record.blob);\n fileList.push({id: id, file: record.blob});\n }\n else {\n uploadData.setStatus(id, qq.status.REJECTED);\n }\n });\n\n // If we are potentially uploading an original file and some scaled versions,\n // ensure the scaled versions include reference's to the parent's UUID and size\n // in their associated upload requests.\n if (originalId !== null) {\n qq.each(scaledIds, function(idx, scaledId) {\n var params = {\n qqparentuuid: uploadData.retrieve({id: originalId}).uuid,\n qqparentsize: uploadData.retrieve({id: originalId}).size\n };\n\n // Make sure the UUID for each scaled image is sent with the upload request,\n // to be consistent (since we may need to ensure it is sent for the original file as well).\n params[uuidParamName] = uploadData.retrieve({id: scaledId}).uuid;\n\n uploadData.setParentId(scaledId, originalId);\n paramsStore.addReadOnly(scaledId, params);\n });\n\n // If any scaled images are tied to this parent image, be SURE we send its UUID as an upload request\n // parameter as well.\n if (scaledIds.length) {\n (function() {\n var param = {};\n param[uuidParamName] = uploadData.retrieve({id: originalId}).uuid;\n paramsStore.addReadOnly(originalId, param);\n }());\n }\n }\n }\n });\n};\n\nqq.extend(qq.Scaler.prototype, {\n scaleImage: function(id, specs, api) {\n \"use strict\";\n\n if (!qq.supportedFeatures.scaling) {\n throw new qq.Error(\"Scaling is not supported in this browser!\");\n }\n\n var scalingEffort = new qq.Promise(),\n log = api.log,\n file = api.getFile(id),\n uploadData = api.uploadData.retrieve({id: id}),\n name = uploadData && uploadData.name,\n uuid = uploadData && uploadData.uuid,\n scalingOptions = {\n customResizer: specs.customResizer,\n sendOriginal: false,\n orient: specs.orient,\n defaultType: specs.type || null,\n defaultQuality: specs.quality,\n failedToScaleText: \"Unable to scale\",\n sizes: [{name: \"\", maxSize: specs.maxSize}]\n },\n scaler = new qq.Scaler(scalingOptions, log);\n\n if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {\n scalingEffort.failure();\n\n log(\"Could not generate requested scaled image for \" + id + \". \" +\n \"Scaling is either not possible in this browser, or the file could not be located.\", \"error\");\n }\n else {\n (qq.bind(function() {\n // Assumption: There will never be more than one record\n var record = scaler.getFileRecords(uuid, name, file)[0];\n\n if (record && record.blob instanceof qq.BlobProxy) {\n record.blob.create().then(scalingEffort.success, scalingEffort.failure);\n }\n else {\n log(id + \" is not a scalable image!\", \"error\");\n scalingEffort.failure();\n }\n }, this)());\n }\n\n return scalingEffort;\n },\n\n // NOTE: We cannot reliably determine at this time if the UA supports a specific MIME type for the target format.\n // image/jpeg and image/png are the only safe choices at this time.\n _determineOutputType: function(spec) {\n \"use strict\";\n\n var requestedType = spec.requestedType,\n defaultType = spec.defaultType,\n referenceType = spec.refType;\n\n // If a default type and requested type have not been specified, this should be a\n // JPEG if the original type is a JPEG, otherwise, a PNG.\n if (!defaultType && !requestedType) {\n if (referenceType !== \"image/jpeg\") {\n return \"image/png\";\n }\n return referenceType;\n }\n\n // A specified default type is used when a requested type is not specified.\n if (!requestedType) {\n return defaultType;\n }\n\n // If requested type is specified, use it, as long as this recognized type is supported by the current UA\n if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {\n if (requestedType === \"image/tiff\") {\n return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;\n }\n\n return requestedType;\n }\n\n return defaultType;\n },\n\n // Get a file name for a generated scaled file record, based on the provided scaled image description\n _getName: function(originalName, scaledVersionProperties) {\n \"use strict\";\n\n var startOfExt = originalName.lastIndexOf(\".\"),\n versionType = scaledVersionProperties.type || \"image/png\",\n referenceType = scaledVersionProperties.refType,\n scaledName = \"\",\n scaledExt = qq.getExtension(originalName),\n nameAppendage = \"\";\n\n if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {\n nameAppendage = \" (\" + scaledVersionProperties.name + \")\";\n }\n\n if (startOfExt >= 0) {\n scaledName = originalName.substr(0, startOfExt);\n\n if (referenceType !== versionType) {\n scaledExt = versionType.split(\"/\")[1];\n }\n\n scaledName += nameAppendage + \".\" + scaledExt;\n }\n else {\n scaledName = originalName + nameAppendage;\n }\n\n return scaledName;\n },\n\n // We want the smallest scaled file to be uploaded first\n _getSortedSizes: function(sizes) {\n \"use strict\";\n\n sizes = qq.extend([], sizes);\n\n return sizes.sort(function(a, b) {\n if (a.maxSize > b.maxSize) {\n return 1;\n }\n if (a.maxSize < b.maxSize) {\n return -1;\n }\n return 0;\n });\n },\n\n _generateScaledImage: function(spec, sourceFile) {\n \"use strict\";\n\n var self = this,\n customResizeFunction = spec.customResizeFunction,\n log = spec.log,\n maxSize = spec.maxSize,\n orient = spec.orient,\n type = spec.type,\n quality = spec.quality,\n failedText = spec.failedText,\n includeExif = spec.includeExif && sourceFile.type === \"image/jpeg\" && type === \"image/jpeg\",\n scalingEffort = new qq.Promise(),\n imageGenerator = new qq.ImageGenerator(log),\n canvas = document.createElement(\"canvas\");\n\n log(\"Attempting to generate scaled version for \" + sourceFile.name);\n\n imageGenerator.generate(sourceFile, canvas, {maxSize: maxSize, orient: orient, customResizeFunction: customResizeFunction}).then(function() {\n var scaledImageDataUri = canvas.toDataURL(type, quality),\n signalSuccess = function() {\n log(\"Success generating scaled version for \" + sourceFile.name);\n var blob = qq.dataUriToBlob(scaledImageDataUri);\n scalingEffort.success(blob);\n };\n\n if (includeExif) {\n self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {\n scaledImageDataUri = scaledImageDataUriWithExif;\n signalSuccess();\n },\n function() {\n log(\"Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.\", \"error\");\n signalSuccess();\n });\n }\n else {\n signalSuccess();\n }\n }, function() {\n log(\"Failed attempt to generate scaled version for \" + sourceFile.name, \"error\");\n scalingEffort.failure(failedText);\n });\n\n return scalingEffort;\n },\n\n // Attempt to insert the original image's EXIF header into a scaled version.\n _insertExifHeader: function(originalImage, scaledImageDataUri, log) {\n \"use strict\";\n\n var reader = new FileReader(),\n insertionEffort = new qq.Promise(),\n originalImageDataUri = \"\";\n\n reader.onload = function() {\n originalImageDataUri = reader.result;\n insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));\n };\n\n reader.onerror = function() {\n log(\"Problem reading \" + originalImage.name + \" during attempt to transfer EXIF data to scaled version.\", \"error\");\n insertionEffort.failure();\n };\n\n reader.readAsDataURL(originalImage);\n\n return insertionEffort;\n },\n\n _dataUriToBlob: function(dataUri) {\n \"use strict\";\n\n var byteString, mimeString, arrayBuffer, intArray;\n\n // convert base64 to raw binary data held in a string\n if (dataUri.split(\",\")[0].indexOf(\"base64\") >= 0) {\n byteString = atob(dataUri.split(\",\")[1]);\n }\n else {\n byteString = decodeURI(dataUri.split(\",\")[1]);\n }\n\n // extract the MIME\n mimeString = dataUri.split(\",\")[0]\n .split(\":\")[1]\n .split(\";\")[0];\n\n // write the bytes of the binary string to an ArrayBuffer\n arrayBuffer = new ArrayBuffer(byteString.length);\n intArray = new Uint8Array(arrayBuffer);\n qq.each(byteString, function(idx, character) {\n intArray[idx] = character.charCodeAt(0);\n });\n\n return this._createBlob(arrayBuffer, mimeString);\n },\n\n _createBlob: function(data, mime) {\n \"use strict\";\n\n var BlobBuilder = window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder,\n blobBuilder = BlobBuilder && new BlobBuilder();\n\n if (blobBuilder) {\n blobBuilder.append(data);\n return blobBuilder.getBlob(mime);\n }\n else {\n return new Blob([data], {type: mime});\n }\n }\n});\n","//Based on MinifyJpeg\n//http://elicon.blog57.fc2.com/blog-entry-206.html\n\nqq.ExifRestorer = (function()\n{\n \n\tvar ExifRestorer = {};\n\t \n ExifRestorer.KEY_STR = \"ABCDEFGHIJKLMNOP\" +\n \"QRSTUVWXYZabcdef\" +\n \"ghijklmnopqrstuv\" +\n \"wxyz0123456789+/\" +\n \"=\";\n\n ExifRestorer.encode64 = function(input)\n {\n var output = \"\",\n chr1, chr2, chr3 = \"\",\n enc1, enc2, enc3, enc4 = \"\",\n i = 0;\n\n do {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n enc1 = chr1 >> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n enc4 = chr3 & 63;\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n } else if (isNaN(chr3)) {\n enc4 = 64;\n }\n\n output = output +\n this.KEY_STR.charAt(enc1) +\n this.KEY_STR.charAt(enc2) +\n this.KEY_STR.charAt(enc3) +\n this.KEY_STR.charAt(enc4);\n chr1 = chr2 = chr3 = \"\";\n enc1 = enc2 = enc3 = enc4 = \"\";\n } while (i < input.length);\n\n return output;\n };\n \n ExifRestorer.restore = function(origFileBase64, resizedFileBase64)\n {\n var expectedBase64Header = \"data:image/jpeg;base64,\";\n\n if (!origFileBase64.match(expectedBase64Header))\n {\n \treturn resizedFileBase64;\n } \n \n var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, \"\"));\n var segments = this.slice2Segments(rawImage);\n \n var image = this.exifManipulation(resizedFileBase64, segments);\n \n return expectedBase64Header + this.encode64(image);\n \n };\n\n\n ExifRestorer.exifManipulation = function(resizedFileBase64, segments)\n {\n var exifArray = this.getExifArray(segments),\n newImageArray = this.insertExif(resizedFileBase64, exifArray),\n aBuffer = new Uint8Array(newImageArray);\n\n return aBuffer;\n };\n\n\n ExifRestorer.getExifArray = function(segments)\n {\n var seg;\n for (var x = 0; x < segments.length; x++)\n {\n seg = segments[x];\n if (seg[0] == 255 & seg[1] == 225) //(ff e1)\n {\n return seg;\n }\n }\n return [];\n };\n\n\n ExifRestorer.insertExif = function(resizedFileBase64, exifArray)\n {\n var imageData = resizedFileBase64.replace(\"data:image/jpeg;base64,\", \"\"),\n buf = this.decode64(imageData),\n separatePoint = buf.indexOf(255,3),\n mae = buf.slice(0, separatePoint),\n ato = buf.slice(separatePoint),\n array = mae;\n\n array = array.concat(exifArray);\n array = array.concat(ato);\n return array;\n };\n\n\n \n ExifRestorer.slice2Segments = function(rawImageArray)\n {\n var head = 0,\n segments = [];\n\n while (1)\n {\n if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218){break;}\n if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216)\n {\n head += 2;\n }\n else\n {\n var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3],\n endPoint = head + length + 2,\n seg = rawImageArray.slice(head, endPoint);\n segments.push(seg);\n head = endPoint;\n }\n if (head > rawImageArray.length){break;}\n }\n\n return segments;\n };\n\n\n \n ExifRestorer.decode64 = function(input) \n {\n var output = \"\",\n chr1, chr2, chr3 = \"\",\n enc1, enc2, enc3, enc4 = \"\",\n i = 0,\n buf = [];\n\n // remove all characters that are not A-Z, a-z, 0-9, +, /, or =\n var base64test = /[^A-Za-z0-9\\+\\/\\=]/g;\n if (base64test.exec(input)) {\n throw new Error(\"There were invalid base64 characters in the input text. \" +\n \"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\");\n }\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, \"\");\n\n do {\n enc1 = this.KEY_STR.indexOf(input.charAt(i++));\n enc2 = this.KEY_STR.indexOf(input.charAt(i++));\n enc3 = this.KEY_STR.indexOf(input.charAt(i++));\n enc4 = this.KEY_STR.indexOf(input.charAt(i++));\n\n chr1 = (enc1 << 2) | (enc2 >> 4);\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n chr3 = ((enc3 & 3) << 6) | enc4;\n\n buf.push(chr1);\n\n if (enc3 != 64) {\n buf.push(chr2);\n }\n if (enc4 != 64) {\n buf.push(chr3);\n }\n\n chr1 = chr2 = chr3 = \"\";\n enc1 = enc2 = enc3 = enc4 = \"\";\n\n } while (i < input.length);\n\n return buf;\n };\n\n \n return ExifRestorer;\n})();\n","/* globals qq */\n/**\n * Keeps a running tally of total upload progress for a batch of files.\n *\n * @param callback Invoked when total progress changes, passing calculated total loaded & total size values.\n * @param getSize Function that returns the size of a file given its ID\n * @constructor\n */\nqq.TotalProgress = function(callback, getSize) {\n \"use strict\";\n\n var perFileProgress = {},\n totalLoaded = 0,\n totalSize = 0,\n\n lastLoadedSent = -1,\n lastTotalSent = -1,\n callbackProxy = function(loaded, total) {\n if (loaded !== lastLoadedSent || total !== lastTotalSent) {\n callback(loaded, total);\n }\n\n lastLoadedSent = loaded;\n lastTotalSent = total;\n },\n\n /**\n * @param failed Array of file IDs that have failed\n * @param retryable Array of file IDs that are retryable\n * @returns true if none of the failed files are eligible for retry\n */\n noRetryableFiles = function(failed, retryable) {\n var none = true;\n\n qq.each(failed, function(idx, failedId) {\n if (qq.indexOf(retryable, failedId) >= 0) {\n none = false;\n return false;\n }\n });\n\n return none;\n },\n\n onCancel = function(id) {\n updateTotalProgress(id, -1, -1);\n delete perFileProgress[id];\n },\n\n onAllComplete = function(successful, failed, retryable) {\n if (failed.length === 0 || noRetryableFiles(failed, retryable)) {\n callbackProxy(totalSize, totalSize);\n this.reset();\n }\n },\n\n onNew = function(id) {\n var size = getSize(id);\n\n // We might not know the size yet, such as for blob proxies\n if (size > 0) {\n updateTotalProgress(id, 0, size);\n perFileProgress[id] = {loaded: 0, total: size};\n }\n },\n\n /**\n * Invokes the callback with the current total progress of all files in the batch. Called whenever it may\n * be appropriate to re-calculate and disseminate this data.\n *\n * @param id ID of a file that has changed in some important way\n * @param newLoaded New loaded value for this file. -1 if this value should no longer be part of calculations\n * @param newTotal New total size of the file. -1 if this value should no longer be part of calculations\n */\n updateTotalProgress = function(id, newLoaded, newTotal) {\n var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0,\n oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;\n\n if (newLoaded === -1 && newTotal === -1) {\n totalLoaded -= oldLoaded;\n totalSize -= oldTotal;\n }\n else {\n if (newLoaded) {\n totalLoaded += newLoaded - oldLoaded;\n }\n if (newTotal) {\n totalSize += newTotal - oldTotal;\n }\n }\n\n callbackProxy(totalLoaded, totalSize);\n };\n\n qq.extend(this, {\n // Called when a batch of files has completed uploading.\n onAllComplete: onAllComplete,\n\n // Called when the status of a file has changed.\n onStatusChange: function(id, oldStatus, newStatus) {\n if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {\n onCancel(id);\n }\n else if (newStatus === qq.status.SUBMITTING) {\n onNew(id);\n }\n },\n\n // Called whenever the upload progress of an individual file has changed.\n onIndividualProgress: function(id, loaded, total) {\n updateTotalProgress(id, loaded, total);\n perFileProgress[id] = {loaded: loaded, total: total};\n },\n\n // Called whenever the total size of a file has changed, such as when the size of a generated blob is known.\n onNewSize: function(id) {\n onNew(id);\n },\n\n reset: function() {\n perFileProgress = {};\n totalLoaded = 0;\n totalSize = 0;\n }\n });\n};\n","/*globals qq*/\nqq.PasteSupport = function(o) {\n \"use strict\";\n\n var options, detachPasteHandler;\n\n options = {\n targetElement: null,\n callbacks: {\n log: function(message, level) {},\n pasteReceived: function(blob) {}\n }\n };\n\n function isImage(item) {\n return item.type &&\n item.type.indexOf(\"image/\") === 0;\n }\n\n function registerPasteHandler() {\n detachPasteHandler = qq(options.targetElement).attach(\"paste\", function(event) {\n var clipboardData = event.clipboardData;\n\n if (clipboardData) {\n qq.each(clipboardData.items, function(idx, item) {\n if (isImage(item)) {\n var blob = item.getAsFile();\n options.callbacks.pasteReceived(blob);\n }\n });\n }\n });\n }\n\n function unregisterPasteHandler() {\n if (detachPasteHandler) {\n detachPasteHandler();\n }\n }\n\n qq.extend(options, o);\n registerPasteHandler();\n\n qq.extend(this, {\n reset: function() {\n unregisterPasteHandler();\n }\n });\n};\n","/* globals qq */\n/**\n * Module that handles support for existing forms.\n *\n * @param options Options passed from the integrator-supplied options related to form support.\n * @param startUpload Callback to invoke when files \"stored\" should be uploaded.\n * @param log Proxy for the logger\n * @constructor\n */\nqq.FormSupport = function(options, startUpload, log) {\n \"use strict\";\n var self = this,\n interceptSubmit = options.interceptSubmit,\n formEl = options.element,\n autoUpload = options.autoUpload;\n\n // Available on the public API associated with this module.\n qq.extend(this, {\n // To be used by the caller to determine if the endpoint will be determined by some processing\n // that occurs in this module, such as if the form has an action attribute.\n // Ignore if `attachToForm === false`.\n newEndpoint: null,\n\n // To be used by the caller to determine if auto uploading should be allowed.\n // Ignore if `attachToForm === false`.\n newAutoUpload: autoUpload,\n\n // true if a form was detected and is being tracked by this module\n attachedToForm: false,\n\n // Returns an object with names and values for all valid form elements associated with the attached form.\n getFormInputsAsObject: function() {\n /* jshint eqnull:true */\n if (formEl == null) {\n return null;\n }\n\n return self._form2Obj(formEl);\n }\n });\n\n // If the form contains an action attribute, this should be the new upload endpoint.\n function determineNewEndpoint(formEl) {\n if (formEl.getAttribute(\"action\")) {\n self.newEndpoint = formEl.getAttribute(\"action\");\n }\n }\n\n // Return true only if the form is valid, or if we cannot make this determination.\n // If the form is invalid, ensure invalid field(s) are highlighted in the UI.\n function validateForm(formEl, nativeSubmit) {\n if (formEl.checkValidity && !formEl.checkValidity()) {\n log(\"Form did not pass validation checks - will not upload.\", \"error\");\n nativeSubmit();\n }\n else {\n return true;\n }\n }\n\n // Intercept form submit attempts, unless the integrator has told us not to do this.\n function maybeUploadOnSubmit(formEl) {\n var nativeSubmit = formEl.submit;\n\n // Intercept and squelch submit events.\n qq(formEl).attach(\"submit\", function(event) {\n event = event || window.event;\n\n if (event.preventDefault) {\n event.preventDefault();\n }\n else {\n event.returnValue = false;\n }\n\n validateForm(formEl, nativeSubmit) && startUpload();\n });\n\n // The form's `submit()` function may be called instead (i.e. via jQuery.submit()).\n // Intercept that too.\n formEl.submit = function() {\n validateForm(formEl, nativeSubmit) && startUpload();\n };\n }\n\n // If the element value passed from the uploader is a string, assume it is an element ID - select it.\n // The rest of the code in this module depends on this being an HTMLElement.\n function determineFormEl(formEl) {\n if (formEl) {\n if (qq.isString(formEl)) {\n formEl = document.getElementById(formEl);\n }\n\n if (formEl) {\n log(\"Attaching to form element.\");\n determineNewEndpoint(formEl);\n interceptSubmit && maybeUploadOnSubmit(formEl);\n }\n }\n\n return formEl;\n }\n\n formEl = determineFormEl(formEl);\n this.attachedToForm = !!formEl;\n};\n\nqq.extend(qq.FormSupport.prototype, {\n // Converts all relevant form fields to key/value pairs. This is meant to mimic the data a browser will\n // construct from a given form when the form is submitted.\n _form2Obj: function(form) {\n \"use strict\";\n var obj = {},\n notIrrelevantType = function(type) {\n var irrelevantTypes = [\n \"button\",\n \"image\",\n \"reset\",\n \"submit\"\n ];\n\n return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;\n },\n radioOrCheckbox = function(type) {\n return qq.indexOf([\"checkbox\", \"radio\"], type.toLowerCase()) >= 0;\n },\n ignoreValue = function(el) {\n if (radioOrCheckbox(el.type) && !el.checked) {\n return true;\n }\n\n return el.disabled && el.type.toLowerCase() !== \"hidden\";\n },\n selectValue = function(select) {\n var value = null;\n\n qq.each(qq(select).children(), function(idx, child) {\n if (child.tagName.toLowerCase() === \"option\" && child.selected) {\n value = child.value;\n return false;\n }\n });\n\n return value;\n };\n\n qq.each(form.elements, function(idx, el) {\n if ((qq.isInput(el, true) || el.tagName.toLowerCase() === \"textarea\") &&\n notIrrelevantType(el.type) &&\n !ignoreValue(el)) {\n\n obj[el.name] = el.value;\n }\n else if (el.tagName.toLowerCase() === \"select\" && !ignoreValue(el)) {\n var value = selectValue(el);\n\n if (value !== null) {\n obj[el.name] = value;\n }\n }\n });\n\n return obj;\n }\n});\n","/*globals qq*/\n/**\n * Upload handler used that assumes the current user agent does not have any support for the\n * File API, and, therefore, makes use of iframes and forms to submit the files directly to\n * a generic server.\n *\n * @param options Options passed from the base handler\n * @param proxy Callbacks & methods used to query for or push out data/changes\n */\nqq.traditional = qq.traditional || {};\nqq.traditional.FormUploadHandler = function(options, proxy) {\n \"use strict\";\n\n var handler = this,\n getName = proxy.getName,\n getUuid = proxy.getUuid,\n log = proxy.log;\n\n /**\n * Returns json object received by iframe from server.\n */\n function getIframeContentJson(id, iframe) {\n /*jshint evil: true*/\n\n var response, doc, innerHtml;\n\n //IE may throw an \"access is denied\" error when attempting to access contentDocument on the iframe in some cases\n try {\n // iframe.contentWindow.document - for IE<7\n doc = iframe.contentDocument || iframe.contentWindow.document;\n innerHtml = doc.body.innerHTML;\n\n log(\"converting iframe's innerHTML to JSON\");\n log(\"innerHTML = \" + innerHtml);\n //plain text response may be wrapped in <pre> tag\n if (innerHtml && innerHtml.match(/^<pre/i)) {\n innerHtml = doc.body.firstChild.firstChild.nodeValue;\n }\n\n response = handler._parseJsonResponse(innerHtml);\n }\n catch (error) {\n log(\"Error when attempting to parse form upload response (\" + error.message + \")\", \"error\");\n response = {success: false};\n }\n\n return response;\n }\n\n /**\n * Creates form, that will be submitted to iframe\n */\n function createForm(id, iframe) {\n var params = options.paramsStore.get(id),\n method = options.method.toLowerCase() === \"get\" ? \"GET\" : \"POST\",\n endpoint = options.endpointStore.get(id),\n name = getName(id);\n\n params[options.uuidName] = getUuid(id);\n params[options.filenameParam] = name;\n\n return handler._initFormForUpload({\n method: method,\n endpoint: endpoint,\n params: params,\n paramsInBody: options.paramsInBody,\n targetName: iframe.name\n });\n }\n\n this.uploadFile = function(id) {\n var input = handler.getInput(id),\n iframe = handler._createIframe(id),\n promise = new qq.Promise(),\n form;\n\n form = createForm(id, iframe);\n form.appendChild(input);\n\n handler._attachLoadEvent(iframe, function(responseFromMessage) {\n log(\"iframe loaded\");\n\n var response = responseFromMessage ? responseFromMessage : getIframeContentJson(id, iframe);\n\n handler._detachLoadEvent(id);\n\n //we can't remove an iframe if the iframe doesn't belong to the same domain\n if (!options.cors.expected) {\n qq(iframe).remove();\n }\n\n if (response.success) {\n promise.success(response);\n }\n else {\n promise.failure(response);\n }\n });\n\n log(\"Sending upload request for \" + id);\n form.submit();\n qq(form).remove();\n\n return promise;\n };\n\n qq.extend(this, new qq.FormUploadHandler({\n options: {\n isCors: options.cors.expected,\n inputName: options.inputName\n },\n\n proxy: {\n onCancel: options.onCancel,\n getName: getName,\n getUuid: getUuid,\n log: log\n }\n }));\n};\n","/*globals qq*/\n/**\n * Upload handler used to upload to traditional endpoints. It depends on File API support, and, therefore,\n * makes use of `XMLHttpRequest` level 2 to upload `File`s and `Blob`s to a generic server.\n *\n * @param spec Options passed from the base handler\n * @param proxy Callbacks & methods used to query for or push out data/changes\n */\nqq.traditional = qq.traditional || {};\nqq.traditional.XhrUploadHandler = function(spec, proxy) {\n \"use strict\";\n\n var handler = this,\n getName = proxy.getName,\n getSize = proxy.getSize,\n getUuid = proxy.getUuid,\n log = proxy.log,\n multipart = spec.forceMultipart || spec.paramsInBody,\n\n addChunkingSpecificParams = function(id, params, chunkData) {\n var size = getSize(id),\n name = getName(id);\n\n if (!spec.omitDefaultParams) {\n params[spec.chunking.paramNames.partIndex] = chunkData.part;\n params[spec.chunking.paramNames.partByteOffset] = chunkData.start;\n params[spec.chunking.paramNames.chunkSize] = chunkData.size;\n params[spec.chunking.paramNames.totalParts] = chunkData.count;\n params[spec.totalFileSizeName] = size;\n }\n\n /**\n * When a Blob is sent in a multipart request, the filename value in the content-disposition header is either \"blob\"\n * or an empty string. So, we will need to include the actual file name as a param in this case.\n */\n if (multipart && !spec.omitDefaultParams) {\n params[spec.filenameParam] = name;\n }\n },\n\n allChunksDoneRequester = new qq.traditional.AllChunksDoneAjaxRequester({\n cors: spec.cors,\n endpoint: spec.chunking.success.endpoint,\n headers: spec.chunking.success.headers,\n jsonPayload: spec.chunking.success.jsonPayload,\n log: log,\n method: spec.chunking.success.method,\n params: spec.chunking.success.params\n }),\n\n createReadyStateChangedHandler = function(id, xhr) {\n var promise = new qq.Promise();\n\n xhr.onreadystatechange = function() {\n if (xhr.readyState === 4) {\n var result = onUploadOrChunkComplete(id, xhr);\n\n if (result.success) {\n promise.success(result.response, xhr);\n }\n else {\n promise.failure(result.response, xhr);\n }\n }\n };\n\n return promise;\n },\n\n getChunksCompleteParams = function(id) {\n var params = spec.paramsStore.get(id),\n name = getName(id),\n size = getSize(id);\n\n params[spec.uuidName] = getUuid(id);\n params[spec.filenameParam] = name;\n params[spec.totalFileSizeName] = size;\n params[spec.chunking.paramNames.totalParts] = handler._getTotalChunks(id);\n\n return params;\n },\n\n isErrorUploadResponse = function(xhr, response) {\n return qq.indexOf([200, 201, 202, 203, 204], xhr.status) < 0 ||\n (spec.requireSuccessJson && !response.success) ||\n response.reset;\n },\n\n onUploadOrChunkComplete = function(id, xhr) {\n var response;\n\n log(\"xhr - server response received for \" + id);\n log(\"responseText = \" + xhr.responseText);\n\n response = parseResponse(true, xhr);\n\n return {\n success: !isErrorUploadResponse(xhr, response),\n response: response\n };\n },\n\n // If this is an upload response, we require a JSON payload, otherwise, it is optional.\n parseResponse = function(upload, xhr) {\n var response = {};\n\n try {\n log(qq.format(\"Received response status {} with body: {}\", xhr.status, xhr.responseText));\n response = qq.parseJson(xhr.responseText);\n }\n catch (error) {\n upload && spec.requireSuccessJson && log(\"Error when attempting to parse xhr response text (\" + error.message + \")\", \"error\");\n }\n\n return response;\n },\n\n sendChunksCompleteRequest = function(id) {\n var promise = new qq.Promise();\n\n allChunksDoneRequester.complete(\n id,\n handler._createXhr(id),\n getChunksCompleteParams(id),\n spec.customHeaders.get(id)\n )\n .then(function(xhr) {\n promise.success(parseResponse(false, xhr), xhr);\n }, function(xhr) {\n promise.failure(parseResponse(false, xhr), xhr);\n });\n\n return promise;\n },\n\n setParamsAndGetEntityToSend = function(entityToSendParams) {\n var fileOrBlob = entityToSendParams.fileOrBlob;\n var id = entityToSendParams.id;\n var xhr = entityToSendParams.xhr;\n var xhrOverrides = entityToSendParams.xhrOverrides || {};\n var customParams = entityToSendParams.customParams || {};\n var defaultParams = entityToSendParams.params || {};\n var xhrOverrideParams = xhrOverrides.params || {};\n var params;\n\n var formData = multipart ? new FormData() : null,\n method = xhrOverrides.method || spec.method,\n endpoint = xhrOverrides.endpoint || spec.endpointStore.get(id),\n name = getName(id),\n size = getSize(id);\n\n if (spec.omitDefaultParams) {\n params = qq.extend({}, customParams);\n qq.extend(params, xhrOverrideParams);\n }\n else {\n params = qq.extend({}, customParams);\n qq.extend(params, xhrOverrideParams);\n qq.extend(params, defaultParams);\n\n params[spec.uuidName] = getUuid(id);\n params[spec.filenameParam] = name;\n\n if (multipart) {\n params[spec.totalFileSizeName] = size;\n }\n else if (!spec.paramsInBody) {\n params[spec.inputName] = name;\n }\n }\n\n //build query string\n if (!spec.paramsInBody) {\n endpoint = qq.obj2url(params, endpoint);\n }\n\n xhr.open(method, endpoint, true);\n\n if (spec.cors.expected && spec.cors.sendCredentials) {\n xhr.withCredentials = true;\n }\n\n if (multipart) {\n if (spec.paramsInBody) {\n qq.obj2FormData(params, formData);\n }\n\n formData.append(spec.inputName, fileOrBlob);\n return formData;\n }\n\n return fileOrBlob;\n },\n\n setUploadHeaders = function(headersOptions) {\n var headerOverrides = headersOptions.headerOverrides;\n var id = headersOptions.id;\n var xhr = headersOptions.xhr;\n\n if (headerOverrides) {\n qq.each(headerOverrides, function(headerName, headerValue) {\n xhr.setRequestHeader(headerName, headerValue);\n });\n }\n else {\n var extraHeaders = spec.customHeaders.get(id),\n fileOrBlob = handler.getFile(id);\n\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\n xhr.setRequestHeader(\"Cache-Control\", \"no-cache\");\n\n if (!multipart) {\n xhr.setRequestHeader(\"Content-Type\", \"application/octet-stream\");\n //NOTE: return mime type in xhr works on chrome 16.0.9 firefox 11.0a2\n xhr.setRequestHeader(\"X-Mime-Type\", fileOrBlob.type);\n }\n\n qq.each(extraHeaders, function(name, val) {\n xhr.setRequestHeader(name, val);\n });\n }\n };\n\n qq.extend(this, {\n uploadChunk: function(uploadChunkParams) {\n var id = uploadChunkParams.id;\n var chunkIdx = uploadChunkParams.chunkIdx;\n var overrides = uploadChunkParams.overrides || {};\n var resuming = uploadChunkParams.resuming;\n\n var chunkData = handler._getChunkData(id, chunkIdx),\n xhr = handler._createXhr(id, chunkIdx),\n promise, toSend, customParams, params = {};\n\n promise = createReadyStateChangedHandler(id, xhr);\n handler._registerProgressHandler(id, chunkIdx, chunkData.size);\n customParams = spec.paramsStore.get(id);\n addChunkingSpecificParams(id, params, chunkData);\n\n if (resuming) {\n params[spec.resume.paramNames.resuming] = true;\n }\n\n toSend = setParamsAndGetEntityToSend({\n fileOrBlob: chunkData.blob,\n id: id,\n customParams: customParams,\n params: params,\n xhr: xhr,\n xhrOverrides: overrides\n });\n\n setUploadHeaders({\n headerOverrides: overrides.headers,\n id: id,\n xhr: xhr\n });\n\n xhr.send(toSend);\n\n return promise;\n },\n\n uploadFile: function(id) {\n var fileOrBlob = handler.getFile(id),\n promise, xhr, customParams, toSend;\n\n xhr = handler._createXhr(id);\n handler._registerProgressHandler(id);\n promise = createReadyStateChangedHandler(id, xhr);\n customParams = spec.paramsStore.get(id);\n\n toSend = setParamsAndGetEntityToSend({\n fileOrBlob: fileOrBlob,\n id: id,\n customParams: customParams,\n xhr: xhr\n });\n\n setUploadHeaders({\n id: id,\n xhr: xhr\n });\n\n xhr.send(toSend);\n\n return promise;\n }\n });\n\n qq.extend(this, new qq.XhrUploadHandler({\n options: qq.extend({namespace: \"traditional\"}, spec),\n proxy: qq.extend({getEndpoint: spec.endpointStore.get}, proxy)\n }));\n\n qq.override(this, function(super_) {\n return {\n finalizeChunks: function(id) {\n proxy.onFinalizing(id);\n\n if (spec.chunking.success.endpoint) {\n return sendChunksCompleteRequest(id);\n }\n else {\n return super_.finalizeChunks(id, qq.bind(parseResponse, this, true));\n }\n }\n };\n });\n};\n","/*globals qq*/\n/**\n * Ajax requester used to send a POST to a traditional endpoint once all chunks for a specific file have uploaded\n * successfully.\n *\n * @param o Options from the caller - will override the defaults.\n * @constructor\n */\nqq.traditional.AllChunksDoneAjaxRequester = function(o) {\n \"use strict\";\n\n var requester,\n options = {\n cors: {\n allowXdr: false,\n expected: false,\n sendCredentials: false\n },\n endpoint: null,\n log: function(str, level) {},\n method: \"POST\"\n },\n promises = {},\n endpointHandler = {\n get: function(id) {\n if (qq.isFunction(options.endpoint)) {\n return options.endpoint(id);\n }\n\n return options.endpoint;\n }\n };\n\n qq.extend(options, o);\n\n requester = qq.extend(this, new qq.AjaxRequester({\n acceptHeader: \"application/json\",\n contentType: options.jsonPayload ? \"application/json\" : \"application/x-www-form-urlencoded\",\n validMethods: [options.method],\n method: options.method,\n endpointStore: endpointHandler,\n allowXRequestedWithAndCacheControl: false,\n cors: options.cors,\n log: options.log,\n onComplete: function(id, xhr, isError) {\n var promise = promises[id];\n\n delete promises[id];\n\n if (isError) {\n promise.failure(xhr);\n }\n else {\n promise.success(xhr);\n }\n }\n }));\n\n qq.extend(this, {\n complete: function(id, xhr, params, headers) {\n var promise = new qq.Promise();\n\n options.log(\"Submitting All Chunks Done request for \" + id);\n\n promises[id] = promise;\n\n requester.initTransport(id)\n .withParams(options.params(id) || params)\n .withHeaders(options.headers(id) || headers)\n .send(xhr);\n\n return promise;\n }\n });\n};\n","/*globals qq, document, CustomEvent*/\nqq.DragAndDrop = function(o) {\n \"use strict\";\n\n var options,\n HIDE_ZONES_EVENT_NAME = \"qq-hidezones\",\n HIDE_BEFORE_ENTER_ATTR = \"qq-hide-dropzone\",\n uploadDropZones = [],\n droppedFiles = [],\n disposeSupport = new qq.DisposeSupport();\n\n options = {\n dropZoneElements: [],\n allowMultipleItems: true,\n classes: {\n dropActive: null\n },\n callbacks: new qq.DragAndDrop.callbacks()\n };\n\n qq.extend(options, o, true);\n\n function uploadDroppedFiles(files, uploadDropZone) {\n // We need to convert the `FileList` to an actual `Array` to avoid iteration issues\n var filesAsArray = Array.prototype.slice.call(files);\n\n options.callbacks.dropLog(\"Grabbed \" + files.length + \" dropped files.\");\n uploadDropZone.dropDisabled(false);\n options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement());\n }\n\n function traverseFileTree(entry) {\n var parseEntryPromise = new qq.Promise();\n\n if (entry.isFile) {\n entry.file(function(file) {\n file.qqPath = extractDirectoryPath(entry);\n droppedFiles.push(file);\n parseEntryPromise.success();\n },\n function(fileError) {\n options.callbacks.dropLog(\"Problem parsing '\" + entry.fullPath + \"'. FileError code \" + fileError.code + \".\", \"error\");\n parseEntryPromise.failure();\n });\n }\n else if (entry.isDirectory) {\n getFilesInDirectory(entry).then(\n function allEntriesRead(entries) {\n var entriesLeft = entries.length;\n\n qq.each(entries, function(idx, entry) {\n traverseFileTree(entry).done(function() {\n entriesLeft -= 1;\n\n if (entriesLeft === 0) {\n parseEntryPromise.success();\n }\n });\n });\n\n if (!entries.length) {\n parseEntryPromise.success();\n }\n },\n\n function readFailure(fileError) {\n options.callbacks.dropLog(\"Problem parsing '\" + entry.fullPath + \"'. FileError code \" + fileError.code + \".\", \"error\");\n parseEntryPromise.failure();\n }\n );\n }\n\n return parseEntryPromise;\n }\n\n function extractDirectoryPath(entry) {\n var name = entry.name,\n fullPath = entry.fullPath,\n indexOfNameInFullPath = fullPath.lastIndexOf(name);\n\n // remove file name from full path string\n fullPath = fullPath.substr(0, indexOfNameInFullPath);\n\n // remove leading slash in full path string\n if (fullPath.charAt(0) === \"/\") {\n fullPath = fullPath.substr(1);\n }\n\n return fullPath;\n }\n\n // Promissory. Guaranteed to read all files in the root of the passed directory.\n function getFilesInDirectory(entry, reader, accumEntries, existingPromise) {\n var promise = existingPromise || new qq.Promise(),\n dirReader = reader || entry.createReader();\n\n dirReader.readEntries(\n function readSuccess(entries) {\n var newEntries = accumEntries ? accumEntries.concat(entries) : entries;\n\n if (entries.length) {\n setTimeout(function() { // prevent stack overflow, however unlikely\n getFilesInDirectory(entry, dirReader, newEntries, promise);\n }, 0);\n }\n else {\n promise.success(newEntries);\n }\n },\n\n promise.failure\n );\n\n return promise;\n }\n\n function handleDataTransfer(dataTransfer, uploadDropZone) {\n var pendingFolderPromises = [],\n handleDataTransferPromise = new qq.Promise();\n\n options.callbacks.processingDroppedFiles();\n uploadDropZone.dropDisabled(true);\n\n if (dataTransfer.files.length > 1 && !options.allowMultipleItems) {\n options.callbacks.processingDroppedFilesComplete([]);\n options.callbacks.dropError(\"tooManyFilesError\", \"\");\n uploadDropZone.dropDisabled(false);\n handleDataTransferPromise.failure();\n }\n else {\n droppedFiles = [];\n\n if (qq.isFolderDropSupported(dataTransfer)) {\n qq.each(dataTransfer.items, function(idx, item) {\n var entry = item.webkitGetAsEntry();\n\n if (entry) {\n //due to a bug in Chrome's File System API impl - #149735\n if (entry.isFile) {\n droppedFiles.push(item.getAsFile());\n }\n\n else {\n pendingFolderPromises.push(traverseFileTree(entry).done(function() {\n pendingFolderPromises.pop();\n if (pendingFolderPromises.length === 0) {\n handleDataTransferPromise.success();\n }\n }));\n }\n }\n });\n }\n else {\n droppedFiles = dataTransfer.files;\n }\n\n if (pendingFolderPromises.length === 0) {\n handleDataTransferPromise.success();\n }\n }\n\n return handleDataTransferPromise;\n }\n\n function setupDropzone(dropArea) {\n var dropZone = new qq.UploadDropZone({\n HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME,\n element: dropArea,\n onEnter: function(e) {\n qq(dropArea).addClass(options.classes.dropActive);\n e.stopPropagation();\n },\n onLeaveNotDescendants: function(e) {\n qq(dropArea).removeClass(options.classes.dropActive);\n },\n onDrop: function(e) {\n handleDataTransfer(e.dataTransfer, dropZone).then(\n function() {\n uploadDroppedFiles(droppedFiles, dropZone);\n },\n function() {\n options.callbacks.dropLog(\"Drop event DataTransfer parsing failed. No files will be uploaded.\", \"error\");\n }\n );\n }\n });\n\n disposeSupport.addDisposer(function() {\n dropZone.dispose();\n });\n\n qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide();\n\n uploadDropZones.push(dropZone);\n\n return dropZone;\n }\n\n function isFileDrag(dragEvent) {\n var fileDrag;\n\n qq.each(dragEvent.dataTransfer.types, function(key, val) {\n if (val === \"Files\") {\n fileDrag = true;\n return false;\n }\n });\n\n return fileDrag;\n }\n\n // Attempt to determine when the file has left the document. It is not always possible to detect this\n // in all cases, but it is generally possible in all browsers, with a few exceptions.\n //\n // Exceptions:\n // * IE10+ & Safari: We can't detect a file leaving the document if the Explorer window housing the file\n // overlays the browser window.\n // * IE10+: If the file is dragged out of the window too quickly, IE does not set the expected values of the\n // event's X & Y properties.\n function leavingDocumentOut(e) {\n if (qq.safari()) {\n return e.x < 0 || e.y < 0;\n }\n\n return e.x === 0 && e.y === 0;\n }\n\n function setupDragDrop() {\n var dropZones = options.dropZoneElements,\n\n maybeHideDropZones = function() {\n setTimeout(function() {\n qq.each(dropZones, function(idx, dropZone) {\n qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide();\n qq(dropZone).removeClass(options.classes.dropActive);\n });\n }, 10);\n };\n\n qq.each(dropZones, function(idx, dropZone) {\n var uploadDropZone = setupDropzone(dropZone);\n\n // IE <= 9 does not support the File API used for drag+drop uploads\n if (dropZones.length && qq.supportedFeatures.fileDrop) {\n disposeSupport.attach(document, \"dragenter\", function(e) {\n if (!uploadDropZone.dropDisabled() && isFileDrag(e)) {\n qq.each(dropZones, function(idx, dropZone) {\n // We can't apply styles to non-HTMLElements, since they lack the `style` property.\n // Also, if the drop zone isn't initially hidden, let's not mess with `style.display`.\n if (dropZone instanceof HTMLElement &&\n qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) {\n\n qq(dropZone).css({display: \"block\"});\n }\n });\n }\n });\n }\n });\n\n disposeSupport.attach(document, \"dragleave\", function(e) {\n if (leavingDocumentOut(e)) {\n maybeHideDropZones();\n }\n });\n\n // Just in case we were not able to detect when a dragged file has left the document,\n // hide all relevant drop zones the next time the mouse enters the document.\n // Note that mouse events such as this one are not fired during drag operations.\n disposeSupport.attach(qq(document).children()[0], \"mouseenter\", function(e) {\n maybeHideDropZones();\n });\n\n disposeSupport.attach(document, \"drop\", function(e) {\n if (isFileDrag(e)) {\n e.preventDefault();\n maybeHideDropZones();\n }\n });\n\n disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones);\n }\n\n setupDragDrop();\n\n qq.extend(this, {\n setupExtraDropzone: function(element) {\n options.dropZoneElements.push(element);\n setupDropzone(element);\n },\n\n removeDropzone: function(element) {\n var i,\n dzs = options.dropZoneElements;\n\n for (i in dzs) {\n if (dzs[i] === element) {\n return dzs.splice(i, 1);\n }\n }\n },\n\n dispose: function() {\n disposeSupport.dispose();\n qq.each(uploadDropZones, function(idx, dropZone) {\n dropZone.dispose();\n });\n }\n });\n\n this._testing = {};\n this._testing.extractDirectoryPath = extractDirectoryPath;\n};\n\nqq.DragAndDrop.callbacks = function() {\n \"use strict\";\n\n return {\n processingDroppedFiles: function() {},\n processingDroppedFilesComplete: function(files, targetEl) {},\n dropError: function(code, errorSpecifics) {\n qq.log(\"Drag & drop error code '\" + code + \" with these specifics: '\" + errorSpecifics + \"'\", \"error\");\n },\n dropLog: function(message, level) {\n qq.log(message, level);\n }\n };\n};\n\nqq.UploadDropZone = function(o) {\n \"use strict\";\n\n var disposeSupport = new qq.DisposeSupport(),\n options, element, preventDrop, dropOutsideDisabled;\n\n options = {\n element: null,\n onEnter: function(e) {},\n onLeave: function(e) {},\n // is not fired when leaving element by hovering descendants\n onLeaveNotDescendants: function(e) {},\n onDrop: function(e) {}\n };\n\n qq.extend(options, o);\n element = options.element;\n\n function dragoverShouldBeCanceled() {\n return qq.safari() || (qq.firefox() && qq.windows());\n }\n\n function disableDropOutside(e) {\n // run only once for all instances\n if (!dropOutsideDisabled) {\n\n // for these cases we need to catch onDrop to reset dropArea\n if (dragoverShouldBeCanceled) {\n disposeSupport.attach(document, \"dragover\", function(e) {\n e.preventDefault();\n });\n } else {\n disposeSupport.attach(document, \"dragover\", function(e) {\n if (e.dataTransfer) {\n e.dataTransfer.dropEffect = \"none\";\n e.preventDefault();\n }\n });\n }\n\n dropOutsideDisabled = true;\n }\n }\n\n function isValidFileDrag(e) {\n // e.dataTransfer currently causing IE errors\n // IE9 does NOT support file API, so drag-and-drop is not possible\n if (!qq.supportedFeatures.fileDrop) {\n return false;\n }\n\n var effectTest, dt = e.dataTransfer,\n // do not check dt.types.contains in webkit, because it crashes safari 4\n isSafari = qq.safari();\n\n // dt.effectAllowed is none in Safari 5\n\n // dt.effectAllowed crashes IE 11 & 10 when files have been dragged from\n // the filesystem\n effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== \"none\";\n return dt && effectTest &&\n (\n (dt.files && dt.files.length) || // Valid for drop events with files\n (!isSafari && dt.types.contains && dt.types.contains(\"Files\")) || // Valid in Chrome/Firefox\n (dt.types.includes && dt.types.includes(\"Files\")) // Valid in IE\n );\n }\n\n function isOrSetDropDisabled(isDisabled) {\n if (isDisabled !== undefined) {\n preventDrop = isDisabled;\n }\n return preventDrop;\n }\n\n function triggerHidezonesEvent() {\n var hideZonesEvent;\n\n function triggerUsingOldApi() {\n hideZonesEvent = document.createEvent(\"Event\");\n hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true);\n }\n\n if (window.CustomEvent) {\n try {\n hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME);\n }\n catch (err) {\n triggerUsingOldApi();\n }\n }\n else {\n triggerUsingOldApi();\n }\n\n document.dispatchEvent(hideZonesEvent);\n }\n\n function attachEvents() {\n disposeSupport.attach(element, \"dragover\", function(e) {\n if (!isValidFileDrag(e)) {\n return;\n }\n\n // dt.effectAllowed crashes IE 11 & 10 when files have been dragged from\n // the filesystem\n var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed;\n if (effect === \"move\" || effect === \"linkMove\") {\n e.dataTransfer.dropEffect = \"move\"; // for FF (only move allowed)\n } else {\n e.dataTransfer.dropEffect = \"copy\"; // for Chrome\n }\n\n e.stopPropagation();\n e.preventDefault();\n });\n\n disposeSupport.attach(element, \"dragenter\", function(e) {\n if (!isOrSetDropDisabled()) {\n if (!isValidFileDrag(e)) {\n return;\n }\n options.onEnter(e);\n }\n });\n\n disposeSupport.attach(element, \"dragleave\", function(e) {\n if (!isValidFileDrag(e)) {\n return;\n }\n\n options.onLeave(e);\n\n var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);\n // do not fire when moving a mouse over a descendant\n if (qq(this).contains(relatedTarget)) {\n return;\n }\n\n options.onLeaveNotDescendants(e);\n });\n\n disposeSupport.attach(element, \"drop\", function(e) {\n if (!isOrSetDropDisabled()) {\n if (!isValidFileDrag(e)) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n options.onDrop(e);\n\n triggerHidezonesEvent();\n }\n });\n }\n\n disableDropOutside();\n attachEvents();\n\n qq.extend(this, {\n dropDisabled: function(isDisabled) {\n return isOrSetDropDisabled(isDisabled);\n },\n\n dispose: function() {\n disposeSupport.dispose();\n },\n\n getElement: function() {\n return element;\n }\n });\n\n this._testing = {};\n this._testing.isValidFileDrag = isValidFileDrag;\n};\n","/*globals qq */\n/**\n * Defines the public API for FineUploader mode.\n */\n(function() {\n \"use strict\";\n\n qq.uiPublicApi = {\n addInitialFiles: function(cannedFileList) {\n this._parent.prototype.addInitialFiles.apply(this, arguments);\n this._templating.addCacheToDom();\n },\n\n clearStoredFiles: function() {\n this._parent.prototype.clearStoredFiles.apply(this, arguments);\n this._templating.clearFiles();\n },\n\n addExtraDropzone: function(element) {\n this._dnd && this._dnd.setupExtraDropzone(element);\n },\n\n removeExtraDropzone: function(element) {\n if (this._dnd) {\n return this._dnd.removeDropzone(element);\n }\n },\n\n getItemByFileId: function(id) {\n if (!this._templating.isHiddenForever(id)) {\n return this._templating.getFileContainer(id);\n }\n },\n\n reset: function() {\n this._parent.prototype.reset.apply(this, arguments);\n this._templating.reset();\n\n if (!this._options.button && this._templating.getButton()) {\n this._defaultButtonId = this._createUploadButton({\n element: this._templating.getButton(),\n title: this._options.text.fileInputTitle\n }).getButtonId();\n }\n\n if (this._dnd) {\n this._dnd.dispose();\n this._dnd = this._setupDragAndDrop();\n }\n\n this._totalFilesInBatch = 0;\n this._filesInBatchAddedToUi = 0;\n\n this._setupClickAndEditEventHandlers();\n },\n\n setName: function(id, newName) {\n var formattedFilename = this._options.formatFileName(newName);\n\n this._parent.prototype.setName.apply(this, arguments);\n this._templating.updateFilename(id, formattedFilename);\n },\n\n pauseUpload: function(id) {\n var paused = this._parent.prototype.pauseUpload.apply(this, arguments);\n\n paused && this._templating.uploadPaused(id);\n return paused;\n },\n\n continueUpload: function(id) {\n var continued = this._parent.prototype.continueUpload.apply(this, arguments);\n\n continued && this._templating.uploadContinued(id);\n return continued;\n },\n\n getId: function(fileContainerOrChildEl) {\n return this._templating.getFileId(fileContainerOrChildEl);\n },\n\n getDropTarget: function(fileId) {\n var file = this.getFile(fileId);\n\n return file.qqDropTarget;\n }\n };\n\n /**\n * Defines the private (internal) API for FineUploader mode.\n */\n qq.uiPrivateApi = {\n _getButton: function(buttonId) {\n var button = this._parent.prototype._getButton.apply(this, arguments);\n\n if (!button) {\n if (buttonId === this._defaultButtonId) {\n button = this._templating.getButton();\n }\n }\n\n return button;\n },\n\n _removeFileItem: function(fileId) {\n this._templating.removeFile(fileId);\n },\n\n _setupClickAndEditEventHandlers: function() {\n this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent();\n\n // A better approach would be to check specifically for focusin event support by querying the DOM API,\n // but the DOMFocusIn event is not exposed as a property, so we have to resort to UA string sniffing.\n this._focusinEventSupported = !qq.firefox();\n\n if (this._isEditFilenameEnabled())\n {\n this._filenameClickHandler = this._bindFilenameClickEvent();\n this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent();\n this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent();\n }\n },\n\n _setupDragAndDrop: function() {\n var self = this,\n dropZoneElements = this._options.dragAndDrop.extraDropzones,\n templating = this._templating,\n defaultDropZone = templating.getDropZone();\n\n defaultDropZone && dropZoneElements.push(defaultDropZone);\n\n return new qq.DragAndDrop({\n dropZoneElements: dropZoneElements,\n allowMultipleItems: this._options.multiple,\n classes: {\n dropActive: this._options.classes.dropActive\n },\n callbacks: {\n processingDroppedFiles: function() {\n templating.showDropProcessing();\n },\n processingDroppedFilesComplete: function(files, targetEl) {\n templating.hideDropProcessing();\n\n qq.each(files, function(idx, file) {\n file.qqDropTarget = targetEl;\n });\n\n if (files.length) {\n self.addFiles(files, null, null);\n }\n },\n dropError: function(code, errorData) {\n self._itemError(code, errorData);\n },\n dropLog: function(message, level) {\n self.log(message, level);\n }\n }\n });\n },\n\n _bindFileButtonsClickEvent: function() {\n var self = this;\n\n return new qq.FileButtonsClickHandler({\n templating: this._templating,\n\n log: function(message, lvl) {\n self.log(message, lvl);\n },\n\n onDeleteFile: function(fileId) {\n self.deleteFile(fileId);\n },\n\n onCancel: function(fileId) {\n self.cancel(fileId);\n },\n\n onRetry: function(fileId) {\n self.retry(fileId);\n },\n\n onPause: function(fileId) {\n self.pauseUpload(fileId);\n },\n\n onContinue: function(fileId) {\n self.continueUpload(fileId);\n },\n\n onGetName: function(fileId) {\n return self.getName(fileId);\n }\n });\n },\n\n _isEditFilenameEnabled: function() {\n /*jshint -W014 */\n return this._templating.isEditFilenamePossible()\n && !this._options.autoUpload\n && qq.FilenameClickHandler\n && qq.FilenameInputFocusHandler\n && qq.FilenameInputFocusHandler;\n },\n\n _filenameEditHandler: function() {\n var self = this,\n templating = this._templating;\n\n return {\n templating: templating,\n log: function(message, lvl) {\n self.log(message, lvl);\n },\n onGetUploadStatus: function(fileId) {\n return self.getUploads({id: fileId}).status;\n },\n onGetName: function(fileId) {\n return self.getName(fileId);\n },\n onSetName: function(id, newName) {\n self.setName(id, newName);\n },\n onEditingStatusChange: function(id, isEditing) {\n var qqInput = qq(templating.getEditInput(id)),\n qqFileContainer = qq(templating.getFileContainer(id));\n\n if (isEditing) {\n qqInput.addClass(\"qq-editing\");\n templating.hideFilename(id);\n templating.hideEditIcon(id);\n }\n else {\n qqInput.removeClass(\"qq-editing\");\n templating.showFilename(id);\n templating.showEditIcon(id);\n }\n\n // Force IE8 and older to repaint\n qqFileContainer.addClass(\"qq-temp\").removeClass(\"qq-temp\");\n }\n };\n },\n\n _onUploadStatusChange: function(id, oldStatus, newStatus) {\n this._parent.prototype._onUploadStatusChange.apply(this, arguments);\n\n if (this._isEditFilenameEnabled()) {\n // Status for a file exists before it has been added to the DOM, so we must be careful here.\n if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) {\n this._templating.markFilenameEditable(id);\n this._templating.hideEditIcon(id);\n }\n }\n\n if (oldStatus === qq.status.UPLOAD_RETRYING && newStatus === qq.status.UPLOADING) {\n this._templating.hideRetry(id);\n this._templating.setStatusText(id);\n qq(this._templating.getFileContainer(id)).removeClass(this._classes.retrying);\n }\n else if (newStatus === qq.status.UPLOAD_FAILED) {\n this._templating.hidePause(id);\n }\n },\n\n _bindFilenameInputFocusInEvent: function() {\n var spec = qq.extend({}, this._filenameEditHandler());\n\n return new qq.FilenameInputFocusInHandler(spec);\n },\n\n _bindFilenameInputFocusEvent: function() {\n var spec = qq.extend({}, this._filenameEditHandler());\n\n return new qq.FilenameInputFocusHandler(spec);\n },\n\n _bindFilenameClickEvent: function() {\n var spec = qq.extend({}, this._filenameEditHandler());\n\n return new qq.FilenameClickHandler(spec);\n },\n\n _storeForLater: function(id) {\n this._parent.prototype._storeForLater.apply(this, arguments);\n this._templating.hideSpinner(id);\n },\n\n _onAllComplete: function(successful, failed) {\n this._parent.prototype._onAllComplete.apply(this, arguments);\n this._templating.resetTotalProgress();\n },\n\n _onSubmit: function(id, name) {\n var file = this.getFile(id);\n\n if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) {\n this._paramsStore.addReadOnly(id, {\n qqpath: file.qqPath\n });\n }\n\n this._parent.prototype._onSubmit.apply(this, arguments);\n this._addToList(id, name);\n },\n\n // The file item has been added to the DOM.\n _onSubmitted: function(id) {\n // If the edit filename feature is enabled, mark the filename element as \"editable\" and the associated edit icon\n if (this._isEditFilenameEnabled()) {\n this._templating.markFilenameEditable(id);\n this._templating.showEditIcon(id);\n\n // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input\n if (!this._focusinEventSupported) {\n this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id));\n }\n }\n },\n\n // Update the progress bar & percentage as the file is uploaded\n _onProgress: function(id, name, loaded, total) {\n this._parent.prototype._onProgress.apply(this, arguments);\n\n this._templating.updateProgress(id, loaded, total);\n\n if (total === 0 || Math.round(loaded / total * 100) === 100) {\n this._templating.hideCancel(id);\n this._templating.hidePause(id);\n this._templating.hideProgress(id);\n this._templating.setStatusText(id, this._options.text.waitingForResponse);\n\n // If ~last byte was sent, display total file size\n this._displayFileSize(id);\n }\n else {\n // If still uploading, display percentage - total size is actually the total request(s) size\n this._displayFileSize(id, loaded, total);\n }\n },\n\n _onTotalProgress: function(loaded, total) {\n this._parent.prototype._onTotalProgress.apply(this, arguments);\n this._templating.updateTotalProgress(loaded, total);\n },\n\n _onComplete: function(id, name, result, xhr) {\n var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments),\n templating = this._templating,\n fileContainer = templating.getFileContainer(id),\n self = this;\n\n function completeUpload(result) {\n // If this file is not represented in the templating module, perhaps it was hidden intentionally.\n // If so, don't perform any UI-related tasks related to this file.\n if (!fileContainer) {\n return;\n }\n\n templating.setStatusText(id);\n\n qq(fileContainer).removeClass(self._classes.retrying);\n templating.hideProgress(id);\n\n if (self.getUploads({id: id}).status !== qq.status.UPLOAD_FAILED) {\n templating.hideCancel(id);\n }\n templating.hideSpinner(id);\n\n if (result.success) {\n self._markFileAsSuccessful(id);\n }\n else {\n qq(fileContainer).addClass(self._classes.fail);\n templating.showCancel(id);\n\n if (templating.isRetryPossible() && !self._preventRetries[id]) {\n qq(fileContainer).addClass(self._classes.retryable);\n templating.showRetry(id);\n }\n self._controlFailureTextDisplay(id, result);\n }\n }\n\n // The parent may need to perform some async operation before we can accurately determine the status of the upload.\n if (parentRetVal instanceof qq.Promise) {\n parentRetVal.done(function(newResult) {\n completeUpload(newResult);\n });\n\n }\n else {\n completeUpload(result);\n }\n\n return parentRetVal;\n },\n\n _markFileAsSuccessful: function(id) {\n var templating = this._templating;\n\n if (this._isDeletePossible()) {\n templating.showDeleteButton(id);\n }\n\n qq(templating.getFileContainer(id)).addClass(this._classes.success);\n\n this._maybeUpdateThumbnail(id);\n },\n\n _onUploadPrep: function(id) {\n this._parent.prototype._onUploadPrep.apply(this, arguments);\n this._templating.showSpinner(id);\n },\n\n _onUpload: function(id, name) {\n var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments);\n\n this._templating.showSpinner(id);\n\n return parentRetVal;\n },\n\n _onUploadChunk: function(id, chunkData) {\n this._parent.prototype._onUploadChunk.apply(this, arguments);\n\n // Only display the pause button if we have finished uploading at least one chunk\n // & this file can be resumed\n if (chunkData.partIndex > 0 && this._handler.isResumable(id)) {\n this._templating.allowPause(id);\n }\n },\n\n _onCancel: function(id, name) {\n this._parent.prototype._onCancel.apply(this, arguments);\n this._removeFileItem(id);\n\n if (this._getNotFinished() === 0) {\n this._templating.resetTotalProgress();\n }\n },\n\n _onBeforeAutoRetry: function(id) {\n var retryNumForDisplay, maxAuto, retryNote;\n\n this._parent.prototype._onBeforeAutoRetry.apply(this, arguments);\n\n this._showCancelLink(id);\n\n if (this._options.retry.showAutoRetryNote) {\n retryNumForDisplay = this._autoRetries[id];\n maxAuto = this._options.retry.maxAutoAttempts;\n\n retryNote = this._options.retry.autoRetryNote.replace(/\\{retryNum\\}/g, retryNumForDisplay);\n retryNote = retryNote.replace(/\\{maxAuto\\}/g, maxAuto);\n\n this._templating.setStatusText(id, retryNote);\n qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying);\n }\n },\n\n //return false if we should not attempt the requested retry\n _onBeforeManualRetry: function(id) {\n if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) {\n this._templating.resetProgress(id);\n qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail);\n this._templating.setStatusText(id);\n this._templating.showSpinner(id);\n this._showCancelLink(id);\n return true;\n }\n else {\n qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable);\n this._templating.showRetry(id);\n return false;\n }\n },\n\n _onSubmitDelete: function(id) {\n var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this);\n\n this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback);\n },\n\n _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) {\n if (this._options.deleteFile.forceConfirm) {\n this._showDeleteConfirm.apply(this, arguments);\n }\n else {\n this._sendDeleteRequest.apply(this, arguments);\n }\n },\n\n _onDeleteComplete: function(id, xhr, isError) {\n this._parent.prototype._onDeleteComplete.apply(this, arguments);\n\n this._templating.hideSpinner(id);\n\n if (isError) {\n this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText);\n this._templating.showDeleteButton(id);\n }\n else {\n this._removeFileItem(id);\n }\n },\n\n _sendDeleteRequest: function(id, uuid, additionalMandatedParams) {\n this._templating.hideDeleteButton(id);\n this._templating.showSpinner(id);\n this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText);\n this._deleteHandler.sendDelete.apply(this, arguments);\n },\n\n _showDeleteConfirm: function(id, uuid, mandatedParams) {\n /*jshint -W004 */\n var fileName = this.getName(id),\n confirmMessage = this._options.deleteFile.confirmMessage.replace(/\\{filename\\}/g, fileName),\n uuid = this.getUuid(id),\n deleteRequestArgs = arguments,\n self = this,\n retVal;\n\n retVal = this._options.showConfirm(confirmMessage);\n\n if (qq.isGenericPromise(retVal)) {\n retVal.then(function() {\n self._sendDeleteRequest.apply(self, deleteRequestArgs);\n });\n }\n else if (retVal !== false) {\n self._sendDeleteRequest.apply(self, deleteRequestArgs);\n }\n },\n\n _addToList: function(id, name, canned) {\n var prependData,\n prependIndex = 0,\n dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled,\n record;\n\n if (this._options.display.prependFiles) {\n if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) {\n prependIndex = this._filesInBatchAddedToUi - 1;\n }\n\n prependData = {\n index: prependIndex\n };\n }\n\n if (!canned) {\n if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) {\n this._templating.disableCancel();\n }\n\n // Cancel all existing (previous) files and clear the list if this file is not part of\n // a scaled file group that has already been accepted, or if this file is not part of\n // a scaled file group at all.\n if (!this._options.multiple) {\n record = this.getUploads({id: id});\n\n this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId;\n\n if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) {\n this._handler.cancelAll();\n this._clearList();\n this._handledProxyGroup = null;\n }\n }\n }\n\n if (canned) {\n this._templating.addFileToCache(id, this._options.formatFileName(name), prependData, dontDisplay);\n this._templating.updateThumbnail(id, this._thumbnailUrls[id], true, this._options.thumbnails.customResizer);\n }\n else {\n this._templating.addFile(id, this._options.formatFileName(name), prependData, dontDisplay);\n this._templating.generatePreview(id, this.getFile(id), this._options.thumbnails.customResizer);\n }\n\n this._filesInBatchAddedToUi += 1;\n\n if (canned ||\n (this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading)) {\n\n this._displayFileSize(id);\n }\n },\n\n _clearList: function() {\n this._templating.clearFiles();\n this.clearStoredFiles();\n },\n\n _displayFileSize: function(id, loadedSize, totalSize) {\n var size = this.getSize(id),\n sizeForDisplay = this._formatSize(size);\n\n if (size >= 0) {\n if (loadedSize !== undefined && totalSize !== undefined) {\n sizeForDisplay = this._formatProgress(loadedSize, totalSize);\n }\n\n this._templating.updateSize(id, sizeForDisplay);\n }\n },\n\n _formatProgress: function(uploadedSize, totalSize) {\n var message = this._options.text.formatProgress;\n function r(name, replacement) { message = message.replace(name, replacement); }\n\n r(\"{percent}\", Math.round(uploadedSize / totalSize * 100));\n r(\"{total_size}\", this._formatSize(totalSize));\n return message;\n },\n\n _controlFailureTextDisplay: function(id, response) {\n var mode, responseProperty, failureReason;\n\n mode = this._options.failedUploadTextDisplay.mode;\n responseProperty = this._options.failedUploadTextDisplay.responseProperty;\n\n if (mode === \"custom\") {\n failureReason = response[responseProperty];\n if (!failureReason) {\n failureReason = this._options.text.failUpload;\n }\n\n this._templating.setStatusText(id, failureReason);\n\n if (this._options.failedUploadTextDisplay.enableTooltip) {\n this._showTooltip(id, failureReason);\n }\n }\n else if (mode === \"default\") {\n this._templating.setStatusText(id, this._options.text.failUpload);\n }\n else if (mode !== \"none\") {\n this.log(\"failedUploadTextDisplay.mode value of '\" + mode + \"' is not valid\", \"warn\");\n }\n },\n\n _showTooltip: function(id, text) {\n this._templating.getFileContainer(id).title = text;\n },\n\n _showCancelLink: function(id) {\n if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {\n this._templating.showCancel(id);\n }\n },\n\n _itemError: function(code, name, item) {\n var message = this._parent.prototype._itemError.apply(this, arguments);\n this._options.showMessage(message);\n },\n\n _batchError: function(message) {\n this._parent.prototype._batchError.apply(this, arguments);\n this._options.showMessage(message);\n },\n\n _setupPastePrompt: function() {\n var self = this;\n\n this._options.callbacks.onPasteReceived = function() {\n var message = self._options.paste.namePromptMessage,\n defaultVal = self._options.paste.defaultName;\n\n return self._options.showPrompt(message, defaultVal);\n };\n },\n\n _fileOrBlobRejected: function(id, name) {\n this._totalFilesInBatch -= 1;\n this._parent.prototype._fileOrBlobRejected.apply(this, arguments);\n },\n\n _prepareItemsForUpload: function(items, params, endpoint) {\n this._totalFilesInBatch = items.length;\n this._filesInBatchAddedToUi = 0;\n this._parent.prototype._prepareItemsForUpload.apply(this, arguments);\n },\n\n _maybeUpdateThumbnail: function(fileId) {\n var thumbnailUrl = this._thumbnailUrls[fileId],\n fileStatus = this.getUploads({id: fileId}).status;\n\n if (fileStatus !== qq.status.DELETED &&\n (thumbnailUrl ||\n this._options.thumbnails.placeholders.waitUntilResponse ||\n !qq.supportedFeatures.imagePreviews)) {\n\n // This will replace the \"waiting\" placeholder with a \"preview not available\" placeholder\n // if called with a null thumbnailUrl.\n this._templating.updateThumbnail(fileId, thumbnailUrl, this._options.thumbnails.customResizer);\n }\n },\n\n _addCannedFile: function(sessionData) {\n var id = this._parent.prototype._addCannedFile.apply(this, arguments);\n\n this._addToList(id, this.getName(id), true);\n this._templating.hideSpinner(id);\n this._templating.hideCancel(id);\n this._markFileAsSuccessful(id);\n\n return id;\n },\n\n _setSize: function(id, newSize) {\n this._parent.prototype._setSize.apply(this, arguments);\n\n this._templating.updateSize(id, this._formatSize(newSize));\n },\n\n _sessionRequestComplete: function() {\n this._templating.addCacheToDom();\n this._parent.prototype._sessionRequestComplete.apply(this, arguments);\n }\n };\n}());\n","/*globals qq */\n/**\n * This defines FineUploader mode, which is a default UI w/ drag & drop uploading.\n */\nqq.FineUploader = function(o, namespace) {\n \"use strict\";\n\n var self = this;\n\n // By default this should inherit instance data from FineUploaderBasic, but this can be overridden\n // if the (internal) caller defines a different parent. The parent is also used by\n // the private and public API functions that need to delegate to a parent function.\n this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic;\n this._parent.apply(this, arguments);\n\n // Options provided by FineUploader mode\n qq.extend(this._options, {\n element: null,\n\n button: null,\n\n listElement: null,\n\n dragAndDrop: {\n extraDropzones: [],\n reportDirectoryPaths: false\n },\n\n text: {\n formatProgress: \"{percent}% of {total_size}\",\n failUpload: \"Upload failed\",\n waitingForResponse: \"Processing...\",\n paused: \"Paused\"\n },\n\n template: \"qq-template\",\n\n classes: {\n retrying: \"qq-upload-retrying\",\n retryable: \"qq-upload-retryable\",\n success: \"qq-upload-success\",\n fail: \"qq-upload-fail\",\n editable: \"qq-editable\",\n hide: \"qq-hide\",\n dropActive: \"qq-upload-drop-area-active\"\n },\n\n failedUploadTextDisplay: {\n mode: \"default\", //default, custom, or none\n responseProperty: \"error\",\n enableTooltip: true\n },\n\n messages: {\n tooManyFilesError: \"You may only drop one file\",\n unsupportedBrowser: \"Unrecoverable error - this browser does not permit file uploading of any kind.\"\n },\n\n retry: {\n showAutoRetryNote: true,\n autoRetryNote: \"Retrying {retryNum}/{maxAuto}...\"\n },\n\n deleteFile: {\n forceConfirm: false,\n confirmMessage: \"Are you sure you want to delete {filename}?\",\n deletingStatusText: \"Deleting...\",\n deletingFailedText: \"Delete failed\"\n\n },\n\n display: {\n fileSizeOnSubmit: false,\n prependFiles: false\n },\n\n paste: {\n promptForName: false,\n namePromptMessage: \"Please name this image\"\n },\n\n thumbnails: {\n customResizer: null,\n maxCount: 0,\n placeholders: {\n waitUntilResponse: false,\n notAvailablePath: null,\n waitingPath: null\n },\n timeBetweenThumbs: 750\n },\n\n scaling: {\n hideScaled: false\n },\n\n showMessage: function(message) {\n if (self._templating.hasDialog(\"alert\")) {\n return self._templating.showDialog(\"alert\", message);\n }\n else {\n setTimeout(function() {\n window.alert(message);\n }, 0);\n }\n },\n\n showConfirm: function(message) {\n if (self._templating.hasDialog(\"confirm\")) {\n return self._templating.showDialog(\"confirm\", message);\n }\n else {\n return window.confirm(message);\n }\n },\n\n showPrompt: function(message, defaultValue) {\n if (self._templating.hasDialog(\"prompt\")) {\n return self._templating.showDialog(\"prompt\", message, defaultValue);\n }\n else {\n return window.prompt(message, defaultValue);\n }\n }\n }, true);\n\n // Replace any default options with user defined ones\n qq.extend(this._options, o, true);\n\n this._templating = new qq.Templating({\n log: qq.bind(this.log, this),\n templateIdOrEl: this._options.template,\n containerEl: this._options.element,\n fileContainerEl: this._options.listElement,\n button: this._options.button,\n imageGenerator: this._imageGenerator,\n classes: {\n hide: this._options.classes.hide,\n editable: this._options.classes.editable\n },\n limits: {\n maxThumbs: this._options.thumbnails.maxCount,\n timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs\n },\n placeholders: {\n waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse,\n thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath,\n waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath\n },\n text: this._options.text\n });\n\n if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {\n this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari);\n }\n else if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) {\n this._templating.renderFailure(this._options.messages.unsupportedBrowser);\n }\n else {\n this._wrapCallbacks();\n\n this._templating.render();\n\n this._classes = this._options.classes;\n\n if (!this._options.button && this._templating.getButton()) {\n this._defaultButtonId = this._createUploadButton({\n element: this._templating.getButton(),\n title: this._options.text.fileInputTitle\n }).getButtonId();\n }\n\n this._setupClickAndEditEventHandlers();\n\n if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) {\n this._dnd = this._setupDragAndDrop();\n }\n\n if (this._options.paste.targetElement && this._options.paste.promptForName) {\n if (qq.PasteSupport) {\n this._setupPastePrompt();\n }\n else {\n this.log(\"Paste support module not found.\", \"error\");\n }\n }\n\n this._totalFilesInBatch = 0;\n this._filesInBatchAddedToUi = 0;\n }\n};\n\n// Inherit the base public & private API methods\nqq.extend(qq.FineUploader.prototype, qq.basePublicApi);\nqq.extend(qq.FineUploader.prototype, qq.basePrivateApi);\n\n// Add the FineUploader/default UI public & private UI methods, which may override some base methods.\nqq.extend(qq.FineUploader.prototype, qq.uiPublicApi);\nqq.extend(qq.FineUploader.prototype, qq.uiPrivateApi);\n","/* globals qq */\n/* jshint -W065 */\n/**\n * Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least\n * a limited amount of control over the template elements after they are added to the DOM.\n * Wherever possible, this module asserts total control over template elements present in the DOM.\n *\n * @param spec Specification object used to control various templating behaviors\n * @constructor\n */\nqq.Templating = function(spec) {\n \"use strict\";\n\n var FILE_ID_ATTR = \"qq-file-id\",\n FILE_CLASS_PREFIX = \"qq-file-id-\",\n THUMBNAIL_MAX_SIZE_ATTR = \"qq-max-size\",\n THUMBNAIL_SERVER_SCALE_ATTR = \"qq-server-scale\",\n // This variable is duplicated in the DnD module since it can function as a standalone as well\n HIDE_DROPZONE_ATTR = \"qq-hide-dropzone\",\n DROPZPONE_TEXT_ATTR = \"qq-drop-area-text\",\n IN_PROGRESS_CLASS = \"qq-in-progress\",\n HIDDEN_FOREVER_CLASS = \"qq-hidden-forever\",\n fileBatch = {\n content: document.createDocumentFragment(),\n map: {}\n },\n isCancelDisabled = false,\n generatedThumbnails = 0,\n thumbnailQueueMonitorRunning = false,\n thumbGenerationQueue = [],\n thumbnailMaxSize = -1,\n options = {\n log: null,\n limits: {\n maxThumbs: 0,\n timeBetweenThumbs: 750\n },\n templateIdOrEl: \"qq-template\",\n containerEl: null,\n fileContainerEl: null,\n button: null,\n imageGenerator: null,\n classes: {\n hide: \"qq-hide\",\n editable: \"qq-editable\"\n },\n placeholders: {\n waitUntilUpdate: false,\n thumbnailNotAvailable: null,\n waitingForThumbnail: null\n },\n text: {\n paused: \"Paused\"\n }\n },\n selectorClasses = {\n button: \"qq-upload-button-selector\",\n alertDialog: \"qq-alert-dialog-selector\",\n dialogCancelButton: \"qq-cancel-button-selector\",\n confirmDialog: \"qq-confirm-dialog-selector\",\n dialogMessage: \"qq-dialog-message-selector\",\n dialogOkButton: \"qq-ok-button-selector\",\n promptDialog: \"qq-prompt-dialog-selector\",\n uploader: \"qq-uploader-selector\",\n drop: \"qq-upload-drop-area-selector\",\n list: \"qq-upload-list-selector\",\n progressBarContainer: \"qq-progress-bar-container-selector\",\n progressBar: \"qq-progress-bar-selector\",\n totalProgressBarContainer: \"qq-total-progress-bar-container-selector\",\n totalProgressBar: \"qq-total-progress-bar-selector\",\n file: \"qq-upload-file-selector\",\n spinner: \"qq-upload-spinner-selector\",\n size: \"qq-upload-size-selector\",\n cancel: \"qq-upload-cancel-selector\",\n pause: \"qq-upload-pause-selector\",\n continueButton: \"qq-upload-continue-selector\",\n deleteButton: \"qq-upload-delete-selector\",\n retry: \"qq-upload-retry-selector\",\n statusText: \"qq-upload-status-text-selector\",\n editFilenameInput: \"qq-edit-filename-selector\",\n editNameIcon: \"qq-edit-filename-icon-selector\",\n dropText: \"qq-upload-drop-area-text-selector\",\n dropProcessing: \"qq-drop-processing-selector\",\n dropProcessingSpinner: \"qq-drop-processing-spinner-selector\",\n thumbnail: \"qq-thumbnail-selector\"\n },\n previewGeneration = {},\n cachedThumbnailNotAvailableImg = new qq.Promise(),\n cachedWaitingForThumbnailImg = new qq.Promise(),\n log,\n isEditElementsExist,\n isRetryElementExist,\n templateDom,\n container,\n fileList,\n showThumbnails,\n serverScale,\n\n // During initialization of the templating module we should cache any\n // placeholder images so we can quickly swap them into the file list on demand.\n // Any placeholder images that cannot be loaded/found are simply ignored.\n cacheThumbnailPlaceholders = function() {\n var notAvailableUrl = options.placeholders.thumbnailNotAvailable,\n waitingUrl = options.placeholders.waitingForThumbnail,\n spec = {\n maxSize: thumbnailMaxSize,\n scale: serverScale\n };\n\n if (showThumbnails) {\n if (notAvailableUrl) {\n options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then(\n function(updatedImg) {\n cachedThumbnailNotAvailableImg.success(updatedImg);\n },\n function() {\n cachedThumbnailNotAvailableImg.failure();\n log(\"Problem loading 'not available' placeholder image at \" + notAvailableUrl, \"error\");\n }\n );\n }\n else {\n cachedThumbnailNotAvailableImg.failure();\n }\n\n if (waitingUrl) {\n options.imageGenerator.generate(waitingUrl, new Image(), spec).then(\n function(updatedImg) {\n cachedWaitingForThumbnailImg.success(updatedImg);\n },\n function() {\n cachedWaitingForThumbnailImg.failure();\n log(\"Problem loading 'waiting for thumbnail' placeholder image at \" + waitingUrl, \"error\");\n }\n );\n }\n else {\n cachedWaitingForThumbnailImg.failure();\n }\n }\n },\n\n // Displays a \"waiting for thumbnail\" type placeholder image\n // iff we were able to load it during initialization of the templating module.\n displayWaitingImg = function(thumbnail) {\n var waitingImgPlacement = new qq.Promise();\n\n cachedWaitingForThumbnailImg.then(function(img) {\n maybeScalePlaceholderViaCss(img, thumbnail);\n /* jshint eqnull:true */\n if (!thumbnail.src) {\n thumbnail.src = img.src;\n thumbnail.onload = function() {\n thumbnail.onload = null;\n show(thumbnail);\n waitingImgPlacement.success();\n };\n }\n else {\n waitingImgPlacement.success();\n }\n }, function() {\n // In some browsers (such as IE9 and older) an img w/out a src attribute\n // are displayed as \"broken\" images, so we should just hide the img tag\n // if we aren't going to display the \"waiting\" placeholder.\n hide(thumbnail);\n waitingImgPlacement.success();\n });\n\n return waitingImgPlacement;\n },\n\n generateNewPreview = function(id, blob, spec) {\n var thumbnail = getThumbnail(id);\n\n log(\"Generating new thumbnail for \" + id);\n blob.qqThumbnailId = id;\n\n return options.imageGenerator.generate(blob, thumbnail, spec).then(\n function() {\n generatedThumbnails++;\n show(thumbnail);\n previewGeneration[id].success();\n },\n function() {\n previewGeneration[id].failure();\n\n // Display the \"not available\" placeholder img only if we are\n // not expecting a thumbnail at a later point, such as in a server response.\n if (!options.placeholders.waitUntilUpdate) {\n maybeSetDisplayNotAvailableImg(id, thumbnail);\n }\n });\n },\n\n generateNextQueuedPreview = function() {\n if (thumbGenerationQueue.length) {\n thumbnailQueueMonitorRunning = true;\n\n var queuedThumbRequest = thumbGenerationQueue.shift();\n\n if (queuedThumbRequest.update) {\n processUpdateQueuedPreviewRequest(queuedThumbRequest);\n }\n else {\n processNewQueuedPreviewRequest(queuedThumbRequest);\n }\n }\n else {\n thumbnailQueueMonitorRunning = false;\n }\n },\n\n getCancel = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.cancel);\n },\n\n getContinue = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.continueButton);\n },\n\n getDialog = function(type) {\n return getTemplateEl(container, selectorClasses[type + \"Dialog\"]);\n },\n\n getDelete = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.deleteButton);\n },\n\n getDropProcessing = function() {\n return getTemplateEl(container, selectorClasses.dropProcessing);\n },\n\n getEditIcon = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.editNameIcon);\n },\n\n getFile = function(id) {\n return fileBatch.map[id] || qq(fileList).getFirstByClass(FILE_CLASS_PREFIX + id);\n },\n\n getFilename = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.file);\n },\n\n getPause = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.pause);\n },\n\n getProgress = function(id) {\n /* jshint eqnull:true */\n // Total progress bar\n if (id == null) {\n return getTemplateEl(container, selectorClasses.totalProgressBarContainer) ||\n getTemplateEl(container, selectorClasses.totalProgressBar);\n }\n\n // Per-file progress bar\n return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) ||\n getTemplateEl(getFile(id), selectorClasses.progressBar);\n },\n\n getRetry = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.retry);\n },\n\n getSize = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.size);\n },\n\n getSpinner = function(id) {\n return getTemplateEl(getFile(id), selectorClasses.spinner);\n },\n\n getTemplateEl = function(context, cssClass) {\n return context && qq(context).getFirstByClass(cssClass);\n },\n\n getThumbnail = function(id) {\n return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail);\n },\n\n hide = function(el) {\n el && qq(el).addClass(options.classes.hide);\n },\n\n // Ensures a placeholder image does not exceed any max size specified\n // via `style` attribute properties iff <canvas> was not used to scale\n // the placeholder AND the target <img> doesn't already have these `style` attribute properties set.\n maybeScalePlaceholderViaCss = function(placeholder, thumbnail) {\n var maxWidth = placeholder.style.maxWidth,\n maxHeight = placeholder.style.maxHeight;\n\n if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) {\n qq(thumbnail).css({\n maxWidth: maxWidth,\n maxHeight: maxHeight\n });\n }\n },\n\n // Displays a \"thumbnail not available\" type placeholder image\n // iff we were able to load this placeholder during initialization\n // of the templating module or after preview generation has failed.\n maybeSetDisplayNotAvailableImg = function(id, thumbnail) {\n var previewing = previewGeneration[id] || new qq.Promise().failure(),\n notAvailableImgPlacement = new qq.Promise();\n\n cachedThumbnailNotAvailableImg.then(function(img) {\n previewing.then(\n function() {\n notAvailableImgPlacement.success();\n },\n function() {\n maybeScalePlaceholderViaCss(img, thumbnail);\n\n thumbnail.onload = function() {\n thumbnail.onload = null;\n notAvailableImgPlacement.success();\n };\n\n thumbnail.src = img.src;\n show(thumbnail);\n }\n );\n });\n\n return notAvailableImgPlacement;\n },\n\n /**\n * Grabs the HTML from the script tag holding the template markup. This function will also adjust\n * some internally-tracked state variables based on the contents of the template.\n * The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported)\n * are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed.\n *\n * @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates\n */\n parseAndGetTemplate = function() {\n var scriptEl,\n scriptHtml,\n fileListNode,\n tempTemplateEl,\n fileListEl,\n defaultButton,\n dropArea,\n thumbnail,\n dropProcessing,\n dropTextEl,\n uploaderEl;\n\n log(\"Parsing template\");\n\n /*jshint -W116*/\n if (options.templateIdOrEl == null) {\n throw new Error(\"You MUST specify either a template element or ID!\");\n }\n\n // Grab the contents of the script tag holding the template.\n if (qq.isString(options.templateIdOrEl)) {\n scriptEl = document.getElementById(options.templateIdOrEl);\n\n if (scriptEl === null) {\n throw new Error(qq.format(\"Cannot find template script at ID '{}'!\", options.templateIdOrEl));\n }\n\n scriptHtml = scriptEl.innerHTML;\n }\n else {\n if (options.templateIdOrEl.innerHTML === undefined) {\n throw new Error(\"You have specified an invalid value for the template option! \" +\n \"It must be an ID or an Element.\");\n }\n\n scriptHtml = options.templateIdOrEl.innerHTML;\n }\n\n scriptHtml = qq.trimStr(scriptHtml);\n tempTemplateEl = document.createElement(\"div\");\n tempTemplateEl.appendChild(qq.toElement(scriptHtml));\n uploaderEl = qq(tempTemplateEl).getFirstByClass(selectorClasses.uploader);\n\n // Don't include the default template button in the DOM\n // if an alternate button container has been specified.\n if (options.button) {\n defaultButton = qq(tempTemplateEl).getFirstByClass(selectorClasses.button);\n if (defaultButton) {\n qq(defaultButton).remove();\n }\n }\n\n // Omit the drop processing element from the DOM if DnD is not supported by the UA,\n // or the drag and drop module is not found.\n // NOTE: We are consciously not removing the drop zone if the UA doesn't support DnD\n // to support layouts where the drop zone is also a container for visible elements,\n // such as the file list.\n if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) {\n dropProcessing = qq(tempTemplateEl).getFirstByClass(selectorClasses.dropProcessing);\n if (dropProcessing) {\n qq(dropProcessing).remove();\n }\n }\n\n dropArea = qq(tempTemplateEl).getFirstByClass(selectorClasses.drop);\n\n // If DnD is not available then remove\n // it from the DOM as well.\n if (dropArea && !qq.DragAndDrop) {\n log(\"DnD module unavailable.\", \"info\");\n qq(dropArea).remove();\n }\n\n if (!qq.supportedFeatures.fileDrop) {\n // don't display any \"drop files to upload\" background text\n uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);\n\n if (dropArea && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) {\n // If there is a drop area defined in the template, and the current UA doesn't support DnD,\n // and the drop area is marked as \"hide before enter\", ensure it is hidden as the DnD module\n // will not do this (since we will not be loading the DnD module)\n qq(dropArea).css({\n display: \"none\"\n });\n }\n }\n else if (qq(uploaderEl).hasAttribute(DROPZPONE_TEXT_ATTR) && dropArea) {\n dropTextEl = qq(dropArea).getFirstByClass(selectorClasses.dropText);\n dropTextEl && qq(dropTextEl).remove();\n }\n\n // Ensure the `showThumbnails` flag is only set if the thumbnail element\n // is present in the template AND the current UA is capable of generating client-side previews.\n thumbnail = qq(tempTemplateEl).getFirstByClass(selectorClasses.thumbnail);\n if (!showThumbnails) {\n thumbnail && qq(thumbnail).remove();\n }\n else if (thumbnail) {\n thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR));\n // Only enforce max size if the attr value is non-zero\n thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null;\n\n serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR);\n }\n showThumbnails = showThumbnails && thumbnail;\n\n isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0;\n isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0;\n\n fileListNode = qq(tempTemplateEl).getFirstByClass(selectorClasses.list);\n /*jshint -W116*/\n if (fileListNode == null) {\n throw new Error(\"Could not find the file list container in the template!\");\n }\n\n fileListEl = fileListNode.children[0].cloneNode(true);\n fileListNode.innerHTML = \"\";\n\n // We must call `createElement` in IE8 in order to target and hide any <dialog> via CSS\n if (tempTemplateEl.getElementsByTagName(\"DIALOG\").length) {\n document.createElement(\"dialog\");\n }\n\n log(\"Template parsing complete\");\n\n return {\n template: tempTemplateEl,\n fileTemplate: fileListEl\n };\n },\n\n prependFile = function(el, index, fileList) {\n var parentEl = fileList,\n beforeEl = parentEl.firstChild;\n\n if (index > 0) {\n beforeEl = qq(parentEl).children()[index].nextSibling;\n\n }\n\n parentEl.insertBefore(el, beforeEl);\n },\n\n processNewQueuedPreviewRequest = function(queuedThumbRequest) {\n var id = queuedThumbRequest.id,\n optFileOrBlob = queuedThumbRequest.optFileOrBlob,\n relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId,\n thumbnail = getThumbnail(id),\n spec = {\n customResizeFunction: queuedThumbRequest.customResizeFunction,\n maxSize: thumbnailMaxSize,\n orient: true,\n scale: true\n };\n\n if (qq.supportedFeatures.imagePreviews) {\n if (thumbnail) {\n if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {\n maybeSetDisplayNotAvailableImg(id, thumbnail);\n generateNextQueuedPreview();\n }\n else {\n displayWaitingImg(thumbnail).done(function() {\n previewGeneration[id] = new qq.Promise();\n\n previewGeneration[id].done(function() {\n setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);\n });\n\n /* jshint eqnull: true */\n // If we've already generated an <img> for this file, use the one that exists,\n // don't waste resources generating a new one.\n if (relatedThumbnailId != null) {\n useCachedPreview(id, relatedThumbnailId);\n }\n else {\n generateNewPreview(id, optFileOrBlob, spec);\n }\n });\n }\n }\n // File element in template may have been removed, so move on to next item in queue\n else {\n generateNextQueuedPreview();\n }\n }\n else if (thumbnail) {\n displayWaitingImg(thumbnail);\n generateNextQueuedPreview();\n }\n },\n\n processUpdateQueuedPreviewRequest = function(queuedThumbRequest) {\n var id = queuedThumbRequest.id,\n thumbnailUrl = queuedThumbRequest.thumbnailUrl,\n showWaitingImg = queuedThumbRequest.showWaitingImg,\n thumbnail = getThumbnail(id),\n spec = {\n customResizeFunction: queuedThumbRequest.customResizeFunction,\n scale: serverScale,\n maxSize: thumbnailMaxSize\n };\n\n if (thumbnail) {\n if (thumbnailUrl) {\n if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {\n maybeSetDisplayNotAvailableImg(id, thumbnail);\n generateNextQueuedPreview();\n }\n else {\n if (showWaitingImg) {\n displayWaitingImg(thumbnail);\n }\n\n return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then(\n function() {\n show(thumbnail);\n generatedThumbnails++;\n setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);\n },\n\n function() {\n maybeSetDisplayNotAvailableImg(id, thumbnail);\n setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);\n }\n );\n }\n }\n else {\n maybeSetDisplayNotAvailableImg(id, thumbnail);\n generateNextQueuedPreview();\n }\n }\n },\n\n setProgressBarWidth = function(id, percent) {\n var bar = getProgress(id),\n /* jshint eqnull:true */\n progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar;\n\n if (bar && !qq(bar).hasClass(progressBarSelector)) {\n bar = qq(bar).getFirstByClass(progressBarSelector);\n }\n\n if (bar) {\n qq(bar).css({width: percent + \"%\"});\n bar.setAttribute(\"aria-valuenow\", percent);\n }\n },\n\n show = function(el) {\n el && qq(el).removeClass(options.classes.hide);\n },\n\n useCachedPreview = function(targetThumbnailId, cachedThumbnailId) {\n var targetThumbnail = getThumbnail(targetThumbnailId),\n cachedThumbnail = getThumbnail(cachedThumbnailId);\n\n log(qq.format(\"ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.\", targetThumbnailId, cachedThumbnailId, cachedThumbnailId));\n\n // Generation of the related thumbnail may still be in progress, so, wait until it is done.\n previewGeneration[cachedThumbnailId].then(function() {\n generatedThumbnails++;\n previewGeneration[targetThumbnailId].success();\n log(qq.format(\"Now using previously generated thumbnail created for ID {} on ID {}.\", cachedThumbnailId, targetThumbnailId));\n targetThumbnail.src = cachedThumbnail.src;\n show(targetThumbnail);\n },\n function() {\n previewGeneration[targetThumbnailId].failure();\n if (!options.placeholders.waitUntilUpdate) {\n maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumbnail);\n }\n });\n };\n\n qq.extend(options, spec);\n log = options.log;\n\n // No need to worry about conserving CPU or memory on older browsers,\n // since there is no ability to preview, and thumbnail display is primitive and quick.\n if (!qq.supportedFeatures.imagePreviews) {\n options.limits.timeBetweenThumbs = 0;\n options.limits.maxThumbs = 0;\n }\n\n container = options.containerEl;\n showThumbnails = options.imageGenerator !== undefined;\n templateDom = parseAndGetTemplate();\n\n cacheThumbnailPlaceholders();\n\n qq.extend(this, {\n render: function() {\n log(\"Rendering template in DOM.\");\n\n generatedThumbnails = 0;\n\n container.appendChild(templateDom.template.cloneNode(true));\n hide(getDropProcessing());\n this.hideTotalProgress();\n fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list);\n\n log(\"Template rendering complete\");\n },\n\n renderFailure: function(message) {\n var cantRenderEl = qq.toElement(message);\n container.innerHTML = \"\";\n container.appendChild(cantRenderEl);\n },\n\n reset: function() {\n container.innerHTML = \"\";\n this.render();\n },\n\n clearFiles: function() {\n fileList.innerHTML = \"\";\n },\n\n disableCancel: function() {\n isCancelDisabled = true;\n },\n\n addFile: function(id, name, prependInfo, hideForever, batch) {\n var fileEl = templateDom.fileTemplate.cloneNode(true),\n fileNameEl = getTemplateEl(fileEl, selectorClasses.file),\n uploaderEl = getTemplateEl(container, selectorClasses.uploader),\n fileContainer = batch ? fileBatch.content : fileList,\n thumb;\n\n if (batch) {\n fileBatch.map[id] = fileEl;\n }\n\n qq(fileEl).addClass(FILE_CLASS_PREFIX + id);\n uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);\n\n if (fileNameEl) {\n qq(fileNameEl).setText(name);\n fileNameEl.setAttribute(\"title\", name);\n }\n\n fileEl.setAttribute(FILE_ID_ATTR, id);\n\n if (prependInfo) {\n prependFile(fileEl, prependInfo.index, fileContainer);\n }\n else {\n fileContainer.appendChild(fileEl);\n }\n\n if (hideForever) {\n fileEl.style.display = \"none\";\n qq(fileEl).addClass(HIDDEN_FOREVER_CLASS);\n }\n else {\n hide(getProgress(id));\n hide(getSize(id));\n hide(getDelete(id));\n hide(getRetry(id));\n hide(getPause(id));\n hide(getContinue(id));\n\n if (isCancelDisabled) {\n this.hideCancel(id);\n }\n\n thumb = getThumbnail(id);\n if (thumb && !thumb.src) {\n cachedWaitingForThumbnailImg.then(function(waitingImg) {\n thumb.src = waitingImg.src;\n if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) {\n qq(thumb).css({\n maxHeight: waitingImg.style.maxHeight,\n maxWidth: waitingImg.style.maxWidth\n });\n }\n\n show(thumb);\n });\n }\n }\n },\n\n addFileToCache: function(id, name, prependInfo, hideForever) {\n this.addFile(id, name, prependInfo, hideForever, true);\n },\n\n addCacheToDom: function() {\n fileList.appendChild(fileBatch.content);\n fileBatch.content = document.createDocumentFragment();\n fileBatch.map = {};\n },\n\n removeFile: function(id) {\n qq(getFile(id)).remove();\n },\n\n getFileId: function(el) {\n var currentNode = el;\n\n if (currentNode) {\n /*jshint -W116*/\n while (currentNode.getAttribute(FILE_ID_ATTR) == null) {\n currentNode = currentNode.parentNode;\n }\n\n return parseInt(currentNode.getAttribute(FILE_ID_ATTR));\n }\n },\n\n getFileList: function() {\n return fileList;\n },\n\n markFilenameEditable: function(id) {\n var filename = getFilename(id);\n\n filename && qq(filename).addClass(options.classes.editable);\n },\n\n updateFilename: function(id, name) {\n var filenameEl = getFilename(id);\n\n if (filenameEl) {\n qq(filenameEl).setText(name);\n filenameEl.setAttribute(\"title\", name);\n }\n },\n\n hideFilename: function(id) {\n hide(getFilename(id));\n },\n\n showFilename: function(id) {\n show(getFilename(id));\n },\n\n isFileName: function(el) {\n return qq(el).hasClass(selectorClasses.file);\n },\n\n getButton: function() {\n return options.button || getTemplateEl(container, selectorClasses.button);\n },\n\n hideDropProcessing: function() {\n hide(getDropProcessing());\n },\n\n showDropProcessing: function() {\n show(getDropProcessing());\n },\n\n getDropZone: function() {\n return getTemplateEl(container, selectorClasses.drop);\n },\n\n isEditFilenamePossible: function() {\n return isEditElementsExist;\n },\n\n hideRetry: function(id) {\n hide(getRetry(id));\n },\n\n isRetryPossible: function() {\n return isRetryElementExist;\n },\n\n showRetry: function(id) {\n show(getRetry(id));\n },\n\n getFileContainer: function(id) {\n return getFile(id);\n },\n\n showEditIcon: function(id) {\n var icon = getEditIcon(id);\n\n icon && qq(icon).addClass(options.classes.editable);\n },\n\n isHiddenForever: function(id) {\n return qq(getFile(id)).hasClass(HIDDEN_FOREVER_CLASS);\n },\n\n hideEditIcon: function(id) {\n var icon = getEditIcon(id);\n\n icon && qq(icon).removeClass(options.classes.editable);\n },\n\n isEditIcon: function(el) {\n return qq(el).hasClass(selectorClasses.editNameIcon, true);\n },\n\n getEditInput: function(id) {\n return getTemplateEl(getFile(id), selectorClasses.editFilenameInput);\n },\n\n isEditInput: function(el) {\n return qq(el).hasClass(selectorClasses.editFilenameInput, true);\n },\n\n updateProgress: function(id, loaded, total) {\n var bar = getProgress(id),\n percent;\n\n if (bar && total > 0) {\n percent = Math.round(loaded / total * 100);\n\n if (percent === 100) {\n hide(bar);\n }\n else {\n show(bar);\n }\n\n setProgressBarWidth(id, percent);\n }\n },\n\n updateTotalProgress: function(loaded, total) {\n this.updateProgress(null, loaded, total);\n },\n\n hideProgress: function(id) {\n var bar = getProgress(id);\n\n bar && hide(bar);\n },\n\n hideTotalProgress: function() {\n this.hideProgress();\n },\n\n resetProgress: function(id) {\n setProgressBarWidth(id, 0);\n this.hideTotalProgress(id);\n },\n\n resetTotalProgress: function() {\n this.resetProgress();\n },\n\n showCancel: function(id) {\n if (!isCancelDisabled) {\n var cancel = getCancel(id);\n\n cancel && qq(cancel).removeClass(options.classes.hide);\n }\n },\n\n hideCancel: function(id) {\n hide(getCancel(id));\n },\n\n isCancel: function(el) {\n return qq(el).hasClass(selectorClasses.cancel, true);\n },\n\n allowPause: function(id) {\n show(getPause(id));\n hide(getContinue(id));\n },\n\n uploadPaused: function(id) {\n this.setStatusText(id, options.text.paused);\n this.allowContinueButton(id);\n hide(getSpinner(id));\n },\n\n hidePause: function(id) {\n hide(getPause(id));\n },\n\n isPause: function(el) {\n return qq(el).hasClass(selectorClasses.pause, true);\n },\n\n isContinueButton: function(el) {\n return qq(el).hasClass(selectorClasses.continueButton, true);\n },\n\n allowContinueButton: function(id) {\n show(getContinue(id));\n hide(getPause(id));\n },\n\n uploadContinued: function(id) {\n this.setStatusText(id, \"\");\n this.allowPause(id);\n show(getSpinner(id));\n },\n\n showDeleteButton: function(id) {\n show(getDelete(id));\n },\n\n hideDeleteButton: function(id) {\n hide(getDelete(id));\n },\n\n isDeleteButton: function(el) {\n return qq(el).hasClass(selectorClasses.deleteButton, true);\n },\n\n isRetry: function(el) {\n return qq(el).hasClass(selectorClasses.retry, true);\n },\n\n updateSize: function(id, text) {\n var size = getSize(id);\n\n if (size) {\n show(size);\n qq(size).setText(text);\n }\n },\n\n setStatusText: function(id, text) {\n var textEl = getTemplateEl(getFile(id), selectorClasses.statusText);\n\n if (textEl) {\n /*jshint -W116*/\n if (text == null) {\n qq(textEl).clearText();\n }\n else {\n qq(textEl).setText(text);\n }\n }\n },\n\n hideSpinner: function(id) {\n qq(getFile(id)).removeClass(IN_PROGRESS_CLASS);\n hide(getSpinner(id));\n },\n\n showSpinner: function(id) {\n qq(getFile(id)).addClass(IN_PROGRESS_CLASS);\n show(getSpinner(id));\n },\n\n generatePreview: function(id, optFileOrBlob, customResizeFunction) {\n if (!this.isHiddenForever(id)) {\n thumbGenerationQueue.push({id: id, customResizeFunction: customResizeFunction, optFileOrBlob: optFileOrBlob});\n !thumbnailQueueMonitorRunning && generateNextQueuedPreview();\n }\n },\n\n updateThumbnail: function(id, thumbnailUrl, showWaitingImg, customResizeFunction) {\n if (!this.isHiddenForever(id)) {\n thumbGenerationQueue.push({customResizeFunction: customResizeFunction, update: true, id: id, thumbnailUrl: thumbnailUrl, showWaitingImg: showWaitingImg});\n !thumbnailQueueMonitorRunning && generateNextQueuedPreview();\n }\n },\n\n hasDialog: function(type) {\n return qq.supportedFeatures.dialogElement && !!getDialog(type);\n },\n\n showDialog: function(type, message, defaultValue) {\n var dialog = getDialog(type),\n messageEl = getTemplateEl(dialog, selectorClasses.dialogMessage),\n inputEl = dialog.getElementsByTagName(\"INPUT\")[0],\n cancelBtn = getTemplateEl(dialog, selectorClasses.dialogCancelButton),\n okBtn = getTemplateEl(dialog, selectorClasses.dialogOkButton),\n promise = new qq.Promise(),\n\n closeHandler = function() {\n cancelBtn.removeEventListener(\"click\", cancelClickHandler);\n okBtn && okBtn.removeEventListener(\"click\", okClickHandler);\n promise.failure();\n },\n\n cancelClickHandler = function() {\n cancelBtn.removeEventListener(\"click\", cancelClickHandler);\n dialog.close();\n },\n\n okClickHandler = function() {\n dialog.removeEventListener(\"close\", closeHandler);\n okBtn.removeEventListener(\"click\", okClickHandler);\n dialog.close();\n\n promise.success(inputEl && inputEl.value);\n };\n\n dialog.addEventListener(\"close\", closeHandler);\n cancelBtn.addEventListener(\"click\", cancelClickHandler);\n okBtn && okBtn.addEventListener(\"click\", okClickHandler);\n\n if (inputEl) {\n inputEl.value = defaultValue;\n }\n messageEl.textContent = message;\n\n dialog.showModal();\n\n return promise;\n }\n });\n};\n","/*globals qq */\n// Base handler for UI (FineUploader mode) events.\n// Some more specific handlers inherit from this one.\nqq.UiEventHandler = function(s, protectedApi) {\n \"use strict\";\n\n var disposer = new qq.DisposeSupport(),\n spec = {\n eventType: \"click\",\n attachTo: null,\n onHandled: function(target, event) {}\n };\n\n // This makes up the \"public\" API methods that will be accessible\n // to instances constructing a base or child handler\n qq.extend(this, {\n addHandler: function(element) {\n addHandler(element);\n },\n\n dispose: function() {\n disposer.dispose();\n }\n });\n\n function addHandler(element) {\n disposer.attach(element, spec.eventType, function(event) {\n // Only in IE: the `event` is a property of the `window`.\n event = event || window.event;\n\n // On older browsers, we must check the `srcElement` instead of the `target`.\n var target = event.target || event.srcElement;\n\n spec.onHandled(target, event);\n });\n }\n\n // These make up the \"protected\" API methods that children of this base handler will utilize.\n qq.extend(protectedApi, {\n getFileIdFromItem: function(item) {\n return item.qqFileId;\n },\n\n getDisposeSupport: function() {\n return disposer;\n }\n });\n\n qq.extend(spec, s);\n\n if (spec.attachTo) {\n addHandler(spec.attachTo);\n }\n};\n","/* global qq */\nqq.FileButtonsClickHandler = function(s) {\n \"use strict\";\n\n var inheritedInternalApi = {},\n spec = {\n templating: null,\n log: function(message, lvl) {},\n onDeleteFile: function(fileId) {},\n onCancel: function(fileId) {},\n onRetry: function(fileId) {},\n onPause: function(fileId) {},\n onContinue: function(fileId) {},\n onGetName: function(fileId) {}\n },\n buttonHandlers = {\n cancel: function(id) { spec.onCancel(id); },\n retry: function(id) { spec.onRetry(id); },\n deleteButton: function(id) { spec.onDeleteFile(id); },\n pause: function(id) { spec.onPause(id); },\n continueButton: function(id) { spec.onContinue(id); }\n };\n\n function examineEvent(target, event) {\n qq.each(buttonHandlers, function(buttonType, handler) {\n var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1),\n fileId;\n\n if (spec.templating[\"is\" + firstLetterCapButtonType](target)) {\n fileId = spec.templating.getFileId(target);\n qq.preventDefault(event);\n spec.log(qq.format(\"Detected valid file button click event on file '{}', ID: {}.\", spec.onGetName(fileId), fileId));\n handler(fileId);\n return false;\n }\n });\n }\n\n qq.extend(spec, s);\n\n spec.eventType = \"click\";\n spec.onHandled = examineEvent;\n spec.attachTo = spec.templating.getFileList();\n\n qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));\n};\n","/*globals qq */\n// Child of FilenameEditHandler. Used to detect click events on filename display elements.\nqq.FilenameClickHandler = function(s) {\n \"use strict\";\n\n var inheritedInternalApi = {},\n spec = {\n templating: null,\n log: function(message, lvl) {},\n classes: {\n file: \"qq-upload-file\",\n editNameIcon: \"qq-edit-filename-icon\"\n },\n onGetUploadStatus: function(fileId) {},\n onGetName: function(fileId) {}\n };\n\n qq.extend(spec, s);\n\n // This will be called by the parent handler when a `click` event is received on the list element.\n function examineEvent(target, event) {\n if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) {\n var fileId = spec.templating.getFileId(target),\n status = spec.onGetUploadStatus(fileId);\n\n // We only allow users to change filenames of files that have been submitted but not yet uploaded.\n if (status === qq.status.SUBMITTED) {\n spec.log(qq.format(\"Detected valid filename click event on file '{}', ID: {}.\", spec.onGetName(fileId), fileId));\n qq.preventDefault(event);\n\n inheritedInternalApi.handleFilenameEdit(fileId, target, true);\n }\n }\n }\n\n spec.eventType = \"click\";\n spec.onHandled = examineEvent;\n\n qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));\n};\n","/*globals qq */\n// Child of FilenameEditHandler. Used to detect focusin events on file edit input elements.\nqq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) {\n \"use strict\";\n\n var spec = {\n templating: null,\n onGetUploadStatus: function(fileId) {},\n log: function(message, lvl) {}\n };\n\n if (!inheritedInternalApi) {\n inheritedInternalApi = {};\n }\n\n // This will be called by the parent handler when a `focusin` event is received on the list element.\n function handleInputFocus(target, event) {\n if (spec.templating.isEditInput(target)) {\n var fileId = spec.templating.getFileId(target),\n status = spec.onGetUploadStatus(fileId);\n\n if (status === qq.status.SUBMITTED) {\n spec.log(qq.format(\"Detected valid filename input focus event on file '{}', ID: {}.\", spec.onGetName(fileId), fileId));\n inheritedInternalApi.handleFilenameEdit(fileId, target);\n }\n }\n }\n\n spec.eventType = \"focusin\";\n spec.onHandled = handleInputFocus;\n\n qq.extend(spec, s);\n qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));\n};\n","/*globals qq */\n/**\n * Child of FilenameInputFocusInHandler. Used to detect focus events on file edit input elements. This child module is only\n * needed for UAs that do not support the focusin event. Currently, only Firefox lacks this event.\n *\n * @param spec Overrides for default specifications\n */\nqq.FilenameInputFocusHandler = function(spec) {\n \"use strict\";\n\n spec.eventType = \"focus\";\n spec.attachTo = null;\n\n qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {}));\n};\n","/*globals qq */\n// Handles edit-related events on a file item (FineUploader mode). This is meant to be a parent handler.\n// Children will delegate to this handler when specific edit-related actions are detected.\nqq.FilenameEditHandler = function(s, inheritedInternalApi) {\n \"use strict\";\n\n var spec = {\n templating: null,\n log: function(message, lvl) {},\n onGetUploadStatus: function(fileId) {},\n onGetName: function(fileId) {},\n onSetName: function(fileId, newName) {},\n onEditingStatusChange: function(fileId, isEditing) {}\n };\n\n function getFilenameSansExtension(fileId) {\n var filenameSansExt = spec.onGetName(fileId),\n extIdx = filenameSansExt.lastIndexOf(\".\");\n\n if (extIdx > 0) {\n filenameSansExt = filenameSansExt.substr(0, extIdx);\n }\n\n return filenameSansExt;\n }\n\n function getOriginalExtension(fileId) {\n var origName = spec.onGetName(fileId);\n return qq.getExtension(origName);\n }\n\n // Callback iff the name has been changed\n function handleNameUpdate(newFilenameInputEl, fileId) {\n var newName = newFilenameInputEl.value,\n origExtension;\n\n if (newName !== undefined && qq.trimStr(newName).length > 0) {\n origExtension = getOriginalExtension(fileId);\n\n if (origExtension !== undefined) {\n newName = newName + \".\" + origExtension;\n }\n\n spec.onSetName(fileId, newName);\n }\n\n spec.onEditingStatusChange(fileId, false);\n }\n\n // The name has been updated if the filename edit input loses focus.\n function registerInputBlurHandler(inputEl, fileId) {\n inheritedInternalApi.getDisposeSupport().attach(inputEl, \"blur\", function() {\n handleNameUpdate(inputEl, fileId);\n });\n }\n\n // The name has been updated if the user presses enter.\n function registerInputEnterKeyHandler(inputEl, fileId) {\n inheritedInternalApi.getDisposeSupport().attach(inputEl, \"keyup\", function(event) {\n\n var code = event.keyCode || event.which;\n\n if (code === 13) {\n handleNameUpdate(inputEl, fileId);\n }\n });\n }\n\n qq.extend(spec, s);\n\n spec.attachTo = spec.templating.getFileList();\n\n qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));\n\n qq.extend(inheritedInternalApi, {\n handleFilenameEdit: function(id, target, focusInput) {\n var newFilenameInputEl = spec.templating.getEditInput(id);\n\n spec.onEditingStatusChange(id, true);\n\n newFilenameInputEl.value = getFilenameSansExtension(id);\n\n if (focusInput) {\n newFilenameInputEl.focus();\n }\n\n registerInputBlurHandler(newFilenameInputEl, id);\n registerInputEnterKeyHandler(newFilenameInputEl, id);\n }\n });\n};\n"]}