var setLocationByIPCalled = false;

$( document ).ready(function() {
	// USES THE <?=$Site->core->getDomain()?>
	var getDomain = $('#getDomain').val();
});

// SETTING VARIABLES SO THEY ARE DEFINED
var latitude, longitude, stateSelect, zipCode, city;

// USES GEOLOCATION TO SET THE LOCATION
function getLocation() {
	if (typeof isSecureContext == 'undefined' || !isSecureContext) {
		return false;
	}

	if($.cookie("posLat") && $.cookie("posLon")) {
		latitude  = $.cookie("posLat");
		longitude = $.cookie("posLon");
		accuracy  = $.cookie("posAccuracy");
		getZipByCoordinates();
		// getStateByZip();
		// getCityByZip();
	} else {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(success,error,{enableHighAccuracy:true, timeout:10000}); // This loads the location once.
			//navigator.geolocation.watchPosition(success,error,{timeout:10000});  // This reloads the location in a loop.
		} else {
			// THIS WILL SET IT ALTERNATIVELY BY IP IF IT FAILS TO SET IT BY GEOLOCATION
			setLocationByIP();
		}
	}
}

function success(position) {
	latitude = position.coords.latitude;
	longitude = position.coords.longitude;
	accuracy = position.coords.accuracy;

	$.cookie("posLat", latitude);
	$.cookie("posLon", longitude);
	$.cookie("posAccuracy", accuracy);

	getZipByCoordinates();
	// getStateByZip();
	// getCityByZip();
}

function error() {
	latitude = null;
	longitude = null;

	// THIS WILL SET IT ALTERNATIVELY BY IP IF IT FAILS TO SET IT BY GEOLOCATION
	setLocationByIP();
}

// SETS THE LOCATION BY IP, CITY, STATE, ZIP AND MORE
function setLocationByIP(){

	if (setLocationByIPCalled) {
		return;
	}

	setLocationByIPCalled = true;

	var requestURL = '/store/ajax-set-location-by-ip.html?ajax=true';

	requestURL = requestURL.replace(/\s/g, '');

	$.ajax({
        headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },

		url: requestURL,
		async : true,
		success: function (response) {
			fileExists = true;

			// ACS Rollbar #54213: endpoints now return application/json, so jQuery already
			// parses the response into an object. Only JSON.parse when it's still a string,
			// otherwise $.parseJSON(object) threw: "[object Object]" is not valid JSON.
			var result = (typeof response === 'string') ? JSON.parse(response) : response;

			ip = result.ip;
			city = result.city;
			state = result.state;
			// countryName = result.countryName;
			// countryCode = result.countryCode;
			latitude = result.latitude;
			longitude = result.longitude;
			// currencyCode = result.currencyCode;
			// currencySymbol = result.currencySymbol;
			// currencyConverter = result.currencyConverter;

			$(".location_city").text(city);
			$(".location_state").text(state);

			if (city !== null && city !== '') {
				localStorage.setItem('location_city', city);
			}

			if (state !== null && state !== '') {
				localStorage.setItem('location_state', state);
			}

			//Set zip code
			zipCode = result.postalCode;
			$(".location_zip").text(result.postalCode);

			if(result.postalCode !== null && result.postalCode !== ''){
				localStorage.setItem('location_zip', result.postalCode);
			}
			//Set zip code

			//Set state
			if (result) $('#state').val(result.regionCode);
			stateSelect = result.regionCode;

			$(".location_state").text(stateSelect);

			if (stateSelect !== null && stateSelect !== '') {
				localStorage.setItem('location_state', stateSelect);
			}

			//Set city
			$(".location_city").text(city);

			if (city !== null && city !== '') {
				localStorage.setItem('location_city', city);
			}
			//Set city

			// getZipByCoordinates();
		}
	});

}


// SETS THE ZIP CODE BY COORDINATES
function getZipByCoordinates(){
	var requestURL = '/store/ajax_get_postal_code_from_coordinates.html?ajax=true&latitude='+ latitude +'&longitude=' +longitude;

	$.ajax({
        headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },

		url: requestURL,
		async : true,
		success: function (response) {
			result = response;
			fileExists = true;

			zipCode = result;
			$(".location_zip").text(zipCode);

			if(zipCode !== null && zipCode!== ''){
				localStorage.setItem('location_zip', zipCode);
			}

			getStateByZip();
			getCityByZip();
		}
	});

}


// SETS THE STATE BY POSTAL CODE
function getStateByZip(zip){
	if(zip != undefined){
		zipCode = zip;
	}
	var requestURL = '/store/ajax-get-state-from-postal.html?ajax=true&zip='+ zipCode;

	requestURL = requestURL.replace(/\s/g, '');

	$.ajax({
        headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },

		url: requestURL,
		async : true,
		success: function (response) {
			result = response;
			fileExists = true;

			if (result) $('#state').val(result);
			stateSelect = result;
			$(".location_state").text(stateSelect);

			if(stateSelect !== null && stateSelect !== ''){
				localStorage.setItem('location_state', stateSelect);
			}
		}
	});
}


// SETS THE CITY BY POSTAL CODE
function getCityByZip(zip){
	if(zip != undefined){
		zipCode = zip;
	}

	var requestURL = '/store/ajax-get-city-from-postal.html?ajax=true&zip='+ zipCode;

	requestURL = requestURL.replace(/\s/g, '');

	$.ajax({
        headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },

		url: requestURL,
		async : true,
		success: function (response) {
			result = response;
			fileExists = true;

			citySelect = result;
			$(".location_city").text(citySelect);

			if(citySelect !== null && citySelect !== ''){
				localStorage.setItem('location_city', citySelect);
			}
		}
	});
}
