/* UPLOADFIVE */

jQuery( document ).ready( function( $ ) {
	$( document ).on( "click", ".file-content-wrapper", ( function() {
		if ( ! $( this ).hasClass( "uploading" ) ) {
			var uploader_class = $( this ).parents( '.uploadifive-uploader-wrapper' ).attr( 'data-media-type' );
			$( this ).parents( '.uploadifive-uploader-wrapper' ).find( "#uploadifive-file_upload_" + uploader_class + " input:last" ).click();
		}
	}));
});

// Call the uploadifive init function
( function ( $ ) {
	$.fn.wpjUploadifiveUploaderInit = function() {
		if ( $( '.uploadifive-uploader' )[0] ) {
			$( '.uploadifive-uploader' ).each( function() {
				var input_file_upload     = $( this ).attr( 'data-input-id' );
				var input_hidden_store_id = $( this ).attr( 'data-input-name' );
				var unique_name           = $( this ).attr( 'data-media-name' );
				var button_label          = $( this ).attr( 'data-button-label' );

				wpj_init_upload_form( 1, input_file_upload, input_hidden_store_id, unique_name, button_label );
			});
		}

		var uploadifive_uploader_classes = ["banner", "avatar", "audio", "skill"];
		uploadifive_uploader_classes.forEach( function( uploader_class ) {
			if ( $( "#file_upload_" + uploader_class )[0] ) {
				wpj_init_media_upload_form( uploader_class );
			}
		});
	}
} ( jQuery ) );

function wpj_init_upload_form( secure, input_file_upload, input_hidden_store_id, unique_name, button_label ) { // Upload Form
	if ( ! jQuery( '#uploadifive-' + input_file_upload )[0] ) {
		jQuery( "#" + input_file_upload ).uploadifive({
			"auto"             : true,
			"multi"            : true,
			"height"           : "auto",
			"width"            : "auto",
			"uploadScript"     : wpj_vars.theme_path + "/lib/uploaders/uploadifive.php",
			"formData"         : { "author": wpj_vars.uid, "secure": 1 , "unique_name": unique_name, "source": unique_name },
			"uploadLimit"      : 10,
			"fileSizeLimit"    : wpj_vars.attachment_filesize_max,
			"buttonText"       : button_label !== undefined ? button_label : wpj_vars.select_file,
			onProgress : function() {
				// disable submit button
				jQuery( "input[type=submit]" ).prop( "disabled", true );

				// add margin bottom
				if ( jQuery( '.files-attachments-wrapper' )[0] && ! jQuery( '.files-attachments-wrapper' ).hasClass( 'mb20' ) )
					jQuery( '.files-attachments-wrapper' ).addClass( 'mb20' );
			},
			onError : function( data ) {
				// display errors
				if ( data == "FILE_SIZE_LIMIT_EXCEEDED" ) jQuery( "#uploadifive-" + input_file_upload ).notify( wpj_vars.attachments_max_size_err, { position: "top center", className: "error" } );
				else jQuery( "#uploadifive-" + input_file_upload ).notify( data, { position: "top center", className: "error" } );

				// enable submit button
				jQuery( "input[type=submit]" ).prop( "disabled", false );
			},
			onUploadComplete : function( file, data, response ) {
				// parse response
				var data = jQuery.parseJSON( data );

				// set attachment id attribute
				jQuery( ".filename:contains(" + file.name + ")" ).parent().parent().attr( "data-id", data.id );

				// add attachment id to input value
				jQuery( "input[name=" + input_hidden_store_id + "]" ).val( function( i,val ) { return val + ( val ? "," : "" ) + data.id; });

				// enable submit button
				jQuery( "input[type=submit]" ).prop( "disabled", false );

				// enable buton
				jQuery( "button" ).removeClass( "div-disabled" );

				// add margin bottom
				if ( jQuery( '.files-attachments-wrapper' )[0] && ! jQuery( '.files-attachments-wrapper' ).hasClass( 'mb20' ) )
					jQuery( '.files-attachments-wrapper' ).addClass( 'mb20' );
			},
			onCancel : function( file ) {
				// remove attachment id from input value
				var id = jQuery( ".filename:contains(" + file.name + ")" ).parent().parent().attr( "data-id" );
				jQuery( "input[name=" + input_hidden_store_id + "]" ).val( removeCommaString( jQuery( "input[name=" + input_hidden_store_id + "]" ).val(), id ) );

				// remove margin bottom
				if ( jQuery( '.files-attachments-wrapper' )[0] && jQuery( '.files-attachments-wrapper' ).hasClass( 'mb20' ) )
					jQuery( '.files-attachments-wrapper' ).removeClass( 'mb20' );
			}
		});
	}
}

// Avatar & Cover & Audio & Skill
function wpj_init_media_upload_form( uploader_class ) {
	var width     = uploader_class == "banner" ? 1170 : 150;
	var height    = uploader_class == "banner" ? 215 : 150;
	var file_ext  = uploader_class == "audio" ? "*.mp3;*.wav;" : "*.jpg;*.jpeg;*.gif;*.png";
	var file_type = uploader_class == "audio" ? "audio/mp3,audio/wav" : "image/*";

	var params = new URL(window.location.toLocaleString()).searchParams;
	var pid    = params.get( 'jobid' );

	if ( pid === null ) {
		pid = decodeURIComponent( getParameterFromGivenURL( wpj_vars.url_params, 'jobid' ) );
	}

	jQuery( "#file_upload_" + uploader_class ).uploadifive({
		"auto"         : true,
		"multi"        : false,
		"uploadScript" : wpj_vars.theme_path + "/lib/uploaders/uploadifive.php",
		"fileTypeExts" : file_ext,
		"formData"     : { "pid" : pid, "author": wpj_vars.uid, "width": width, "height": height, "source": uploader_class, "secure": 1 },
		"fileType"     : file_type,
		"fileSizeLimit": wpj_vars[uploader_class + "_filesize_max"],
		onProgress : function() {
			jQuery( "." + uploader_class + "-uploader-wrapper" ).find( ".js-new-file-wrapper" ).addClass( "loading uploading" );
		},
		onError : function( data ) {
			if ( data == "FILE_SIZE_LIMIT_EXCEEDED" )
				jQuery( "." + uploader_class + "-uploader-wrapper" ).parent().notify( wpj_vars[uploader_class + "_filesize_msg"], { position: "top center", className: "error" } );

			else if ( data == "FORBIDDEN_FILE_TYPE" )
				jQuery( "." + uploader_class + "-uploader-wrapper" ).parent().notify( wpj_vars.user_filetype_msg, { position: "top center", className: "error" } );

			else
				jQuery( "." + uploader_class + "-uploader-wrapper" ).parent().notify( data, { position: "top center", className: "error" } );

			jQuery( "." + uploader_class + "-uploader-wrapper" ).find( ".js-new-file-wrapper" ).removeClass( "loading uploading" );
		},
		onUploadComplete : function( file, data, response ) {
			var data = jQuery.parseJSON( data );

			if ( data.status == "ok" ) {
				if ( uploader_class == "banner" ) {
					if ( ! jQuery( '.user-profile-cover-row-wrapper' ).hasClass( 'js-user-has-cover' ) )
						jQuery( '.user-profile-cover-row-wrapper' ).addClass( 'user-has-cover js-user-has-cover' );

					jQuery( "#banner" ).addClass( "ub-cover-photo" ).css( {"background-image": "url(" + data.file_url + ")"} ); // increase the hight
					jQuery( ".js-add-user-cover-button" ).hide(); // hide add cover button
					jQuery( ".js-delete-user-cover-button" ).attr( "data-attachment-id", data.id ).show(); // show delete cover button
				}

				if ( uploader_class == "avatar" ) {
					jQuery( ".avatar-image-wrapper" ).find( "img" ).attr( "src", data.file_url ); // set avatar
					jQuery( ".user-info-menu" ).find( ".ui.avatar.image" ).attr( "src", data.file_url ); // set header avatar
				}

				if ( uploader_class == "audio" ) {
					// set audio
					jQuery( ".audio-wrapper" ).append( '\
						<div class="file-wrapper audio-file-wrapper" id="' + data.id + '" data-audio-id="' + data.id + '">\
							<p>' + data.file_name + '</p>\
							<a data-attachment-id="' + data.id + '" data-media-type="audio" class="js-delete-file delete-file delete-audio cursor-pointer"><i class="x icon"></i></a>\
						</div>\
					' );

					// hide upload box if max number
					if ( jQuery( ".audio-file-wrapper" ).length >= jQuery( ".audio-uploader-wrapper" ).attr( "data-maxnrofpictures" ) )
						jQuery( ".audio-new-file-wrapper" ).hide();
				}

				if ( uploader_class == "skill" ) {
					jQuery( ".skill-image-wrapper" ).find( ".icon" ).remove(); // remove loading icon
					jQuery( ".skill-image-wrapper" ).css( "background-image", "url( " + data.file_url + " )" ).attr( "data-id", data.id ); // set logo
				}
			}

			else if ( data.status == "size" )
				jQuery( "." + uploader_class + "-uploader-wrapper" ).parent().notify( wpj_vars.user_filesize_min_msg, { position: "top center", className: "error" } );

			else if ( data.status == "extension" )
				jQuery( "." + uploader_class + "-uploader-wrapper" ).parent().notify( wpj_vars.user_filetype_msg, { position: "top center", className: "error" } );

			else
				jQuery( "." + uploader_class + "-uploader-wrapper" ).parent().notify( wpj_vars.err, { position: "top center", className: "error" } );

			jQuery( "." + uploader_class + "-uploader-wrapper" ).find( ".js-new-file-wrapper" ).removeClass( "loading uploading" );
		}
	});
}

// Display new audio upload box
Hooks.add_action( "wpj_after_file_removal", wpj_display_uploadifive_audio_upload_box, 2 );
function wpj_display_uploadifive_audio_upload_box( attachment_id, media_type ) {
	if ( jQuery( ".audio-file-wrapper" ).length >= jQuery( ".audio-uploader-wrapper" ).attr( "data-maxnrofpictures" ) )
		jQuery( ".audio-new-file-wrapper" ).hide();
	else
		jQuery( ".audio-new-file-wrapper" ).show();
}