﻿var monthExpr = new RegExp("^(0[1-9]|[2-9]|1[0-2])","i");
var dayExpr = new RegExp("^(0[1-9]|[1-2][0-9]|3[01]|[4-9])", "i");
var yearExpr = new RegExp("^((19|2[0-9])[0-9]{2})", "i");

var validExpr = new RegExp("^[0-9]+$", "i");

var SUGGESTION_COLOR = "#c0c0c0";
var EDITING_COLOR = "#537746";
var VALID_COLOR = "#a16517";

var ACTIVE_COLOR = "#FFFFFF";
var INACTIVE_COLOR = "#FFFFFF";

var integerFieldValues = new Array();		
function IntegerFieldKeyPress(elem, nextId, expression) {
	if (elem.value != integerFieldValues[elem.id]) {
		integerFieldValues[elem.id] = elem.value;
		
		if (expression.test(elem.value)) {
			var nextElem = document.getElementById(nextId);
			
			try {
				nextElem.focus();
			} catch (e) { }
		} else if (!validExpr.test(elem.value)) {
			elem.value = "";
		}				
	}
}

function InitializeFocus(elem) {
	elem.style.color = EDITING_COLOR;
	elem.style.backgroundColor = ACTIVE_COLOR;	
	
	integerFieldValues[elem.id] = elem.value;
		
	if (validExpr.test(elem.value)) {		
		try {
			elem.select();
		} catch (e) { }
	} else {
			elem.value = "";
	}
}

function CleanupBlur(elem, maxValue, suggestionText) {
	var value = elem.value;

	if ((value.indexOf("0") == 0) && (value.length > 1)) {
		value = value.substr(1);
	}
	
	try {
		value = parseInt(value);
	} catch (e) {		
		value = 0;
	}

	if ((value > 0) && (value <= maxValue)) {
		elem.style.color = VALID_COLOR;
	} else {
		elem.style.color = SUGGESTION_COLOR;
		elem.value = suggestionText;
	}
	
	elem.style.backgroundColor = INACTIVE_COLOR;
}

var DOBMonthId = "DOBMonth";
var DOBDayId = "DOBDay";
var DOBYearId = "DOBYear";
var SubmitAgeId = "SubmitButton";

function SetupEvents() {
	var elem = document.getElementById(DOBDayId);
	try{
	    elem.onfocus = function () { InitializeFocus(this); }
	    elem.onblur = function () { CleanupBlur(this, 31, 'DD'); }
	    elem.onkeyup = function () { IntegerFieldKeyPress(this, DOBYearId, dayExpr); }
	} catch(e){}
	
	try {
		elem.setAttribute("autocomplete", "OFF");
	} catch(e) { }

	elem = document.getElementById(DOBYearId);
	
	try{
	    elem.onfocus = function () { InitializeFocus(this); }
	    elem.onblur = function () { CleanupBlur(this, 2100, 'YYYY'); }
	    elem.onkeyup = function () { IntegerFieldKeyPress(this, SubmitAgeId, yearExpr); }
	} catch(e) { }
	
	
	try {
		elem.setAttribute("autocomplete", "OFF");
	} catch(e) { }
	
	elem = document.getElementById(SubmitAgeId);
	
	elem = document.getElementById(DOBMonthId);
	
	try{
	    elem.onfocus = function () { InitializeFocus(this); }
	    elem.onblur = function () { CleanupBlur(this, 12, 'MM'); }
	    elem.onkeyup = function () { IntegerFieldKeyPress(this, DOBDayId, monthExpr); }
	} catch(e) { }
	
	try {
		elem.setAttribute("autocomplete", "OFF");
	} catch(e) { }
	
	try {
	    elem.focus();
	} catch(e) { }
}