"use strict";

(function( $ ) {
	var itsecMalwareScan = {
		init: function() {
			this.bindEvents();
		},
		
		bindEvents: function() {
			$( '#itsec-malware-scan-start' ).on( 'click', this.startScan );
			$( '.itsec-malware-scan-results-wrapper' ).on( 'click', '.itsec-malware-scan-toggle-details', this.toggleDetails );
		},
		
		toggleDetails: function( e ) {
			e.preventDefault();
			
			var $container = $(this).parents( '.itsec-malware-scan-results-section' );
			var $details = $container.find( '.itsec-malware-scan-details' );
			
			if ( $details.is(':visible') ) {
				$(this).html( itsecMalwareScanData.showDetailsText );
				$details.hide();
			} else {
				$(this).html( itsecMalwareScanData.hideDetailsText );
				$details.show();
			}
		},
		
		startScan: function( e ) {
			e.preventDefault();
			
			itsecMalwareScanData.originalSubmitButtonText = $(this).val();
			
			$(this)
				.prop( 'disabled', true )
				.val( itsecMalwareScanData.clickedButtonText );
			
			var data = {
				'action': 'run-scan'
			};
			
			itsecSettingsPage.sendWidgetAJAXRequest( 'malware-scan', data, itsecMalwareScan.handleResponse );
		},
		
		handleResponse: function( results ) {
			$('#itsec-malware-scan-start').hide();
			
			if ( results.errors.length > 0 ) {
				var message;
				
				$.each( results.errors, function( index, error ) {
					message = '<div class="error inline"><p><strong>' + error + '</strong></p></div>';
					$('.itsec-malware-scan-results-wrapper').append( message );
				} );
			} else {
				$('.itsec-malware-scan-results-wrapper').html( results.response );
			}
		},
	};
	
	$(document).ready(function() {
		itsecMalwareScan.init();
	});
})( jQuery );
