'use strict';

jQuery(document).ready(function ($) {
 	$(document).on( "searchwp_live_search_start", function( $event, $input, $results, $form, action, values ) {
 		// Abort previous requests
		$('input[data-swplive="true"]').each( function () {
			var swp = $(this).data('plugin_searchwp_live_search');
			if ( typeof( swp ) !== 'undefined' && swp.current_request ) {
				swp.current_request.abort();
			}
		});
		
		$input.closest('.search-form').addClass('loading');
		$results.addClass('loading');
 		$results.removeClass('results-ready');
 	});

	$(document).on( "searchwp_live_destroy_results", function( $event ) {
		$('.searchwp-live-search-results').removeClass('results-ready');
	});

	$(document).on( "searchwp_live_search_complete", function( $event, $input, $results, $form, action, values ) {
		$input.closest('.search-form').removeClass('loading');
		$results.removeClass('loading');
		$results.addClass('results-ready');
	});

	// Handle arrow and home/end keys in searchbox
	$('input[data-swplive="true"]').on( 'keydown', function (e) {
		var $form = $(this).closest('form');
		var $result_links = $form.find('.searchwp-live-search-results > .searchwp-live-search-result a');

		switch ( e.keyCode ) {
			case 35: // End
			case 36: // Home
			case 37: // Left arrow
			case 38: // Up arrow
			case 39: // Right arrow
				// Prevent new searching				
				break;
			case 40: // Down arrow
				if ( $result_links.length ) {
					$result_links.eq(0).focus();
				}
				e.preventDefault(); // Prevent keyup, to abort search
				return false;
				break;
			default:
		}
	});

	// Move up/down through the results using keyboard arrows
	$('.wrap-results').on( 'keydown', '.searchwp-live-search-results > .searchwp-live-search-result a', function (e) {
		if ( e.keyCode === 38 ) {
			if ( $(this).closest('.searchwp-live-search-result').prev().length ) {
				$(this).closest('.searchwp-live-search-result').prev().find('a').focus();
			} else {
				$(this).closest('form').find('input[data-swplive="true"]').focus();
			}
			e.preventDefault(); // Prevent window scrolling on keydown
		}

		if ( e.keyCode === 40 ) {
			$(this).closest('.searchwp-live-search-result').next().find('a').focus();
			e.preventDefault(); // Prevent window scrolling on keydown
		}
	});
});