var DEFAULT_RADIUS = 100;
var PANORAMIO_URL = "panoramio.asp?order=popularity&set=public&from=0&to=15";
var DELTA_LAT = 0.00000898; // approx 1 metre in degrees latitude
var DELTA_LNG = 0.00001525; // approx 1 metre in degrees longitude

var currentPhotoList = null;
var currentPhotoNumber = -1;

function resetRadius(r) {
	var url = makeURL (lat, lng, r);
	getPhotoList(url);
}

function makeURL(lat, lng, r) {
	var incrX = DELTA_LNG * r;
	var incrY = DELTA_LAT * r;
	var bb = "&minx=" + (lng - incrX) +
			 "&miny=" + (lat - incrY) +
			 "&maxx=" + (lng + incrX) +
			 "&maxy=" + (lat + incrY) +
			 "&size=medium";
	return PANORAMIO_URL + bb;
}

function getPhotoList(url) {
	req = getXMLHTTPRequest();
	req.open("GET", url, true);
	req.onreadystatechange = updatePhotos;
	req.send(null);
}

function updatePhotos() {
	// ignore intermediate statuses and failure responses
	if (req.readyState != 4) return;
	if (req.status != 200) return;
	response = window.eval("("+ req.responseText + ")");
	window.currentPhotoList = response.photos;
	setFirstPhoto();
}

function setFirstPhoto() {
	if (currentPhotoList.length == 0) {
		var img = window.document.images.img0;
		img.src = "clear.gif";
		document.getElementById("credits").style.display = "none";
		}
	else {
		currentPhotoNumber = 0;
		replacePhoto(currentPhotoList[currentPhotoNumber]);
		}
}

function getNextPhoto() {
	currentPhotoNumber += 1;
	if (currentPhotoNumber == currentPhotoList.length)
		currentPhotoNumber = 0;
	replacePhoto(currentPhotoList[currentPhotoNumber]);
}

function getPrevPhoto() {
	if (currentPhotoNumber == 0)
		currentPhotoNumber = currentPhotoList.length - 1;
	else
		currentPhotoNumber -= 1;
	replacePhoto(currentPhotoList[currentPhotoNumber]);
}

function replacePhoto(p) {

	var img = window.document.images.img0;
	img.src = p.photo_file_url;

	var title = (p.photo_title == "") ? "Untitled": '"' + p.photo_title + '"';
	var author = "author <a class='Ncontext' href='" + p.owner_url + "'>" + p.owner_name + "</a>";

	img.alt = "Panoramio photo: " + title + ", by " + p.owner_name;

	document.getElementById("photoCredit").innerHTML = "<span>" + title + "&nbsp;&nbsp;&nbsp;" + author + "</span>";
	document.getElementById("photoCount").innerHTML = "<span>this <a class='Ncontext' href='" + p.photo_url + "'>photo</a> is number " +
		(1 + currentPhotoNumber) + " of " + currentPhotoList.length + "</span>";
	document.getElementById("credits").style.display = "inline";
}

function getXMLHTTPRequest() {
	var request;
	try {
		request = new XMLHttpRequest();
		}
	catch(err0) {
		try {
			request = new ActiveXObject("Msml2.XMLHTTP");
			}
		catch(err1) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
				}
			catch(err2) {
				request = false;
				}
			}
		}
	return request;
}

