var W = 60;
var H = 60;

function makeAttr(name, value) {
	return ' ' + name + '="' + value + '"';
}

function RandomPic(pic, id, name) {
	this.pic = pic;
	this.id = id;
	this.name = name;
	this.JSname = name.replace(/'/,"\\'");
	this.writePic = RandonPicWrite;
	this.writePicLinked = RandonPicWriteLinked;
	this.writeIMG = RandonPicWriteIMG;
	this.select = RandomPicSelect;
}

function RandonPicWriteIMG(path, w, h) {
	document.write("<img",
			makeAttr("src", path + "/" + this.pic + ".jpg"),
			makeAttr("border", 0),
			makeAttr("width", w == null ? W : w),
			makeAttr("height", h == null ? H : h),
			makeAttr("alt", this.name),
			">");
}

function RandonPicWrite(path, w, h) {
	this.writeIMG(path, w, h);
	document.write("&nbsp;");
}

function RandonPicWriteLinked(path, w, h) {
	document.write("<a",
			makeAttr("href","javascript:selectRandomPic(" + this.id + ");"),
			makeAttr("onmouseover", "window.status='" + this.JSname + "'; return true;"),
			makeAttr("onmouseout", "window.status=''; return true;"),
			">");
	this.writeIMG(path, w, h);		
	document.write("</a>&nbsp;");
}

function RandomPicSelect() {
	alert(this.name);
}

// returns an array of m numbers, without duplicates, in the range 0 to n - 1
function selectRandom(m, n) {
	// create an array containing the numbers 0 .. n
	var a = new Array(n);
	var i;
	for (i = 0; i < n; i++)
		a[i] = i;
	// select m from n
	for (i = 0; i < m; i++, n--) {
		// select a number in the range 0 .. n
		var r = Math.floor(Math.random() * (n));
		// swap it with the number at position n-1
		var temp = a[n-1];
		a[n-1] = a[r];
		a[r] = temp;	
		}
	// return the selected numbers
	return a.slice(n);
}

function writePics(m, path, w, h) {
	var a = selectRandom(m, pics.length);
	var i;
	for (i = 0; i < a.length; i++)
		pics[a[i]].writePic(path, w, h);
}

function writeLinkedPics(m, path, w, h) {
	var a = selectRandom(m, pics.length);
	var i;
	for (i = 0; i < a.length; i++)
		pics[a[i]].writePicLinked(path, w, h);
}

function selectRandomPic(id) {
	var i;
	for (i = 0; i < pics.length; i++)
		if (pics[i].id == id)
			pics[i].select();
}
