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

	// show/hide fields on let's meet
	$( document ).on( 'change', '.js-lets-meet-trigger', function( e ) {
		if ( this.checked ) {
			$( '.js-lets-meet-item' ).parents( '.field' ).css({ display: "flex" });
			$( '.js-lets-meet-item' ).parents( '.fields' ).css({ display: "flex" });

		} else {
			$( '.js-lets-meet-item' ).each( function() {
				$( this ).parents( '.field' ).hide();

				if ( $( this ).parents( '.field' ).siblings( '.field' ).is( ':hidden' ) ) {
					$( this ).parents( '.fields' ).hide();
				}
			});

		}
	});

});

// prompt browser html5 geolocation
function wpj_geolocation_get() {
	if ( navigator.geolocation ) {
		navigator.geolocation.getCurrentPosition( wpj_geolocation_success );
	}
}

// use google places api to fetch location name based on lat + lng
function wpj_geolocation_success( position ) {
	var lat = position.coords.latitude;
	var lng = position.coords.longitude;

	// check if input exists or cokie never set (so we limit requests)
	if ( ( jQuery( '.js-location-autocomplete' ).length
		|| jQuery.cookie( 'wpj_location' ) == undefined
		|| jQuery.cookie( 'wpj_lat' ) == undefined
		|| jQuery.cookie( 'wpj_lng' ) == undefined
	) ) {

		var city     = '';
		var state    = '';
		var country  = '';
		var location = '';

		// Google Places API
		if ( wpj_vars.locations_api_key && wpj_vars.locations_api === 'google' && typeof google !== 'undefined' ) {
			var geocoder = new google.maps.Geocoder();
			var latlng   = new google.maps.LatLng(lat, lng);

			// perform an educated guess for city, state and country
			geocoder.geocode({'latLng': latlng}, function(results, status) {
				if ( status == google.maps.GeocoderStatus.OK ) {
					if ( results[1] ) {
						geocode_loop:
						for ( var i = 0; i < results[0].address_components.length; i++ ) {
							for ( var j = 0; j < results[0].address_components[i].types.length; j++ ) {

								// avoid multiple loops by checking all at once
								// do not overwrite
								if ( city == ''
									&& ( results[0].address_components[i].types[j] == "locality"
										|| results[0].address_components[i].types[j] == "administrative_area_level_2" ) ) {
									city = results[0].address_components[i].long_name;
								}

								if ( state == ''
									&& results[0].address_components[i].types[j] == "administrative_area_level_1" ) {
									state = results[0].address_components[i].long_name;
								}

								if ( country == ''
									&& results[0].address_components[i].types[j] == "country" ) {
									country = results[0].address_components[i].long_name;
								}

								// break loops when we have all data
								if ( city != '' && state != '' && country != '' ) {
									break geocode_loop;
								}
							}
						}

						location = city;
						location += ( state != '' ) ? ', ' + state : '';
						location += ( country != '' ) ? ', ' + country : '';

						// autofill input
						wpj_geolocation_autofill( location, lat, lng );
					}
				}
			});

		}

		// TomTom Search API
		else if ( wpj_vars.locations_api === 'tomtom' ) {
			jQuery.ajax({
				type: 'GET',
				url: 'https://api.tomtom.com/search/2/reverseGeocode/' + lat + ',' + lng + '.json?key=' + wpj_vars.tomtom_api_key,
				dataType: 'json',
				success: function( response ) {
					if ( response.addresses[0] ) {
						location = response.addresses[0].address.freeformAddress;
						wpj_geolocation_autofill( location, lat, lng );
					}
				},
				error: function( response ) {
					console.log( 'Error: ' + response );
				},
			});
		}
	}
}

// store cookies and autofill inputs
function wpj_geolocation_autofill( location, lat, lng ) {
	// autofill from cookies, if google places api doesn't work or is slow
	if ( location !== undefined
		&& lat !== undefined
		&& lng !== undefined
	) {
		jQuery.cookie( 'wpj_location', location, { expires: 7, path: '/' } );
		jQuery.cookie( 'wpj_lat', lat, { expires: 7, path: '/' } );
		jQuery.cookie( 'wpj_lng', lng, { expires: 7, path: '/' } );
	} else {
		location = jQuery.cookie( 'wpj_location' );
		lat = jQuery.cookie( 'wpj_lat' );
		lng = jQuery.cookie( 'wpj_lng' );
	}

	// autofill only if all values are populated and input exists
	if ( location != '' && lat != '' && lng != ''
		&& jQuery( '.js-location-autocomplete' ).length ) {
		jQuery( '.js-location-autocomplete' ).each( function() {

			// do not autofill if user edited/editing the field
			// do not autofill after first search query (already filled or emptied by the user)
			var location_input = jQuery( this );
			if ( ! location_input.is( 'input' ) ) {
				location_input = location_input.find( 'input' );
			}

			if ( ( getUrlParameter( 'location' ) === undefined
				&& getUrlParameter( 'latitude' ) === undefined
				&& getUrlParameter( 'longitude' ) === undefined )
				&& ( location_input.val() == '' || location_input.attr( 'data-autofilled' ) )
				&& ! location_input.is( ':focus' )
			) {
				// allow cookie based autofill to be overwritten by api
				location_input.attr( 'data-autofilled', 'true' );
				location_input.val( location ).trigger( 'change' );
				location_input.next( 'input' ).val( lat ).trigger( 'change' );
				location_input.next( 'input' ).next( 'input' ).val( lng ).trigger( 'change' );
			}

			// stop autofill if user edited
			location_input.focus( function() {
				location_input.removeAttr( 'data-autofilled' );
			});
		});
	}
}