codedropz-uploader.js 31 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
/**
 * CodeDropz Uploader v2.11.1
 * Copyright 2019 Glen Mongaya
 * CodeDropz - Drag & Drop Uploader
 * @version 2.11.1
 * @author CodeDropz, Glen Don L. Mongaya
 * @license The MIT License (MIT)
 */

(function($){

    // Queue, DataFiles ( Store Queue, Data Information )
    var FileDataRecord = [];
    var DataQueue = [];

    // Begin plugin initialization
	$.fn.CodeDropz_Uploader = function( settings ){

		// Support multiple elements
		this.each(function(){

			// Parent input file type
			var input = $(this);

			// Extends options
			var options = $.extend({
				handler 			: input,
				color 				: "#000",
				background 			: '',
				upload_dir			: input.parents('form').find("[name='upload_dir']"), //@ hidden input fields @todo - add in input file attribute
				server_max_error 	: 'Uploaded file exceeds the maximum upload size of your server.', //@ Server error
				max_file 			: input.data('max') ? input.data('max') : 5, //@ default 10
				max_upload_size 	: input.data('limit') ? input.data('limit') : '10485760', //@ should be a bytes it's (10MB)
				supported_type 		: input.data('type') ? input.data('type') : 'jpg|jpeg|JPG|png|gif|pdf|doc|docx|ppt|pptx|odt|avi|ogg|m4a|mov|mp3|mp4|mpg|wav|wmv|xls',
				max_total_size      : '100MB', //@ total size of all files uploaded - should be MB
				parallel_uploads	: 2, //@ Number of files to simultaneously upload
				chunks				: false, //@ wheather upload files in chunks
				chunk_size			: 10000, //@ 10MB - default chunk size (KB - format)
				text 				: 'Drag & Drop Files Here',
				separator			: 'or',
				button_text 		: 'Browse Files',
				err_message			: {
					maxNumFiles 		: 'You have reached the maximum number of files ( Only %s files allowed )',
					maxUploadLimit		: 'Note : Some of the files could not be uploaded ( Only %s files allowed )',
					maxTotalSize		: 'The total file(s) size exceeding the max size limit of %s.'
				},
				on_success			: '',
				in_progress			: '',
				completed			: ''
			}, settings);

			// Custom Upload Options
			var FileOptions = {
				parallelUploads : options.parallel_uploads, // sequential upload - how my files at a time.
				chunking 		: options.chunks,
				chunkSize 		: options.chunk_size, //kb
				progress__id	: 'codedropz--results'
			}

			// Clean and convert MB to Bytes
			var totalSize__Limit	= parseInt( options.max_total_size.replace('[^0-9]/g','') ) * 1048576; // convert MB to Bytes

			//Unique Filename for multiple uploads -- useful for multiple file upload in 1 form...
			var FileName = input.attr('data-name');

			// Template Container
			var cdropz_template = '<div class="codedropz-upload-handler">'
				+ '<div class="codedropz-upload-container">'
				+ '<div class="codedropz-upload-inner">'
				+ '<'+ dnd_cf7_uploader.heading_tag +'>'+ options.text +'</'+ dnd_cf7_uploader.heading_tag +'>'
				+ '<span>'+ options.separator +'</span>'
				+ '<div class="codedropz-btn-wrap"><a class="cd-upload-btn" href="javascript:void(0)">'+ options.button_text +'</a></div>'
				+ '</div>'
				+ '</div>'
				+ '<span class="dnd-upload-counter"><span>0</span> '+ dnd_cf7_uploader.dnd_text_counter +' '+ parseInt(options.max_file) +'</span>'
				+ '</div>';

			// Wrap input fields
			options.handler.wrapAll('<div class="codedropz-upload-wrapper"></div>');

			// Element Handler
			var form_handler = options.handler.parents('form'),
				options_handler = options.handler.parents('.codedropz-upload-wrapper');

			// Append Format
			options.handler.after( cdropz_template);

			// Preview Thumbnails
			if( dnd_cf7_uploader.preview_layout == 'column') {
				if( ! $('.codedropz--preview', options_handler).length > 0 ) {
					options_handler.append('<div class="codedropz--preview"></div>');
				}
			}

			// Uploader Object
			var CodeDropzUploader = {

				// Initialize
				init : function() {

					var self = this;

					// Get clean Field Name...
					FileName = this.getFieldName( FileName );

					// Create queue with index of file
					DataQueue[FileName] = [];

					// Data Record
					FileDataRecord[FileName] = {
						total 			: 0,
						uploaded 		: 0,
						uploading 		: true, // true if auto start upload / set to false if not
						maxTotalSize 	: 0, // total size of all files
						maxSize 		: options.max_upload_size,	//kb format default : 5mb - for indivual
						maxFile 		: options.max_file, // total number of files that can be uploaded
					};

					// preventing the unwanted behaviours
					$('.codedropz-upload-handler', options_handler ).on( 'drag dragstart dragend dragover dragenter dragleave drop',  function( e ){
						e.preventDefault();
						e.stopPropagation();
					})

					// dragover and dragenter - add class
					$('.codedropz-upload-handler', options_handler ).on( 'dragover dragenter',  function( e ){
						$(this).addClass('codedropz-dragover');
					});

					// dragleave dragend drop - remove class
					$('.codedropz-upload-handler', options_handler ).on( 'dragleave dragend drop',  function( e ){
						$(this).removeClass('codedropz-dragover');
					});

					// Begin upload files
					this.getUploadFiles();

					// Delete or Remove files
					$('body').on("click", 'a.remove-file', function(e){
						if( ! $(this).hasClass('deleting') ) {
							self.deleteFiles( $(this).data('index'), $(this), $(this).data('name') );
						}
					});

                    // Remove accept attribute on mobile devices
                    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
                        input.removeAttr('accept');
                    }
				},

                // Preview Thumbnails
                previewThumbnail : function( input ) {
                    if( input.file ) {
                        var imageFormat = ['image/png','image/jpg','image/jpeg','image/gif','image/tiff','image/xheic'];
                        if( $.inArray( input.file.type , imageFormat) !== -1 ) {
                            var reader = new FileReader();
                            reader.onload = function(e) {
                                $('#' + input.progressbar).find('.dnd-upload-image')
                                    .addClass('has-bg')
                                        .append('<img title="'+ input.name +'" src="'+ e.target.result +'">');
                                        
                            }
                            reader.readAsDataURL( input.file ); // convert to base64 string
                        }else{
                            return false;
                        }
                    }
                },

				// Get Upload Filed Name
				getFieldName : function( FieldName ) {
					return FieldName.replace(/[^a-zA-Z0-9_-]/g, "");
				},

				// Remove files
				deleteFiles : function( index, a_remove, fieldName ) {

					var file;
					var fileData = DataQueue[fieldName];
					var $_this = this;

					// Add delete status...
					a_remove.addClass('deleting').text( dnd_cf7_uploader.delete_text );

					// Loop files data queue
					for( var i=0; i < fileData.length; i++ ) {

						// Assign individual fileData to variable name - file
						file = fileData[i];

						// Check & Make sure we have property of file
						if( fileData[i].hasOwnProperty('file') ) {

							if( $.type(index) === "undefined" || file.index === index ) {

								// File started and not yet completed
								if( file.queued && file.complete == false && ! file.error ) {

									// Add abort status
									a_remove.addClass('deleting').text('aborting...');

									// Abort Upload & Remove progressbar
									this.abortFile( file );
									this.removeFile( file, i, fieldName );

								} else if( file.complete ) {

									// Assign file for ajax deletion ( Only `complete` status file ).
									var ajax_file = { _file : file, _index : i, _name : fieldName };

									// Remove uploaded file through ajax request
									data = {
										security : dnd_cf7_uploader.nonce,
										action 	 : 'dnd_codedropz_upload_delete',
										path 	 : $('#'+file.progressbar).find('input[type="hidden"]').val()
									}

									// Begin ajax delete
									$.post( options.ajax_url, data , function(response) {

										if( response.success ) {

											// Remove file & progress bar
											$_this.removeFile( ajax_file._file, ajax_file._index, ajax_file._name );

											//@debug - for developers
											console.log( ajax_file._file.name + ' - file deleted.');
										}

									});

								}else {

									// If there any error remove directly.
									this.removeFile( file, i, fieldName );
								}
							}
						}
					}
				},

				// Abort File Upload
				abortFile : function( file ) {
					if( FileOptions.chunking ) {
						if( file.chunkTransfer )
							file.chunkTransfer.abort();
					} else {
						file.transfer.abort();
					}
				},

				// Remove File - Specific File
				removeFile : function( file, i, FieldName ) {

					// Get parent element of file
					var CurrentProgress = $('#' + file.progressbar).parents('.codedropz-upload-wrapper');

					if( file && file.hasOwnProperty('file') && file.progressbar != null ) {

						// Find specific progress bar of file
						progressBar = CurrentProgress.find('#'+ file.progressbar );

						// Begin to remove progress bar
						if( progressBar.length > 0 ) {

							//DataQueue.splice( i, 1 );
							file.deleted = true; 	// set status deleted in Queue
							FileDataRecord[FieldName].total--; 	// reduce total
							FileDataRecord[FieldName].maxTotalSize = ( FileDataRecord[FieldName].maxTotalSize - file.size ); // minus total size of current deleted file.size

							// reduced file uploaded - counter
							if( file.complete && FileDataRecord[FieldName].uploaded > 0 ) {
								FileDataRecord[FieldName].uploaded--;
							}

							// Remove progress bar status
							progressBar.remove();

							// Continue processing the queue
							this.resetQueue( FieldName );

						}else{
							console.log('Progress Bar not exists!');
						}

						// Hide any error
						if( FileDataRecord[FieldName].uploaded < FileDataRecord[FieldName].maxFile ) {
							CurrentProgress.find('span.has-error-msg').remove();
						}

						// Show error file - ( If Total Size Exceeds )
						if( FileDataRecord[FieldName].maxTotalSize > totalSize__Limit ) {
							options_handler = CurrentProgress;
							this.validateFiles.setError( options.err_message['maxTotalSize'], false, options.max_total_size );
						}

						// Update counter
						$('.dnd-upload-counter span', $('input[data-name="'+FieldName+'"]').parents('.codedropz-upload-wrapper')).text( FileDataRecord[FieldName].total );

						//console.log(FileDataRecord); // debug
					}
				},

				// Get upload files
				getUploadFiles : function() {
					var _this = this;

					// when dropping files
					$('.codedropz-upload-handler', options_handler ).on('drop', function(event){
						_this.handleFiles( event.originalEvent.dataTransfer.files ); // Run the uploader
					});

					// Browse button clicked
					$( 'a.cd-upload-btn', options_handler ).on("click", function(e){
						e.preventDefault(); // stops the default action of an element from happening
						options.handler.val(null); // Reset value &
						options.handler.click(); // Click input type[file] element
					});

					// Trigger when input type[file] is click/changed
					options.handler.on("change", function(e){
						_this.handleFiles( this.files ); // Run the uploader
					});
				},

				// Handle Upload
				handleFiles : function( files ) {
					var numFiles = files.length,
						file = [];

					// Check max file limit - ex : 5
					if( FileDataRecord[FileName].maxFile ) {
						var remainingFiles = FileDataRecord[FileName].maxFile - FileDataRecord[FileName].uploaded; // ( 5:max - 3:uploaded = 2 remaining )
						if( remainingFiles >= 0 && files.length > remainingFiles ) { // 5:len > 3:remaining
							numFiles = remainingFiles;
						}
						if( FileDataRecord[FileName].uploaded == 0 && FileDataRecord[FileName].total > 0 ) {
							numFiles = ( FileDataRecord[FileName].maxFile - FileDataRecord[FileName].total );
						}
					}

					// Remove error message
					$('span.has-error-msg', options_handler).remove();

					// Total files reached max file limit
					if( FileDataRecord[FileName].total >= FileDataRecord[FileName].maxFile ) {
						return this.validateFiles.setError( options.err_message['maxNumFiles'], true, options.max_file );
					}

					// Loop Files - make sure we have remaining items ( greater > 0 ), /\ if reached 0 - it means zero remaining files
					if( numFiles > 0 ) {

						for( var i = 0; i < numFiles; i++ ) {

							if( files[i] ) {

								// Generate unique index key
								$unique_index = 'index-' + Date.now().toString(36) + Math.random().toString(36).substr(2, 5);

								// Supply Files details
								file = {
									index: $unique_index,
									file: files[i],
									name: files[i].name,
									size: files[i].size,
									queued: false,
									complete: false,
									error: false,
									pause : false,
									transfer: null,
									progressbar : null,
									deleted : false,
								};
								
								// Validate filename if there's no special character (prevent xss attack)
								if( newName = this.validateFiles.checkValidName( file.name ) ) {
									file.name = newName;
								}

								// Check if file already exceeds the max upload limit
								if( files.length - numFiles > 0  ) {
									this.validateFiles.setError( options.err_message['maxUploadLimit'], false, options.max_file );
								}

								// Increment File Index
								FileDataRecord[FileName].total++;

								// Add up total size of file
								FileDataRecord[FileName].maxTotalSize += file.size;

								// Create progress
								file.progressbar = this.progressBar.make( file );

								// Files - validation ( check file_type, file size etc... )
								if( this.validateFiles.check( file, FileName ) === false ) {
									file.error = true;
								}

								//@debug - dev purposes
								//$('.codedropz-btn-wrap a').text( CodeDropzUploader.bytesToSize( FileDataRecord[FileName].maxTotalSize ) +' of '+ options.max_total_size );

								// Check total size for all files
								if( ( FileDataRecord[FileName].maxTotalSize ) > totalSize__Limit ) {
									this.validateFiles.setError( options.err_message['maxTotalSize'], true, options.max_total_size );
									file.pause = true;
								}

								// Push new file to Queue
								DataQueue[FileName].push( file );

							}

						}
					}

					// Set uploading - to start queue / auto upload
					FileDataRecord[FileName].uploading = true;

					// Process QUEUE files
					this.processQueue( DataQueue[FileName], FileName );

				},

				// File validations
				validateFiles : {

					// Add error message
					setError : function( msg, _return, error_code ) {

						// Remove error msg
						$('span.has-error-msg', options_handler).remove();

						// Append error msg
						$('.' + FileOptions.progress__id, options_handler).after('<span class="has-error-msg">'+ msg.replace( '%s', error_code ) +'</span>');

						// return bolean
						if( _return ) {
							return false;
						}

					},

					// Check files
					check : function( file, FileName ){

						// Make sure we have files before we can validate.
						if( ! file ) return true;

						// Begin to validate
						if( file.progressbar ) {

							// Get specific Element (progress bar ID) of File
							var progress__bar = $('#'+ file.progressbar).find('.dnd-upload-details');

							// Reset & remove error msg
							$('#'+ file.progressbar).find('.has-error').remove();

							// Filesize validation
							if( file.size > FileDataRecord[FileName].maxSize && ! FileOptions.chunking ) {
								progress__bar.append('<span class="has-error">'+ dnd_cf7_uploader.drag_n_drop_upload.large_file +'</span>');
								return false;
							}
							
							// Not a valid file. (with 0 size)
							if( file.size === 0 ) {
								progress__bar.append('<span class="has-error">File is empty. Please upload something more substantial.</span>');
								return false;
							}

							// Filetype validation
							regex_type = new RegExp("(.*?)\.("+ options.supported_type +")$");
							if ( !( regex_type.test( file.name.toLowerCase() ) ) ) {
								progress__bar.append('<span class="has-error">'+ dnd_cf7_uploader.drag_n_drop_upload.invalid_type +'</span>');
								return false;
							}

						}

						return file;
					},

					// Validate File Name ( Prevent XSS attack )
					checkValidName : function( name ) {
						var notValidName = new RegExp(/[{>="'<:;/\}]+/g);
						if( notValidName.test( name ) ) {
							return encodeURIComponent( name.replace(/[{>="'<:;/\} ]/g,'_') );
						}
						return false;
					}
				},

				// Reset/Resume file Queue
				resetQueue : function( name ) {

					// Assign filtered file to new queue
					var newQueue = [];

					// Set option uploading to start uploading a file...
					FileDataRecord[name].uploading = true;

					// Loop DataQueue
					if( DataQueue[name].length > 0 ) {
						for( var e in DataQueue[name] ) {

							// Delete file from queue
							if( ! DataQueue[name][e].deleted == true ) {
								newQueue.push( DataQueue[name][e] );
							}

							// Resume if file status pause
							if( DataQueue[name][e].pause == true ) {
								if( FileDataRecord[name].maxTotalSize < totalSize__Limit ) {
									DataQueue[name][e].pause = false;
								}
							}
						}
					}

					if( newQueue.length > 0 ) {
						DataQueue[name] = newQueue;
					}

					// Re process Queue if there's remaining...
					this.processQueue( DataQueue[name], name );

					//@For debug purposes...
					console.log( DataQueue[name] );
					console.log( FileDataRecord[name] );
					console.log( CodeDropzUploader.bytesToSize(FileDataRecord[name].maxTotalSize) +' of '+ options.max_total_size );
				},

				// Process Queue Data
				processQueue : function( data, name ){

					var transfering = 0;
					var forQueue = [];

					if( ! FileDataRecord[name].uploading ) {
						return;
					}

					// Queue & Ignore files that has `error` and `completed` - assign to new Queue
					for( var i in data ) {
						if( data[i].complete == false && data[i].error == false ) {
							if( data[i].pause == false ) {
								forQueue.push( data[i] );
							}
						}
					}

					// in progress hooks
					if ( $.isFunction( options.in_progress ) ) {
						options.in_progress.call( this, form_handler, forQueue, DataQueue[name] );
					}

					// Loop Newly Queued files
					for( var i=0; i < forQueue.length; i++ ) {
						if( forQueue[i].hasOwnProperty('file') ) {

							// Get the files that are not being queued
							if( forQueue[i].queued == false ) {
								this.uploadFile( DataQueue[name], forQueue[i], name );
							}

							// Transferring increment ( so we can match into parallel uploads )
							transfering++;

							// parallel uploads - how many files uploaded at the same time
							if( transfering >= FileOptions.parallelUploads ) {
								return;
							}
						}
					}

					// All uploads are completed - js hook
					if( transfering == 0 ) {
						FileDataRecord[name].uploading = false;
						if ( $.isFunction( options.completed ) ) {
							options.completed.call( this, form_handler, FileDataRecord[name], DataQueue[name] );
						}
					}

				},

				// Create progress bar
				progressBar : {

					// Make a progress bar elements
					make : function( file ) {
						// Setup progress bar variable
						var generated_ID = 'dnd-file-' + Math.random().toString(36).substr(2, 9);

                        // Preview Image Thumbnail
                        var preview = false;

                        // Show thumbnail 
                        if( dnd_cf7_uploader.image_preview == true ) {
                            preview = CodeDropzUploader.previewThumbnail( file );
                        }

						// Setup progressbar elements
						var fileDetails = '<div class="dnd-upload-image">'+ ( preview === false ? '<span class="dnd-icon-blank-file"></span>' : '' ) +'</div>'
							+ '<div class="dnd-upload-details">'
							+ '<span class="name"><span title="'+ decodeURIComponent( file.name ) +'">'+ decodeURIComponent( file.name ) +'</span> <em>('+ CodeDropzUploader.bytesToSize( file.size ) +')</em></span>'
							+ '<a href="javascript:void(0)" title="'+ dnd_cf7_uploader.remove_text +'" class="remove-file" data-name="'+ FileName +'" data-index="'+ file.index +'"><span class="dnd-icon-remove"></span></a>'
							+ '<span class="dnd-progress-bar"><span></span></span>'
							+ '</div>';

						if( ! $('.' + FileOptions.progress__id, options_handler).length > 0 ) {
							options_handler.append('<div class="'+ FileOptions.progress__id +'"></div>');
						}

						// Append file details
						$('.' + FileOptions.progress__id, options_handler).append('<div id="'+ generated_ID +'" class="dnd-upload-status _uploading">'+ fileDetails +'</div>');

						return generated_ID;
					},

					// Set progress bar size
					setProgress : function( statusbar, percent ) {
						var statusBar = $( '.dnd-progress-bar', $('#' + statusbar) );
						if( statusBar.length > 0 ) {

							// Compute Progress bar percentage
							progress_width = ( percent * statusBar.width() / 100);

							// Start progress animation
							$('span', statusBar ).addClass('in-progress').animate({ width: progress_width }, 10).text( percent + '% ');

							// Set progress bar to 100%
							if( percent == 100 ) {
								$('span', statusBar ).addClass('complete').removeClass('in-progress');
                                $('#' + statusbar).removeClass('_uploading');
							}
						}
						return false;
					}
				},

				// Upload Single File
				uploadFile : function( data, file, name ) {
					var _this = this;

					// gathering the form data
					var formData = new FormData();
					var chunkSize = ( 1024 * FileOptions.chunkSize ); // convert ( 1024 Bytes = 1KB ) ( 1MB = 1000KB )

					// Setup form data
					formData.append('supported_type', options.supported_type );
					formData.append('size_limit', options.max_upload_size );
					formData.append('action', 'dnd_codedropz_upload' );
					formData.append('upload_dir', options.upload_dir.val() );
					formData.append('post_id', form_handler.find("[name='_wpcf7_container_post']").val());
					formData.append('security', dnd_cf7_uploader.nonce );

					// CF7 - upload field name & cf7 id
					formData.append('form_id', input.data('id'));
					formData.append('upload_name', input.data('name'));

					// Clean and validate filename
					if( newName = this.validateFiles.checkValidName( file.file.name ) ) {
						formData.append('orig-name', decodeURIComponent( newName ) );
					}
					
					// Chunks file upload
					if( FileOptions.chunking && file.size > chunkSize ) {
						file.queued = true;
						file.chunkSize = chunkSize;
						file.totalChunks = Math.ceil( file.size / file.chunkSize );
						file.currentChunk = 0;
						this.uploadChunks( data, file, name );
					} else {

						// set queued to true
						file.queued = true;

						// Append file
						formData.append('upload-file', file.file );

						// Process ajax upload
						file.transfer =  $.ajax({
							url			: options.ajax_url,
							type		: form_handler.attr('method'),
							data		: formData,
							dataType	: 'json',
							cache		: false,
							contentType	: false,
							processData	: false,
							xhr			: function(){

								//objects to interact with servers.
								var _xhr = new window.XMLHttpRequest();

								// reference : https://stackoverflow.com/questions/15410265/file-upload-progress-bar-with-jquery
								_xhr.upload.onprogress = function(event) {
									if ( event.lengthComputable ) {
										var	percentage = parseInt( ( event.loaded / event.total ) * 100 );

										// Progress Loading
										_this.progressBar.setProgress( file.progressbar, percentage - 1 );

									}
								};

								return _xhr;
							},
							success: function( response ) {

								if( response.success ) {

									// Complete progressbar
									_this.progressBar.setProgress( file.progressbar, 100 );

									// Complete file
									file.complete = true;

									// Increment Uploaded counter
									FileDataRecord[name].uploaded++;

									// Run uploaded again
									_this.processQueue( data, name );

									// Callback on success
									if ( $.isFunction( options.on_success ) ) {
										options.on_success.call( this, file.progressbar, response, name, FileDataRecord[name] );
									}

								}else {

									// Display erro message
									$('#' + file.progressbar)
										.find('.dnd-upload-details')
											.append('<span class="has-error">'+ response.data +'</span>');


									// Set file status to error
									file.error = true;

									// Run uploaded again
									_this.processQueue( data, name );
								}
							},
							error: function( xhr,ajax,thrownError ) {

								// Display Progress bar - with erro msg
								$('#'+ file.progressbar)
								.find('.dnd-upload-details')
									.append('<span class="has-error">'+ thrownError +'</span>');

								// Set file has error & process queue
								file.error = true;
								_this.processQueue( data, name );
							}
						});
					}

				},

				// Upload files in chunks
				uploadChunks : function( data, file, name ){

					var chunk_start = ( file.chunkSize * file.currentChunk ), // @description: chunk_start = (5000 * 0) // @currentChunk( increment : 0,1,2,3 )
						chunk_end = ( chunk_start + file.chunkSize),
						$_this = this;

					// If size - end less than 0 end should be total file of size
					if ( chunk_end > file.size ) {
						chunk_end = file.size;
					}

					// Begin Slicing files here ( file, start , end )
					var slicedPart = this.sliceFile( file.file, chunk_start, chunk_end );
					var formData = new FormData();

					// Security
					formData.append('security', dnd_cf7_uploader.nonce );

					// Append needed data
					formData.append('start', chunk_start );
					formData.append('end', chunk_end );
					formData.append('total_chunks', file.totalChunks ); // Count Total of chunks ( file.size / FileOptions.chunkSize )
					formData.append('chunk_size', file.chunkSize );
					formData.append('upload_dir', options.upload_dir.val());
					formData.append('chunk', file.currentChunk );
					formData.append('chunks-file', slicedPart, file.file.name );
					formData.append('unique', file.progressbar );
					formData.append('post_id', form_handler.find("[name='_wpcf7_container_post']").val());
					formData.append('action', 'dnd_codedropz_upload_chunks' );

					// cf7 form data & uploader name
					formData.append('form_id', input.data('id'));
					formData.append('upload_name', input.data('name'));

					// Begin ajax request
					file.chunkTransfer = $.ajax({
						url			: options.ajax_url,
						type		: form_handler.attr('method'),
						dataType	: 'json',
						data		: formData,
						type		: "POST",
						contentType	: false,
						processData	: false,
						cache		: false,
						success		: function( response, status, jqXHR ) {

							if( response && typeof response != 'undefined' ) {

								// Increment currentChunk
								file.currentChunk++;

								// Make sure we have response from chunks
								if( response.data.partial_chunks && file.currentChunk < file.totalChunks ) { //@Recursive - until currentChunk is Equal to TotalChunks ( ex: 3 < 4 )
									$_this.uploadChunks( data, file, name );
								}

								// Logs chunks
								console.log( file.name +' [chunk -'+ file.currentChunk +' of '+ file.totalChunks +']' );

								// Check and make sure we have response
								if( response.data.file ) {

									// Complete progressbar
									if( file.currentChunk == file.totalChunks ) {
										$_this.progressBar.setProgress( file.progressbar, 100 );
									}

									// Complete File & Increment Uloaded - FileOptions
									file.complete = true;
									FileDataRecord[name].uploaded++;

									// run queue
									$_this.processQueue( data, name );

									// Callback on success
									if ( $.isFunction( options.on_success ) ) {
										options.on_success.call( this, file.progressbar, response, name, FileDataRecord[name] );
									}
								}else{
                                    if( response.success == false ){

                                        // Display error message
                                        $('#' + file.progressbar)
                                            .find('.dnd-upload-details')
                                                .append('<span class="has-error">'+ response.data +'</span>');


                                        // Set file status to error
                                        file.error = true;

                                        // Run uploaded again
                                        $_this.processQueue( data, name );

                                    }
                                }
							}

						},
						error		: function( xhr, ajax, thrownError ) {

							// Display Progress bar - with erro msg
							$('#'+ file.progressbar)
								.find('.dnd-upload-details')
									.append('<span class="has-error">'+ thrownError +'</span>');

							// Set file has error - and process queue
							file.error = true;

							// Process queue
							$_this.processQueue( data, name );
						},
						xhr			: function(){
							//objects to interact with servers.
							var _xhr = new window.XMLHttpRequest();

							// reference : https://stackoverflow.com/questions/15410265/file-upload-progress-bar-with-jquery
							_xhr.upload.onprogress = function(event) {
								if ( event.lengthComputable ) {

									// Compute progress & percentage
									var percentComplete = ( event.loaded / event.total ),
										chunksPercent = Math.ceil( ( 1 / file.totalChunks ) * 99 ), //@description - 2 / 3 = 66 percent
										partialTotal = ( file.currentChunk / file.totalChunks ) * 99;

									// Get current percent
									var percentage = ( file.currentChunk == 0 ? chunksPercent * percentComplete : ( chunksPercent * percentComplete ) + partialTotal );

									// Progress Loading
									$_this.progressBar.setProgress( file.progressbar, parseInt( percentage ) );

								}
							};

							return _xhr;
						}
					});
				},

				// File Slicing
				sliceFile : function( file, start, end ) {
					var slice = file.mozSlice ? file.mozSlice :	file.webkitSlice ? file.webkitSlice : file.slice ? file.slice : {};
					return slice.bind(file)(start, end);
				},

				// Size Conversion
				bytesToSize : function( bytes ) {
					if( bytes === 0 ) return '0';
					kBytes = ( bytes / 1024 );
					fileSize = ( kBytes >= 1024 ? ( kBytes / 1024 ).toFixed(2) + 'MB' : kBytes.toFixed(2) + 'KB' );
					return fileSize;
				},
			}

			// Initialize plugin
			CodeDropzUploader.init();

			// Contact form Javascript dom events
			var cf7_events = ['wpcf7mailsent','wpcf7spam','wpcf7mailfailed'];

			// Loop and reset all file data.
			for( var i in cf7_events ) {
				// cf7 js hooks
				document.addEventListener( cf7_events[i], function( event ) {
					name = CodeDropzUploader.getFieldName( FileName );
					DataQueue[name] = [];
					FileDataRecord[name] = {
						total 			: 0,
						uploaded 		: 0,
						uploading 		: true,
						maxTotalSize 	: 0,
						maxSize 		: options.max_upload_size,
						maxFile 		: options.max_file,
					};
				}, false);
			}

		});

	}
}( jQuery ));