/**
* MAIN TRACKER FUNCTION
* AUTHOR: ZUL ZOLKAFFLY
*/

function goTrk(callback) {
	var data = {};
	$.get("http://ipinfo.io", function(response) {
		data['io'] = response;
		data['org'] = response['org'];
		data['ip'] = response['ip'];
		data['href'] = window.location.href;
		
		if (!navigator.geolocation) {
			console.log("%c Geolocation is not supported by your browser","color: red;");
			return;
		}
		
		function parseresult(result) {
			data['full'] = result.formatted_address;
			for (var i=0; i < result.address_components.length; i++) {
				for (var j=0; j < result.address_components[i].types.length; j++) {
					if (result.address_components[i].types[j] == "country") {
						country = result.address_components[i];
						data['country_long'] = country.long_name;
						data['country_short'] = country.short_name;
					}
					
					if (result.address_components[i].types[j] == "locality") {
						city = result.address_components[i];
						data['city'] = city.long_name;
					}
					
					if ((result.address_components[i].types[j]).indexOf('administrative') >= 0) {
						state = result.address_components[i];
						data['state'] = state.long_name;
					}
					
					if (result.address_components[i].types[j] == "postal_code") {
						postcode = result.address_components[i];
						data['postcode'] = postcode.long_name;
					}
					
					if (result.address_components[i].types[j] == "route") {
						route = result.address_components[i];
						data['route'] = route.long_name;
					}
				}
			}
		}

		function success(position) {
			var latitude  = position.coords.latitude;
			var longitude = position.coords.longitude;
			var geocoder = new google.maps.Geocoder();
			
			data['lat'] = latitude;
			data['long'] = longitude;
			
					geocoder.geocode({'latLng': new google.maps.LatLng(latitude,longitude)}, function(results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							parseresult(results[0]);							
							callback(data);
						} else {
							console.log("%c Geocoder failure: " + status, 'color:red;');
						}
					});
					
					if(position.coords.accuracy <= 1000) {
						navigator.geolocation.clearWatch(watchid);
						return;
					}
		}

		function error() {
			console.log("%c Geocoder failure: unable to retrieve location.", 'color:red;');							
			callback(data);
		}
		
		var watchid = navigator.geolocation.watchPosition(success, error, {
			enableHighAccuracy : true, 
			maximumAge         : 30000, 
			timeout            : 60000
		});
	}, 'jsonp');
}