// User Search
jQuery( document ).ready( function( $ ) {

	function search_delay( callback, ms ) {
		var timer = 0;
		return function() {
			var context = this, args = arguments;
			clearTimeout( timer );
			timer = setTimeout( function () { callback.apply( context, args ); }, ms || 0 );
		};
	}

	$( document ).on( 'keyup paste change', '#user_term, #user_location, #user_radius, #user_skills, #user_level', search_delay( function( e ) { /* Add search params to URL */
		var term      = '';
		var location  = '';
		var radius    = '';
		var longitude = '';
		var latitude  = '';
		var skills    = '';
		var level     = '';
		var params    = '';

		if ( $( '#user_term' ).val() ) {
			term   = validateInputContent( $( '#user_term' ).val() );
			term   = term.replace( /\s+/g, '-' ).toLowerCase();

			params = params + '&term=' + term;
		}

		if ( $( '#user_location' ).val() ) {
			location  = validateInputContent( $( '#user_location' ).val() );
			location  = location.replace( /\s+/g, '-' ).toLowerCase();
			params    = params + '&location=' + location;

			longitude = validateInputContent( $( '#user_longitude' ).val() );
			params    = params + '&longitude=' + longitude;

			latitude  = validateInputContent( $( '#user_latitude' ).val() );
			params    = params + '&latitude=' + latitude;
		}

		if ( $( '#user_radius' ).val() ) {
			radius = validateInputContent( $( '#user_radius' ).val() );
			radius = radius.replace( /\s+/g, '-' ).toLowerCase();

			params = params + '&radius=' + radius;
		}

		if ( $( '#user_skills' ).val() ) {
			skills = $( '#user_skills' ).val();
			skills = skills.join( '|' );
			skills = validateInputContent( skills );
			skills = skills.replace( /\s+/g, '-' ).toLowerCase();

			params = params + '&skills=' + skills;
		}

		if ( $( '#user_level' ).val() ) {
			level = $( '#user_level' ).val();

			params = params + '&level=' + level;
		}

		if ( params != '' ) params = '?' + params.substring( 1 );

		addLoader( '.user-info-wrapper' );

		history.pushState( null, "page 2", wpj_vars.page_url + params );

		jQuery.ajax({ /* Displays the searched result */
			type : 'post',
			url  : wpj_vars.ajaxurl,
			data : {
				action       : 'search_users_action',
				term         : term,
				location     : location,
				radius       : radius,
				latitude     : latitude,
				longitude    : longitude,
				skills       : skills,
				level        : level
			},
			success: function( response ) {
				$( '.js-user-info-wrapper' ).replaceWith( response );
				
				wpj_display_load_more_button();
			}
		});

	}, 500 ) );

});