/* HTML5 File Upload */

// Call the html5fileupload init function
( function ( $ ) {
	$.fn.wpjHTML5UploaderInit = function() {
		if ( $( '.html5fileupload-wrapper' )[0] ) {
			$( '.html5fileupload-wrapper' ).each( function() {
				wpj_init_html5_images_uploader( $( this ).attr( 'data-media-type' ) );
			});
		}
	}
} ( jQuery ) );

function wpj_init_html5_images_uploader( uploader_class ) {

	if ( jQuery( '.' + uploader_class )[0] ) {

		jQuery.html5fileupload.defaults = {
			showErrors      : true,
			url             : null,
			downloadUrl     : null,
			removeUrl       : null,
			removeDone      : false,
			removeDoneDelay : 1200,
			file            : null,
			edit            : true,
			randomName      : false,
			randomNameLength: 8,
			form            : false,
			data            : { ID: jQuery( '.' + uploader_class ).attr( 'data-pid' ), author: jQuery( '.' + uploader_class ).attr( 'data-uid' ), source: uploader_class },
			ajax            : true,
			ajaxType        : 'POST',
			ajaxDataType    : 'json',
			ajaxHeaders     : {},
			multiple        : uploader_class == 'cover' ? false : true,
			validExtensions : null,
			validMime       : null,
			labelInvalid    : null,
			autostart       : false,
			minFilesize     : 0,
			maxFilesize     : 2048000,
			labelMinFilesize: null,
			labelMaxFilesize: null,
			regexp          : /^[^\\/:\*\?"<>\|]+$/,
		}

		jQuery( '.html5fileupload.' + uploader_class ).html5fileupload({
			onAfterStartSuccess: function( response ) {

				if ( ! response.error ) {

					if ( ! jQuery( '.' + uploader_class ).parents( '.html5fileupload-wrapper' ).find( '.html5fileupload-images-wrapper' )[0] )
						jQuery( '.' + uploader_class ).parents( '.html5fileupload-wrapper.' + uploader_class + '-uploader-wrapper' ).prepend( '<div class="html5fileupload-images-wrapper cf"></div>' );

					var html_content = '\
						<div class="file-wrapper pr">\
							\
							<img class="no-border" src="' + response.go + '" />\
							\
							<a data-attachment-id="' + response.attach_id + '" data-media-type="' + uploader_class + '" class="js-delete-file delete-file delete-image cursor-pointer"><i class="x icon"></i></a>\
							\
						</div>\
					';

					jQuery( '.' + uploader_class ).parents( '.html5fileupload-wrapper' ).find( '.html5fileupload-images-wrapper' ).append( html_content );

				} else {
					jQuery( '.' + uploader_class ).notify( response.error, { position: 'top', className: 'error' } );
					jQuery( '.' + uploader_class ).find( 'input[type="file"]' ).show();

				}

			}
		});

	}

}