jQuery( document ).ready( function( $ ) {
	// UPLOADERS
	$.fn.wpjDropzoneUploaderInit();
	$.fn.wpjHTML5UploaderInit();
});

( function ( $ ) {

	// Google Places API
	$.fn.wpjGoogleMapsInit = function() {
		if ( wpj_vars.locations_api_key && typeof google !== 'undefined' ) {
			if ( jQuery( '.js-location-autocomplete' ).length ) {
				jQuery( '.js-location-autocomplete' ).each( function() {
					var location_input = jQuery( this );
					if ( ! location_input.is( 'input' ) ) {
						location_input = location_input.find( 'input' );
					}

					var options = {
						componentRestrictions: {country: wpj_vars.locations_country},
						types: ['(cities)']
					}

					var autocomplete = new google.maps.places.Autocomplete( location_input[0], options );

					google.maps.event.addListener( autocomplete, 'place_changed', function() {
						var place = autocomplete.getPlace();
						if ( place.geometry ) {
							location_input.next( 'input' ).val( place.geometry.location.lat() );
							location_input.next( 'input' ).next( 'input' ).val( place.geometry.location.lng() );
						}
					});
				});
			}
		}
	}

	// TomTom Search API
	$.fn.wpjTomTomMapsInit = function() {
		if ( jQuery( '.js-location-autocomplete' ).length ) {
			jQuery( '.js-location-autocomplete' ).each( function() {
				var this_ui_input     = jQuery( this );
				var locations_country = wpj_vars.locations_country ? encodeURI( wpj_vars.locations_country.join() ) : '';

				this_ui_input.search({
					apiSettings: {
						onResponse: function(tomtomResponse) {
							var response = { results: [] };
							// translate TomTom API response to work with search
							$.each(tomtomResponse.results, function(index, item) {
								response.results.push({
									title : item.address.freeformAddress,
									lat   : item.position.lat,
									lng   : item.position.lon
								})
							});
							return response;
						},
						url: 'https://api.tomtom.com/search/2/search/{query}.json?countrySet=' + locations_country + '&key=' + wpj_vars.tomtom_api_key
					},
					fields: {
						results : 'results',
						title   : 'title',
						description: false,
						url     : false
					},
					minCharacters : 2,
					showNoResults: false,
					onSelect: function(result, response) {
						jQuery( this_ui_input.find( 'input' )[1] ).val( result.lat );
						jQuery( this_ui_input.find( 'input' )[2] ).val( result.lng );
					}
				});
			});
		}
	}

	if ( wpj_vars.locations_api_key && wpj_vars.locations_api === 'google' && typeof google !== 'undefined' ) {
		window.addEventListener( 'load', $.fn.wpjGoogleMapsInit );

	} else if ( wpj_vars.locations_api === 'tomtom' ) {
		jQuery( document ).ready( function() { $.fn.wpjTomTomMapsInit(); } );

	}

} ( jQuery ) );