//----------------------------------------
//  days per month accumulation arrays
var accumulate   = new Array( 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
var accumulateLY = new Array( 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)


//----------------------------------------
//  set the form to today's date
function setDate(form) {

	//  get today's date object
    var today = new Date()

	//  set year
    var y = today.getYear()
	form.year.value = (y < 1000) ? y += 1900 : y

	//  set month and day
	form.month.value = (today.getMonth() + 1)
	form.day.value = today.getDate()
}


//----------------------------------------
//  reformat year for y2k
function y2k(y) {
	return (y < 1000) ? y + 1900 : y
}


//----------------------------------------
//  determine if year is leap year
function leapYear(year) {
	var y = y2k(year)
	return (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) ? 1 : 0
}


//----------------------------------------
//  zero-pad a string
function pad0(string,len) {
	var pad = ""
	len -= String(string).length
	for (var i = 0; i < len; i++)
		pad += "0"
	return (pad + string)
}


//----------------------------------------
//  generate a sample lot number
//  year, year's day number, 01 - 0528201
function setLotNum(form) {
	form.lotnum.value = (form.year.value.substr(2,4) + form.day_result.value + "01")
}


//----------------------------------------
//  calculate the year's day number from the month, day, and year
function calcDay(form) {

	var days = parseInt(form.day.value)
	var month = (form.month.value - 1)

	if (leapYear(form.year.value))
		days += accumulateLY[month]
	else
		days += accumulate[month]

	form.day_result.value = pad0(days,3)

	//  update lot number
	setLotNum(form)
}


//----------------------------------------
//  calculate the month and day from the year's day number and year
function calcDays(form) {

	var days = form.day_result.value
	var year = form.year.value

	//  catch invalid days
	if ( (days < 1) || (days > 365) ) {
		if (days > 365) {
			if (leapYear(year))
				days = 366
			else
				days = 365
		} else {
			days = 1
		}
	}

	var acc = accumulate
	if (leapYear(year))
		acc = accumulateLY

	for (i = (acc.length-1); i >= 0; i--)
		if (days > acc[i]) {
			form.month.value = (i + 1)
			form.day.value   = (days - acc[i])
			break
		}

	//  reformat number
	form.day_result.value = pad0(days,3)

	//  update lot number
	setLotNum(form)
}


//----------------------------------------
//  reset the date and year's day number
function resetDate(form) {

	setDate(form)
	calcDay(form)
}

