jQuery( document ).ready( function( $ ) {

	// DOWNLAD ATTACHMENT WITH TOKEN
	$( document ).on( 'click', "a[href*='secure_download']", function( e ) {
		var url = ( $( this ).attr( 'href' ) );
		var auth_token = getParameterFromGivenURL( url, 'auth_token' );
		var secure_download = getParameterFromGivenURL( url, 'secure_download' );

		if ( secure_download ) {
			$.ajax({
				type: "POST",
				url: wpj_vars.ajaxurl,
				data: {
					action: 'save_auth_token_transient_action',
					secure_download: secure_download,
					auth_token: auth_token,
				},
				success: function( msg ) {}
			});
		}
	});

	if ( wpj_vars.is_user_logged_in ) {

		// DELETE FILE
		$( document ).on( 'click', '.js-delete-file', function( e ) {

			e.preventDefault();
			e.stopPropagation();

			var attachment_id = $( this ).attr( 'data-attachment-id' );
			var media_type    = $( this ).attr( 'data-media-type' );
			var pid           = $( this ).attr( 'data-pid' );

			// action
			Hooks.do_action( 'wpj_before_file_removal', attachment_id, media_type );

			if ( media_type == 'banner' ) {
				$( '.user-profile-cover-row-wrapper' ).removeClass( 'user-has-cover js-user-has-cover' );

				$( this ).parents( '#banner' ).removeClass( 'ub-cover-photo' );
				$( this ).parents( '#banner' ).css( 'background-image', 'unset' );
				$( this ).parents( '#banner' ).find( '.js-add-user-cover-button' ).show();

				$( this ).hide();

			} else { // remove file
				if ( $( this ).parents( '.file-wrapper' ).parent( '.dz-image-wrapper' )[0] )
					$( this ).parents( '.dz-image-wrapper' ).remove();

				else
					$( this ).parents( '.file-wrapper' ).remove();

			}

			// remove file from database
			$.ajax({
				type   : "POST",
				url    : wpj_vars.ajaxurl,
				data   : {
					action       : 'delete_attachment_action',
					attachment_id: attachment_id,
					media_type   : media_type,
					pid          : pid
				},
				success: function( msg ) {}
			});

			// action
			Hooks.do_action( 'wpj_after_file_removal', attachment_id, media_type );
		});

		wpj_sort_image_files();

	}

});

// SORT IMAGE FILES
function wpj_sort_image_files() {
	if ( jQuery( '.images-wrapper' )[0] ) {
		jQuery( '.images-wrapper' ).sortable({
			connectWith: '.images-wrapper',
			start      : function( event, ui ) {},
			change     : function( event, ui ) {},
			update     : function( event, ui ) {
				var images_order = jQuery( '.images-wrapper' ).sortable( 'toArray', { attribute: 'data-id' } );
				jQuery( '#images_order' ).val( images_order );

				jQuery.ajax({
					type: 'POST',
					url : wpj_vars.ajaxurl,
					data: {
						action      : 'sort_attachment_action',
						images_order: images_order,
						pid         : jQuery( '.images-wrapper' ).attr( 'data-pid' )
					},
					success: function( output ) {}
				});
			}
		});

		jQuery( '.images-wrapper div' ).disableSelection();
	}

}