function getRandId () {
	var rn = $A($R(1, 9));
	var rl = $A($R('a', 'z'));
	var i = 10;
	var id = '';

	for (; i > 0; --i)
		id += rl[getRandom (0, rl.length)] + rn[getRandom (0, rn.length)];

	return id;
}

function getRandom (min, max) {
	return Math.floor (Math.random() * max + min);
}

function setPopupable (idLink, idImgContainer, idImg) {
	var link = $(idLink);
	var imgContainer = $(idImgContainer);

	Event.observe (window, 'load', function () {
		link.observe ('mouseover', showPopup.curry (link, imgContainer, idImg));
	});
}

function showPopup (link, imgContainer, idImg, e) {
	var tp = window.scrollY + e.clientY - 200;
	var lf = e.clientX + 30;
	var img = $(idImg);

	if (tp < 0)
		tp += 200;

	imgContainer.writeAttribute ({style: 'left: '+lf+'px; top: '+tp+'px'});
	$$ ('.cinfo').invoke ('hide');

	imgContainer.show ();
	img.fire ('widget:view');

	link.observe ('mouseout', hidePopup.curry (imgContainer, link));
}

function hidePopup (imgContainer, link, e) {
	if (!e.target.descendantOf (imgContainer)) {
		imgContainer.hide ();
		link.stopObserving ('mouseout', hidePopup);
	}

	e.stop ();
}

function setInfos (line, idImgContainer, idLinkContainer, idBefore, idImg) {
	var url = './addon/addon-functions.php';

	new Ajax.Updater (idImgContainer, url, {
		method: 'post',
		parameters: {content: line, idImgContainer: idImgContainer, linkContainer: idLinkContainer, beforeContainer: idBefore, idImg: idImg},
		evalScripts: true
	});
}

function makeCard (line) {
	var idBeforeContainer = getRandId ();
	var idLink = getRandId ();
	var idLinkContent = getRandId ();
	var idImgContainer = getRandId ();
	var idLinkContainer = getRandId ();
	var idImg = getRandId ();

	var rg = /^([0-9 ]*)([^0-9!"#$%&()*+./:;?@\\\_`{|}~]+)(.*)$/;

	line = line.unescapeHTML ();

	if (rg.test (line)) {
		line.sub (rg, function (matches) {
			document.write ('<span id="'+idBeforeContainer+'"></span>');
			document.write ('<span id="'+idLinkContainer+'">'+line+'</span>');
			document.write ('<div id="'+idImgContainer+'" class="tablebg cinfo" style="display:none;">&nbsp;</div>');

			setInfos (line, idImgContainer, idLinkContainer, idBeforeContainer, idImg);
		});
	}
	else {
		document.write (line.escapeHTML ());
	}
}

function makeDeck (deck) {
	var arr = deck.split ("<br />");

	arr.each (function (line) {
		if (!line.blank ())
			makeCard (line);

		document.write ("<br />");
	});
}
