// This key only works from the kvdb.net domain, for demo purposes.
// Replace this auth_key with your own.
var pro6pp_auth_key = "n5SEkGlaFzbkWDfj";


var pro6pp_cache = {};
function pro6pp_cached_get(url, callback) {
	key = escape(url);
	if (pro6pp_cache.hasOwnProperty(key)) {
		callback(pro6pp_cache[key]);
	} else {
		$.getJSON(url + "&callback=?", function(data) {
			pro6pp_cache[key] = data;
			callback(data);
		});
	}
}
	
function pro6pp_range() {
	$('.pro6pp_range_message').empty();
	var postcode = $('.pro6pp_range_postcode').val();
	var range = $('.pro6pp_range').val();
	// User puts in range in kilometers, API uses meters.
	range = parseInt(range) * 1000;
	var url = "http://api.pro6pp.nl/v1/range?auth_key=" + pro6pp_auth_key + "&nl_fourpp=" + postcode + "&range=" + range;
	pro6pp_cached_get(url, pro6pp_range_fillin);
}

function pro6pp_range_fillin(json) {
	if (json.status == 'ok')
	{
		if (json.results.length == 0)
		{
			$('.pro6pp_range_message').html("Geen resultaten gevonden");
		} else {
			$.each(json.results, function(i, result) {
				$('.pro6pp_range_message').append(result.nl_fourpp + "[" + result.lat + ", " + result.lng + "]<br/>");
			});
		}
	}
	else
	{
		$('.pro6pp_message').html(json.error.message);
	}
}

$(document)
	.ready(function() {
	$('.pro6pp_range_submit').click(pro6pp_range);
});

