NDOJ/resources/fine-uploader/fine-uploader.min.js.map
2023-05-20 08:53:43 +09:00

1 line
No EOL
603 KiB
Text

{"version":3,"sources":["?","../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","qq","element","hide","style","display","this","attach","type","fn","addEventListener","attachEvent","detach","removeEventListener","detachEvent","contains","descendant","compareDocumentPosition","insertBefore","elementB","parentNode","remove","removeChild","css","styles","Error","opacity","filter","Math","round","extend","hasClass","name","considerParent","re","RegExp","test","className","addClass","removeClass","replace","getByClass","first","candidates","result","querySelector","querySelectorAll","getElementsByTagName","each","idx","val","push","getFirstByClass","children","child","firstChild","nodeType","nextSibling","setText","text","innerText","textContent","clearText","hasAttribute","attrName","attrVal","exec","getAttribute","undefined","canvasToBlob","canvas","mime","quality","dataUriToBlob","toDataURL","dataUri","arrayBuffer","byteString","intArray","mimeString","createBlob","data","BlobBuilder","window","WebKitBlobBuilder","MozBlobBuilder","MSBlobBuilder","blobBuilder","append","getBlob","Blob","split","indexOf","atob","decodeURI","ArrayBuffer","length","Uint8Array","character","charCodeAt","log","message","level","console","isObject","variable","Object","prototype","toString","call","isFunction","isArray","value","buffer","constructor","isItemList","maybeItemList","isNodeList","maybeNodeList","item","namedItem","isString","maybeString","trimStr","string","String","trim","format","str","args","Array","slice","arguments","newStr","nextIdxToReplace","substring","isFile","maybeFile","File","isFileList","maybeFileList","FileList","isFileOrInput","maybeFileOrInput","isInput","maybeInput","notFile","evaluateType","normalizedType","toLowerCase","HTMLInputElement","tagName","isBlob","maybeBlob","isXhrUploadSupported","input","document","createElement","multiple","FormData","createXhrInstance","upload","XMLHttpRequest","ActiveXObject","error","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","prop","override","target","sourceFn","super_","source","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","retVal","Storage","key","getItem","charAt","bind","oldFunc","context","newArgs","concat","apply","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","match","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","options","title","self","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","index","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","params","endpoint","addFiles","addInitialFiles","cannedFileList","cannedFile","_addCannedFile","_maybeHandleIos8SafariWorkaround","_storedIds","_currentBatchId","processBlob","_handleNewFile","_options","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","callbacks","onError","_createDeleteHandler","DeleteFileAjaxRequester","method","toUpperCase","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","namespace","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","el","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","DragAndDrop","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","dropZoneElements","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","FineUploader","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","uploader","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","cloneNode","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,QCEV,GAAIC,IAAK,SAASC,GACd,YAEA,QACIC,KAAM,WAEF,MADAD,GAAQE,MAAMC,QAAU,OACjBC,MAIXC,OAAQ,SAASC,EAAMC,GAMnB,MALIP,GAAQQ,iBACRR,EAAQQ,iBAAiBF,EAAMC,GAAI,GAC5BP,EAAQS,aACfT,EAAQS,YAAY,KAAOH,EAAMC,GAE9B,WACHR,GAAGC,GAASU,OAAOJ,EAAMC,KAIjCG,OAAQ,SAASJ,EAAMC,GAMnB,MALIP,GAAQW,oBACRX,EAAQW,oBAAoBL,EAAMC,GAAI,GAC/BP,EAAQS,aACfT,EAAQY,YAAY,KAAON,EAAMC,GAE9BH,MAGXS,SAAU,SAASC,GAKf,QAAKA,IAKDd,IAAYc,IAIZd,EAAQa,SACDb,EAAQa,SAASC,MAGgC,EAA9CA,EAAWC,wBAAwBf,OAOrDgB,aAAc,SAASC,GAEnB,MADAA,GAASC,WAAWF,aAAahB,EAASiB,GACnCb,MAGXe,OAAQ,WAEJ,MADAnB,GAAQkB,WAAWE,YAAYpB,GACxBI,MAOXiB,IAAK,SAASC,GAEV,GAAqB,MAAjBtB,EAAQE,MACR,KAAM,IAAIH,IAAGwB,MAAM,6EAWvB,OAPsB,OAAlBD,EAAOE,SAC8B,gBAA1BxB,GAAQE,MAAMsB,SAA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I4tC,WAAY,KACZ7iD,IAAK,SAASC,EAASkjD,KACvBU,kBAAmB,SAAShpC,KAC5B2oC,UAAW,SAAS3oC,KACpBipC,UAAW,SAASjpC,EAAQtE,KAC5BwtC,sBAAuB,SAASlpC,EAAQmpC,KAwDhDnqD,IAAG6B,OAAOuZ,EAAMo+C,GAEhBp+C,EAAKy+C,SAAWz+C,EAAK4tC,WAAWgP,cAEhCh4D,GAAG6B,OAAOxB,KAAM,GAAIL,IAAGu5D,eAAen+C,EAAMi/C,IAE5Cr6D,GAAG6B,OAAOw4D,GACNC,mBAAoB,SAASngD,EAAI7N,EAAQ8uD,GACrC,GAAIN,GAAqB1/C,EAAK4tC,WAAWqB,aAAalwC,EAEtDiB,GAAK8uC,sBAAsB/vC,GAAI,GAE/B2gD,EAAmB/zD,MAAQ0zD,EAAyBtgD,GAEhDihD,GACAN,EAAmBO,QAGvBL,EAAyBF,EAAoB3gD,GAC7C8gD,EAA6BH,EAAoB3gD,Q3CvF9BjV","file":"fine-uploader.min.js","sourcesContent":[null,"/*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"]}