//
// date_val.js
//
// Date validation routines
//

function verifyDayMonth(month,day,year) {

    // first we need to check to see that this day is in the future, and not in the past
    var currentDate = new Date();

    var givenDate = new Date();

    if (year < 100)    
        givenDate.setFullYear(Math.floor(currentDate.getFullYear() / 100) + year, month-1, day);
    else
        givenDate.setFullYear(year, month-1, day);

    if (givenDate < currentDate)
        return false;

    var monthDays = new Array(12);

    // first we determine if it's a leap year (leap years have 29 days for february)
    if (year % 4 == 0) {
        // it's a leap year, february will have 29 days.
        monthDays[0] = 31; // jan
        monthDays[1] = 29; // feb
        monthDays[2] = 31; // mar
        monthDays[3] = 30; // apr
        monthDays[4] = 31; // may
        monthDays[5] = 30; // jun
        monthDays[6] = 31; // jul
        monthDays[7] = 31; // aug
        monthDays[8] = 30; // sep
        monthDays[9] = 31; // oct
        monthDays[10] = 30; // nov
        monthDays[11] = 31; // dec
    } else {
        // it's *not* a leap year, february will have 28 days.
        monthDays[0] = 31; // jan
        monthDays[1] = 28; // feb
        monthDays[2] = 31; // mar
        monthDays[3] = 30; // apr
        monthDays[4] = 31; // may
        monthDays[5] = 30; // jun
        monthDays[6] = 31; // jul
        monthDays[7] = 31; // aug
        monthDays[8] = 30; // sep
        monthDays[9] = 31; // oct
        monthDays[10] = 30; // nov
        monthDays[11] = 31; // dec
    }

    if (month < 1 || month > 12)
        return false;
    
    var daysInThisMonth = monthDays[month-1];
    
    if (day < 1 || day > daysInThisMonth)
        return false;

    return true;
}

function verifyDateField(s) {
    var Reg_fullyear = /([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/;
    
    var Reg_halfyear = /([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{2})/;

    var groups = Reg_fullyear.exec(s);

    if (groups != null) {
        return verifyDayMonth(groups[1], groups[2], groups[3]);    
    } else {
        groups = Reg_halfyear.exec(s);
        if (groups != null) {
            return verifyDayMonth(groups[1], groups[2], groups[3]);     
        } else {
            return false;        
        }
    }

    return true;
}

