// JavaScript Document
// **BEGIN GENERIC VALIDATION FUNCTIONS**
// general purpose function to see if an input value has been entered at all
function isEmpty(inputStr) {
	if (inputStr == "" || inputStr == null) {
		return true
	}
	return false
}

// function to determine if value is in acceptable range for this application
function inRange(inputStr, lo, hi) {
	var num = parseInt(inputStr, 10)
	if (num < lo || num > hi) {
		return false
	}
	return true
}
// **END GENERIC VALIDATION FUNCTIONS**
function validateMonth(field, bypassUpdate) {
	var input = field.value
	if (isEmpty(input)) {
		alert("Este campo deve ser preenchido.")
		select(field)
		return false
	} else {
		input = parseInt(field.value, 10)
		if (isNaN(input)) {
			alert("Somente números são aceitos.")
			select(field)
			return false
		} else {
			if (!inRange(input,1,12)) {
				alert("Entre um número entre 1 (Janeiro) e 12 (Dezembro).")
				select(field)
				return false
			}
		}
	}
/*	if (!bypassUpdate) {
		calcDate()
	}*/
	return true
}

function validateDate(field) {
	var input = field.value
	if (isEmpty(input)) {
		alert("Este campo deve ser preenchido.")
		select(field)
		return false
	} else {
		input = parseInt(field.value, 10)
		if (isNaN(input)) {
			alert("Somente números são aceitos.")
			select(field)
			return false
		} else {
			var monthField = document.resumo.month
			if (!validateMonth(monthField, true)) return false
			var monthVal = parseInt(monthField.value, 10)
			var monthMax = new Array(31,31,29,31,30,31,30,31,31,30,31,30,31)
			var top = monthMax[monthVal]
			if (!inRange(input,1,top)) {
				alert("Entre um número entre 1 e " + top + ".")
				select(field)
				return false
			}
		}
	}
	//calcDate()
	return true
}

function validateYear(field) {
	var input = field.value
	if (isEmpty(input)) {
		alert("Este campo deve ser preenchido.")
		select(field)
		return false
	} else {
		input = parseInt(field.value, 10)
		if (isNaN(input)) {
			alert("Somente números são aceitos.")
			select(field)
			return false
		} else {
			if (!inRange(input,1900,2100)) {
				alert("Entre um número entre 1900 e 2100.")
				select(field)
				return false
			}
		}
	}
	//calcDate()
	return true
}

function select(field) {
	field.focus()
	field.select()
}

function checkForm(form) {
	if (validateDate(form.dia)) {
		if (validateMonth(form.mes)) {
			if (validateYear(form.ano)) {
				return true
			}
		}
	}
	return false
}

function validateForm(formName) 
{
	var isValid = true;
	var form = document.getElementById(formName);
	
	for (var c = 0; c < form.elements.length; c++) {
		if (form.elements[c].value == "" || form.elements[c].value == null) {
			isValid = false;
		} 
	}

	if (isValid) {
		form.submit();
	} else {
		alert("Existem campos obrigatorios vazios.\nFavor preencher todos os campos do formulario.");
	}
}