/*
 * (c)reated: 11-Nov-06 by Oliver Böhm
 */

now = new Date();

function readForm(elements) {
	now = readDate(elements, 0);
	birthdate = readDate(elements, 4);
	updateForm(birthdate, elements, 7);
}

/*
 * @param elements - the elements where to write the result
 * @param first - start index of the elements where to write the result
 */
function updateForm(birthdate, elements, first) {
	updateAge(birthdate, elements, first);
	updateBiorhythm(birthdate, elements, first+7);
}

/*
 * @params birthdate
 * @param elements - the elements where to write the result
 * @param first - start index of the elements where to write the result
 */
function updateAge(birthdate, elements, first) {
	var nDays = 365.25;	// 1 year = 365d 5:48:45.98, see http://de.wikipedia.org/wiki/Schaltjahr
	age = new Array(7);
	age[0] = (now - birthdate) / 1000;	// age in seconds
	age[1] = age[0] / 60;
	age[2] = age[0] / 3600;
	age[3] = age[2] / 24;			// age in days
	age[4] = age[3] / 7;			// age in weeks
	age[5] = age[3] / (nDays/12);		// age in months
	age[6] = (age[3] + 0.75) / nDays;	// age in years
	for (i = 0; i < age.length; i++) {
		elements[first+i].value = Math.floor(age[i]);
	}
}

function updateBiorhythm(birthdate, elements, first) {
	days = (now - birthdate) / 1000 / 24 / 3600;
	mental    = Math.sin(days * 2 * Math.PI / 33) * 100;
	physical  = Math.sin(days * 2 * Math.PI / 23) * 100;
	emotional = Math.sin(days * 2 * Math.PI / 28) * 100;
	elements[first  ].value = Math.round(mental) + "%";
	elements[first+1].value = Math.round(physical) + "%";
	elements[first+2].value = Math.round(emotional) + "%";
	setColor(document.getElementById("mental").style, mental);
	setColor(document.getElementById("physical").style, physical);
	setColor(document.getElementById("emotional").style, emotional);
}

function setColor(style, percent) {
	grey = Math.round(percent * 2.3);
	rg = Math.round(percent / 4);
	if (percent >= 0) {
		var red = 230 - grey;
		var blue = 230 - grey;
		var green = 230 + rg;
	} else {
		var red = 230 - rg;
		var green = 230 + grey;
		var blue = 230 + grey;
	}
	style.background = "rgb(" + red + "," + green + "," + blue + ")";
}

function readDate(elements, first) {
	day = elements[first].value;
	month = elements[first+1].value;
	year = elements[first+2].value;
	if ((day < 1) || (day > 31)) {
		window.alert("Bitte nur Tage zwischen 1 und 31 eingeben");
		elements[first].focus();
	} else if ((month < 1) || (month > 12)) {
		window.alert("Bitte nur Monate zwischen 1 und 12 eingeben");
		elements[first+1].focus();
	} else if ((year < 1900) || (year > 2100)) {
		window.alert("Bitte nur eine Jahreszahl zwischen 1900 und 2100 eingeben");
		elements[first+1].focus();
	}
	return new Date(year, month-1, day);
}

function email(text, name, domain, tld, link) {
    var link = text+"<a href='mailto:"+name+"@"+domain+"."+tld+"'>"+link+"</a>";
    document.write(link);
}
