/*
    INSTALLATION INSTRUCTIONS

    1. copy this line into your source code to your <HEAD> section
        <SCRIPT type="text/javascript" src="/scripts/selectDate.js"></SCRIPT>

    2. Copy the code below of the page to your document

        <FORM name="yourFormName">
            <SELECT name="yourDateSelectionFieldDay"></SELECT> <!--optional-->
            <SELECT name="yourDateSelectionFieldMonth"
                onchange="changeOptionDays('yourFormName.yourDateSelectionField')">
            </SELECT>
            <SELECT name="yourDateSelectionFieldYear"
                onchange="changeOptionDays('yourFormName.yourDateSelectionField')">
            </SELECT>
            <SCRIPT>
                <!-- the first number is the number of years before to show -->
                <!-- the second number is the number of years after to show -->
                startDateSelect('document.yourFormName.yourDateSelectionField',9,9);
                <!-- the second option is the default date -->
                setDefaultDate('document.yourFormName.yourDateSelectionField','today');
                <!-- this will keep the default in a self referential jsp program -->
                <%if (request.getParameter("yourDateSelectionFieldMonth") != null) {%>
                    setActualDate('yourFormName.yourDateSelectionField', 
                        <%=request.getParameter("yourDateSelectionFieldYear")%>, 
                        <%=request.getParameter("yourDateSelectionFieldMonth")%>,
                        <%=request.getParameter("yourDateSelectionFieldDay")%>);
                <%}%>
            </SCRIPT>
        </FORM>

    3. Change all references to yourFormName to the name of the form on
    your page.

    4. Change all references to yourDateSelectionField to the name of
    the field(s) on your form.

    5. to set the default change option in the second line of the
    <SCRIPT> to one of the following:
        'today'
        'yesterday'
        'tommorrow'
        'firstOfMonth'
        'lastOfMonth'
        'firstOfLastMonth'
        'lastOfLastMonth'
        'lastMonth'
        'firstOfNextMonth'
        'lastOfNextMonth'
        'nextMonth'
        'firstOfYear'
        'lastOfYear'
        'firstOfLastYear'
        'lastOfLastYear'
        'firstOfNextYear'
        'lastOfNextYear'
*/

// set todays date
var dateSelectNow = null;
var dateSelectNowDay = null;
// month is valued from 0 to 11
var dateSelectNowMonth = null;
var dateSelectNowYear = null;

function initializeDateSelect() {
	if (dateSelectNow == null)
		dateSelectNow = new Date();
	if (dateSelectNowDay == null)
		dateSelectNowDay = dateSelectNow.getDate();
	if (dateSelectNowMonth == null)
		dateSelectNowMonth = dateSelectNow.getMonth();
	if (dateSelectNowYear == null) {
		dateSelectNowYear = dateSelectNow.getYear();
		if (dateSelectNowYear < 1000)
			dateSelectNowYear += 1900;
	}
}

// function for how many days in a month
function daysInMonth(whichMonth, whichYear) {

    // 30 days hath september, april, june and november
    if (whichMonth == "Apr" || whichMonth == "Jun" || whichMonth == "Sep" || whichMonth == "Nov") 
        return 30;
    if (whichMonth == 3 || whichMonth == 5 || whichMonth == 8 || whichMonth == 10) 
        return 30;

    // all the rest have 31
    if (whichMonth != "Feb" && whichMonth != 1) 
        return 31;

    // excepting february
    if ((whichYear/400) == Math.floor(whichYear/400))
        return 29;
    if ((whichYear/100) == Math.floor(whichYear/100))
        return 28;
    if ((whichYear/4)   == Math.floor(whichYear/4))
        return 29;
    return 28;
}


// change the available days in a months
function changeOptionDays(whichField) {

    // get the screen objects
    daysObject  = newEval(whichField + "Day");
    monthObject = newEval(whichField + "Month");
    yearObject  = newEval(whichField + "Year");
    if (yearObject.length == 0) return;
    tradexObject = newEval(whichField + "TRADEX");
    if (tradexObject == null)
        tradexObject = newEval(whichField);
        

    // if there is a 'tradex' date, make the conversion
    if (tradexObject != null)
        tradexObject.value = convertToTradexDate(whichField);

    // exit if there is no date
    if (daysObject == null) return;

    // calculate the number of days in the month
    var daysThisSelection = daysInMonth(monthObject[monthObject.selectedIndex].text,
                                    yearObject[yearObject.selectedIndex].text);

    // adjust the days down if needed
    currentNumberDays = daysObject.length;
    if (currentNumberDays > daysThisSelection) {
        for (i=0; i<(currentNumberDays-daysThisSelection); i++) {
            daysObject.options[daysObject.length - 1] = null
        }
    }

    // adjust the days up if needed
    if (daysThisSelection > currentNumberDays) {
        for (i=0; i<(daysThisSelection-currentNumberDays); i++) {
            daysObject[daysObject.length] = (new Option(daysObject.length + 1));
        }
    }

    // set the selection as the first of the month if
    // the prior selection is invalid in this month
    if (daysObject.selectedIndex < 0) daysObject.selectedIndex = 0;
}


// load the month selections
function loadOptionMonths(monthObject) {

    // delete the prior options
    for (i = 0; i < monthObject.length; i++)
        monthObject.options[monthObject.length - 1] = null;

    // load the options
    for (i = 1; i <= 12; i++) {
        switch (i) {
            case 1:
                monthObject[monthObject.length] = (new Option("Jan","01"));
                break;
            case 2:
                monthObject[monthObject.length] = (new Option("Feb","02"));
                break;
            case 3:
                monthObject[monthObject.length] = (new Option("Mar","03"));
                break;
            case 4:
                monthObject[monthObject.length] = (new Option("Apr","04"));
                break;
            case 5:
                monthObject[monthObject.length] = (new Option("May","05"));
                break;
            case 6:
                monthObject[monthObject.length] = (new Option("Jun","06"));
                break;
            case 7:
                monthObject[monthObject.length] = (new Option("Jul","07"));
                break;
            case 8:
                monthObject[monthObject.length] = (new Option("Aug","08"));
                break;
            case 9:
                monthObject[monthObject.length] = (new Option("Sep","09"));
                break;
            case 10:
                monthObject[monthObject.length] = (new Option("Oct","10"));
                break;
            case 11:
                monthObject[monthObject.length] = (new Option("Nov","11"));
                break;
            case 12:
                monthObject[monthObject.length] = (new Option("Dec","12"));
                break;
        }
    }
}

function newEval(fieldName) {
    if (document.getElementsByName != null) {
        var fields = document.getElementsByName(fieldName);
        if (fields != null && fields.length > 0)
            return fields[0];
    }

    return eval(fieldName);
}


// function to write option years plus x and minus y
function loadOptionYears(whichField, yearsBefore, yearsAfter) {

    // get the object
    yearObject = newEval(whichField + "Year");
    if (yearObject == null)
        return;

    // delete the prior options
    for (i = 0; i < yearObject.length; i++)
        yearObject.options[yearObject.length - 1] = null;

    // load the options
	initializeDateSelect()
	for (i = 0; i < (yearsBefore+yearsAfter+1); i++) 
        yearObject[yearObject.length] = (new Option(dateSelectNowYear-yearsBefore+i));
}


////////////////////////////////////////////////////////////
// set the default values
// set the default day
function adjustDefaultDay(daysObject, defaultDay) {
    if (daysObject == null)
        return;
	if (defaultDay == null)
		return;
	if (defaultDay < 0)
		return;
	if (defaultDay > daysObject.length)
		return;
	var wrk = daysObject[defaultDay-1];
	if (wrk == null)
		return;
	wrk.selected = true;
}

// set the selected month to today
function adjustDefaultMonth(monthObject, defaultMonth) {
    if (monthObject == null)
        return;
    if (defaultMonth == null)
        return;
	if (defaultMonth < 0)
		return;
	if (defaultMonth > monthObject.length)
		return;
	var wrk = monthObject[defaultMonth];
	if (wrk == null)
		return;
    wrk.selected = true;
}

// adjust default year
function adjustDefaultYear(yearObject, defaultYear) {
    if (yearObject == null)
        return;
    if (defaultYear < 1000) defaultYear += 1900;
    for (i = 0; i < yearObject.length; i++) {
        if (yearObject[i].text == defaultYear) {
            yearObject[i].selected = true;
        }
    }
}

////////////////////////////////////////////////////////////
// set the date to an actual day
function setActualDate(whichField, defaultYear, defaultMonth, defaultDay) {

    // we need option pointers
    daysObject  = newEval(whichField + "Day");
    monthObject = newEval(whichField + "Month");
    if (monthObject == null) return;
    yearObject  = newEval(whichField + "Year");
    if (yearObject == null) return;
    tradexObject = newEval(whichField + "TRADEX");

    // first create a date
    var dateWork = new Date(defaultYear, defaultMonth-1, defaultDay);
    
    // now make the adjustments
    adjustDefaultYear(yearObject, dateWork.getYear());
    adjustDefaultMonth(monthObject, dateWork.getMonth());

    // if there are 'days' make the adjustment
    if (daysObject != null) {
        changeOptionDays(whichField);
        adjustDefaultDay(daysObject, dateWork.getDate());
    }

    // if there is a 'tradex' date, make the conversion
    if (tradexObject != null)
        tradexObject.value = convertToTradexDate(whichField);
}

// set the default date to one of several options
function setDefaultDate(whichField, dateDescription) {

    // we need option pointers
    daysObject  = newEval(whichField + "Day");
    monthObject = newEval(whichField + "Month");
    if (monthObject == null)
        return;
    yearObject  = newEval(whichField + "Year");
    if (yearObject == null)
        return;
    tradexObject = newEval(whichField + "TRADEX");


    // need a new date to calculate the adjustment, assume today
    var dateWork = new Date();;

	initializeDateSelect();

    if (dateDescription == "tommorrow") 
        dateWork = new Date (dateSelectNowYear, dateSelectNowMonth, dateSelectNowDay+1);

    else if (dateDescription == "yesterday") 
        dateWork = new Date (dateSelectNowYear, dateSelectNowMonth, dateSelectNowDay-1);

    else if (dateDescription == "firstOfMonth")
        dateWork = new Date (dateSelectNowYear, dateSelectNowMonth, 1);

    else if (dateDescription == "lastOfMonth") 
        dateWork = new Date (dateSelectNowYear, dateSelectNowMonth, daysInMonth(dateSelectNowMonth, dateSelectNowYear));

    else if (dateDescription == "firstOfLastMonth" || dateDescription == "lastMonth") {
        if (dateSelectNowMonth == 0) 
            dateWork = new Date (dateSelectNowYear-1, 11, 1);
        else
            dateWork = new Date (dateSelectNowYear, dateSelectNowMonth-1, 1);
    }

    else if (dateDescription == "lastOfLastMonth") {
        if (dateSelectNowMonth == 0) 
            dateWork = new Date (dateSelectNowYear-1, 11, 31);
        else
            dateWork = new Date (dateSelectNowYear, (dateSelectNowMonth-1), daysInMonth((dateSelectNowMonth-1), dateSelectNowYear));
    }

    else if (dateDescription == "firstOfNextMonth" || dateDescription == "nextMonth") {
        if (dateSelectNowMonth == 11) 
            dateWork = new Date (dateSelectNowYear+1, 0, 1);
        else
            dateWork = new Date (dateSelectNowYear, dateSelectNowMonth+1, 1);
    }

    else if (dateDescription == "lastOfNextMonth") {
        if (dateSelectNowMonth == 11) 
            dateWork = new Date (dateSelectNowYear+1, 0, 31);
        else
            dateWork = new Date (dateSelectNowYear, dateSelectNowMonth+1, daysInMonth(dateSelectNowMonth+1, dateSelectNowYear));
    }

    else if (dateDescription == "firstOfYear") 
        dateWork = new Date (dateSelectNowYear, 0, 1);

    else if (dateDescription == "lastOfYear") 
        dateWork = new Date (dateSelectNowYear, 11, 31);

    else if (dateDescription == "firstOfLastYear") 
        dateWork = new Date (dateSelectNowYear-1, 0, 1);

    else if (dateDescription == "lastOfLastYear") 
        dateWork = new Date (dateSelectNowYear-1, 11, 31);

    else if (dateDescription == "firstOfNextYear") 
        dateWork = new Date (dateSelectNowYear+1, 0, 1);

    else if (dateDescription == "lastOfNextYear") 
        dateWork = new Date (dateSelectNowYear+1, 11, 31);

    // now make the adjustments
    adjustDefaultYear(yearObject, dateWork.getYear());
    adjustDefaultMonth(monthObject, dateWork.getMonth());
    if (daysObject != null) {
        changeOptionDays(whichField);
        adjustDefaultDay(daysObject, dateWork.getDate());
    }

    // if there is a 'tradex' date, make the conversion
    if (tradexObject != null)
        tradexObject.value = convertToTradexDate(whichField);
}


////////////////////////////////////////////////////////////
function convertToTradexYear(fourDigitYear) {

    // need a year
    if (fourDigitYear == null)
        return "";
    if (fourDigitYear.length < 4)
        return "";

    // convert a possible number to a text field
    var yearText = fourDigitYear+'';

    // decompose the year
    if (fourDigitYear < 1900)
        return "";
    else if (fourDigitYear < 2000) 
        return (yearText.substring(2,4));
    else if (fourDigitYear < 2010)
        return ("A" + yearText.substring(3,4));
    else if (fourDigitYear < 2020)
        return ("B" + yearText.substring(3,4));
    else if (fourDigitYear < 2030)
        return ("C" + yearText.substring(3,4));
    else if (fourDigitYear < 2040)
        return ("D" + yearText.substring(3,4));
    else if (fourDigitYear < 2050)
        return ("E" + yearText.substring(3,4));
    else if (fourDigitYear < 2060)
        return ("F" + yearText.substring(3,4));
    else if (fourDigitYear < 2070)
        return ("G" + yearText.substring(3,4));
    else if (fourDigitYear < 2080)
        return ("H" + yearText.substring(3,4));
    else if (fourDigitYear < 2090)
        return ("I" + yearText.substring(3,4));
    else if (fourDigitYear < 2100)
        return ("J" + yearText.substring(3,4));
    else if (fourDigitYear < 2110)
        return ("K" + yearText.substring(3,4));
    else if (fourDigitYear < 2120)
        return ("L" + yearText.substring(3,4));
    else if (fourDigitYear < 2130)
        return ("M" + yearText.substring(3,4));
    else if (fourDigitYear < 2140)
        return ("N" + yearText.substring(3,4));
    else if (fourDigitYear < 2150)
        return ("O" + yearText.substring(3,4));
    else if (fourDigitYear < 2160)
        return ("P" + yearText.substring(3,4));
    else if (fourDigitYear < 2170)
        return ("Q" + yearText.substring(3,4));
    else if (fourDigitYear < 2180)
        return ("R" + yearText.substring(3,4));
    else if (fourDigitYear < 2190)
        return ("S" + yearText.substring(3,4));
    else if (fourDigitYear < 2200)
        return ("T" + yearText.substring(3,4));
    else if (fourDigitYear < 2210)
        return ("U" + yearText.substring(3,4));
    else if (fourDigitYear < 2220)
        return ("V" + yearText.substring(3,4));
    else if (fourDigitYear < 2230)
        return ("W" + yearText.substring(3,4));
    else if (fourDigitYear < 2240)
        return ("X" + yearText.substring(3,4));
    else if (fourDigitYear < 2250)
        return ("Y" + yearText.substring(3,4));
    else if (fourDigitYear < 2260)
        return ("Z" + yearText.substring(3,4));

    // return an empty string otherwize
    else 
        return "";
}


////////////////////////////////////////////////////////////
function convertToTradexDate(whichField) {

    // we need option pointers
    daysObject  = newEval(whichField + "Day");
    monthObject = newEval(whichField + "Month");
    if (monthObject == null) return "";
    yearObject  = newEval(whichField + "Year");
    if (yearObject == null) return "";
    tradexObject = newEval(whichField + "TRADEX");


    // the work fields
    var returnDate = "";
    var wrkField = "";

    // find the selected year
    for (i = 0; i < yearObject.length; i++) {
        if (yearObject[i].selected == true) {
            wrkField = yearObject[i].text;
            break;
        }
    }

    // make sure we found the selection
    if (wrkField == "")
        return returnDate;

    // convert the yeat to tradex internal format
    returnDate = convertToTradexYear(wrkField);

    // add the month
    for (i = 0; i < monthObject.length; i++)
        if (monthObject[i].selected == true)
            returnDate += monthObject[i].value;

    // add the day if applicable
    if (daysObject != null) {
        for (i = 0; i < daysObject.length; i++) {
            if (daysObject[i].selected == true) {
                if (daysObject[i].text < 10)
                    returnDate += "0" + daysObject[i].text;
                else
                    returnDate += daysObject[i].text;
            }
        }
    }
    

    // if there is a 'tradex' date, make the conversion
    if (tradexObject != null)
        tradexObject.value = returnDate;

    // and we are done
    return returnDate;
}


////////////////////////////////////////////////////////////
// start the date selector for this series of fields
function startDateSelect(whichField, yearsBefore, yearsAfter) {

    // we need option pointers
    daysObject  = newEval(whichField + "Day");
    monthObject = newEval(whichField + "Month");
    if (monthObject == null) return;
    yearObject = newEval(whichField + "Year");
    if (yearObject == null) return;
    tradexObject = newEval(whichField + "TRADEX");

    // load the years available
    loadOptionYears(whichField, yearsBefore, yearsAfter);
    adjustDefaultYear(yearObject, dateSelectNowYear);
    
    // load the twelve months
    loadOptionMonths(monthObject);
    adjustDefaultMonth(monthObject, dateSelectNowMonth);

    // make the number of days in the month match
    changeOptionDays(whichField);

    setDefaultDate(whichField,"today");

    // if there is a 'tradex' date, make the conversion
    if (tradexObject != null)
        tradexObject.value = convertToTradexDate(whichField);
}


////////////////////////////////////////////////////////////
// start the year selector for this series of fields
function startYearSelect(whichField, allOptionText, yearsBefore, yearsAfter) {

    // we need option pointers
    yearObject = newEval(whichField + "Year");
    if (yearObject == null) return;

    // load the years available
    // delete the prior options
    for (i = 0; i < yearObject.length; i++)
        yearObject.options[yearObject.length - 1] = null;

    // add the 'all' option
    yearObject[yearObject.length] = (new Option(allOptionText,"A"));
    
    // load the year options
    var optionYear = null;
    for (i = (yearsBefore+yearsAfter); i >= 0; i--) {
        optionYear = dateSelectNowYear-yearsBefore+i;
        yearObject[yearObject.length] = (new Option(optionYear, convertToTradexYear(optionYear)));
    }

    // always default to the 'all' option
    yearObject[0].selected = true;
}


////////////////////////////////////////////////////////////
// the year select needs it's own defaulting scheme
function setDefaultYear(whichField, defaultValue) {

    // we need option pointers
    yearObject = newEval(whichField + "Year");
    if (yearObject == null) return;

    for (i = 0; i < yearObject.length; i++) {
        if (yearObject[i].value == defaultValue) {
            yearObject[i].selected = true;
        }
    }
}