function getElm(id) {
	return document.getElementById(id);
}

function saveFileID(id, file) {
	document.forms[0].elements[id].value = file;
}

function showElement(id) {
	getElm(id).style.left = 'auto';
}

function hideElement(id) {
	getElm(id).style.left = '-999em';
}

function setBigPicture(pic) {
	alert(getElm('big_picture'));
}

function findX(obj) {
	return obj.offsetLeft + (obj.offsetParent ? findX(obj.offsetParent) : 0);
}

function findY(obj) {
	return obj.offsetTop + (obj.offsetParent ? findY(obj.offsetParent) : 0);
}

function showPopup(id, mainId, fakeHeight) {
	var mainX = findX(getElm(mainId));
	var mainY = findY(getElm(mainId));

	// Try to place popup to the left of the field
	var x = mainX - getElm(id).offsetWidth;

	// If it ends up too far to the left, place it on the right side.
	if (x < 50)
		x = mainX + getElm(mainId).offsetWidth;

	var y = mainY + getElm(mainId).offsetHeight;
	if (fakeHeight)
		// We can't reliably poll the height of the popup, since the image in it is dynamically loaded.
		y -= 500;
	else
		y -= getElm(id).offsetHeight;

	if (y < 0)
		y = 0;

	// If it's above the top of the window, move it
	if (window.pageYOffset && y < window.pageYOffset) // for Firefox
		y = window.pageYOffset;

	if (document.body.scrollTop && y < document.body.scrollTop) // for Explorer
		y = document.body.scrollTop;

	getElm(id).style.left = x;
	getElm(id).style.top = y;
}

function hidePopup(id) {
	getElm(id).style.left = '-999em';
}

function loadPicture(id, url) {
	getElm(id).src = url;
}

function findSelectIndex(key, value) {
	e = document.forms[0].elements[key];
	for (var i = 0; i < e.options.length; i++) {
		if (e.options[i].value == value)
			return i;
	}
	return -1;
}

var picLast = new Array();
var formData = new Array();

function selectItem(id, num, idPic) {
	if (picLast[id] && picLast[id] != idPic) {
		hideElement(picLast[id]);
	}
	showElement(idPic);

	picLast[id] = idPic;

	getElm(id).value = num;

	if (formData[id] && formData[id][num]) {
		for (var key in formData[id][num]) {
			if (!document.forms[0].elements[key])
				continue;
			var value = formData[id][num][key];
			var index = findSelectIndex(key, value);
			document.forms[0].elements[key].selectedIndex = index;
		}
	}
}

function resetPopups() {
	for (var id in picLast) {
		hideElement(picLast[id]);
		getElm(id).value = '';
	}
}

function registerFormData(id, num, key, value) {
	if (!formData[id])formData[id] = new Array();
	if (!formData[id][num])formData[id][num] = new Array();
	formData[id][num][key] = value;
}