// code to reformat the text box on after update.

/*
<input
    style="font-family: verdana; font-size: 8pt; width: 90px; border: 1px solid black"
    name="test_date"
    id="test_date"
    tabindex="1"
    format="%d/%m/%Y"
    type="text"
    value="19/06/2007"
/>

*/

function calendar_input_onchange(ctrl) {
    if (ctrl.getAttribute('show_time') == 1) {
        ctrl_datetimeformat(ctrl);
    } else {
        ctrl_dateformat(ctrl);
    }
    var dt = new Date();
    dt = Date.parseDate(ctrl.value, '%d/%m/%Y %I:%M');
    ctrl.value = dt.print(ctrl.getAttribute('format'));
}

function ctrl_datetimeformat(ctrl) {
    // difference: Date Format == dd/mm/yyyy, Time Format == hh:mm.ss ampm
    //              DateTime format == dd/mm/yyyy hh:mm.ss ampm
    /* Required Formats:
        Today = 8 Jan 2006
        1/1 10p = 1 Jan Year, 22:00
        20/1 == 20 Jan Year  (00:00)
        17/6/06 23:40:10 == 17 Jun 2006 23:40
        10 == 10 Jan 2006 (next future occurance of the 10th)
        7 == 7 Feb 2006 (next future occurance of the 7th)

        */

    var dt = ctrl.value.toLowerCase().trim();
    if (dt == '') return true;

    var hasDate = 0, hasTime = 0;
    var now=new Date();
    var day=now.getDate(),month=now.getMonth()+1,year=now.getYear();


    for(var i=0;i<5;i++) {
        dt=dt.replace(' AM', 'am');
        dt=dt.replace(' am', 'am');
        dt=dt.replace(' PM', 'pm');
        dt=dt.replace(' pm', 'pm');
        dt=dt.replace('.', ':');  // swap . with : for time
        dt=dt.replace('-', '/'); // swap - with / for dates
        dt=dt.replace('\\', '/');  // swap  with / for dates
        dt=dt.replace(',', ''); // remove commas for 'month, year'
    }
    
    if ((right(dt, 1) == 'p') || (right(dt, 1) == 'a')) {
        hasTime = 1;
    } else {
        if ((dt.indexOf(':') >= 0)) {
            hasTime = 1;
        }
    }

    if ((dt.indexOf('/') > 0)) {
        hasDate = 1;
    } else {
        var months = new Array('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
        for (i=0;i<months.length;i++) {
            if (dt.indexOf(months   [i]) >= 0) { hasDate = 1; }
        }
    }

    if ((hasDate == 0) && (hasTime == 0)) {
        if (isNaN(dt) == false) {
            // only day speified, if today = 12 and 10 specified, will default to 10th of next month
            //alert('Day only, using now for rest of date only');
            dt = dt * 1;
            if (dt < day) {
                month += 1;
                if (month == 13) {
                    year += 1;
                    month = 1;
                }
            }
            ctrl.value = dt.toString() + '/' + lpad(month.toString()) + '/' + year.toString();
            ctrl_dateformat(ctrl);
            return true;
        }
    }

    if ((hasDate == 1) && (hasTime == 1)) {
        // use date + time
        var dt_date, dt_time;
        if (dt.lastIndexOf(' ') == -1) {
            alert('Error, Invalid DateTime format (no space found)');
            return false;
        }
        dt_date = dt.substr(0, dt.lastIndexOf(' ')).toString().trim();
        dt_time = dt.substr(dt.lastIndexOf(' ')).toString().trim();

        ctrl.value = dt_date;
        ctrl_dateformat(ctrl);
        dt_date = ctrl.value
        
        ctrl.value = dt_time;
        ctrl_timeformat(ctrl);
        dt_time = ctrl.value;
        
        ctrl.value = dt_date + ' ' + dt_time;
        return true;
    }
    if ((hasDate == 1) && (hasTime == 0)) {
        // date only, no time
        ctrl_dateformat(ctrl);
        return true;
    }
    if ((hasDate == 0) && (hasTime == 1)) {
        // time only, use todays date
        ctrl_timeformat(ctrl);
        ctrl.value = day.toString() + '/' + lpad(month.toString(), '0', 2) + '/' + year + ' ' + ctrl.value;
        return true;
    }

    if ((hasDate == 0) && (hasTime == 0)) {
        // null value
        alert('Error, Invalid DateTime format (no valid date or time found)');
        ctrl.value = '';
        return false;
    }
}

function ctrl_dateformat(ctrl) {
    var now=new Date();
    var day=now.getDate(),month=now.getMonth(),year=now.getYear();

    if ((ctrl.value == '0') || (ctrl.value == '')) {
        ctrl.value = day.toString() + '/' + lpad(month.toString(), '0', 2) + '/' + year;
        return true;
    }
    var dt=ctrl.value.toString().toLowerCase();
    for (var i=0;i<5;i++) {
        dt=dt.replace("-", "/");
        dt=dt.replace(" ", "/");
        dt=dt.replace(".", "/");
        dt=dt.replace("\\", "/"); //"
    }

    /* accepted formats: (where today is 12 Jan 2006)
                         10 = 10 Feb 2006 (next occurance)
                         14 = 14 Jan 2006 (next occurance)
                         1/2 = 1 Feb 2006
                         1 Feb = 1 Feb 2006
                         1/2/5 = 1 Feb 2005
                         1/02/2005 = 1 Feb 2005
                         1/Feb/2005 = 1 feb 2005
    */
    dt=dt.split("/");
    switch (dt.length) {
        case 1: // just day - use the next occurance
            if ((dt[0]*1) < day) {
                month += 1;
                if (month == 13) {
                    year +=1;
                    month=1;
                }
            }
            day=dt[0]*1;
            break;

        case 2: // day/month
            day=dt[0]*1;
            month=getMonth(dt[1]);
            if (((month * 1) > 12) && ((day * 1) <= 12)) {
                // switch day + month
                var tmp=day;
                day=month;
                month=tmp;
            }
            break;

        case 3: // day/month/year
            if ((dt[0]*1) > 1900) {
                year=dt[0] * 1;
                month=getMonth(dt[1]);
                day=dt[2] * 1;
            } else {
                day=dt[0];
                month=getMonth(dt[1]);
                year=dt[2];
            }
            break;
        default:
            alert('Invalid Date Format');
            return false;
    }
    month=getMonth(month);
    if (isNaN(month)) {
        alert('Invalid Date (month)');
        return false;
    }

    if (day > days_in_month(month, year)) {
        day = days_in_month(month, year);
    }

    if (day < 1) {
        day = 1;
    }
    
    if (month < 1) {
        month = 1;
    }
    if (month > 12) {
        month = 12;
    }

    if (year < 90) {
        year = 2000+(year*1);
    }
    if ((year > 90) && (year < 100)) {
        year = 1900 + (year*1);
    }

    if ((year < 0) || (year < 1800) || (year > 2099)) {
        year = now.getYear();
    }

    if (year > 2020) year = 2020;
    if (year < 1980) year = 1980;

    ctrl.value = day.toString() + '/' + lpad(month.toString(), '0', 2) + '/' + year;
    return true;
}


function days_in_month(Month, Year) {
    var daysInMonthEnum = [31,28,31,30,31,30,31,31,30,31,30,31];

    if (Month > 12) { Month=12; }
    if (Month < 1)  { Month=1; }
    Month = Month -1; // Jan == 0, Dec == 11;

    var days=daysInMonthEnum[Month];
    if (Month == 1) {   // February, Jan == 0
        if (Year % 4 == 0) {    // Yead mod 4 = 0
            if (Year % 400 != 0) { // year mod 400 = 0
                // Leap year = every 4 years, but not every 400th year :P
                days += 1;
            }
        }
    }
    return days;
}


function getMonth(month) {
    if (isNaN(month * 1)) {
        switch (month.toString().toLowerCase()) {
            case 'jan': case 'j': case 'january': case 'janu': case 'janua': case 'janary': case 'januar': case 'ja': return 1; break;
            case 'feb': case 'f': case 'fe': case 'febr': case 'febru': case 'februa': case 'februar': case 'february': case 'febuary': return 2; break;
            case 'mar': case 'marc': case 'march':    return 3; break;
            case 'apr': case 'apri': case 'ap': case 'april':    return 4; break;
            case 'may':                  return 5; break;
            case 'jun': case 'june':     return 6; break;
            case 'jul': case 'july':     return 7; break;
            case 'aug': case 'au': case 'augu': case 'augus': case 'august':   return 8; break;
            case 'sep': case 's':  case 'se': case 'sept': case 'septe': case 'septem': case 'septemb': case 'septembe': case 'september': return 9; break;
            case 'oct': case 'oc': case 'octo': case 'octob': case 'octobe': case 'october':  return 10; break;
            case 'nov': case 'n': case 'no': case 'nove': case 'novem': case 'novemb': case 'novembe': case 'november': return 11; break;
            case 'dec': case 'd': case 'de': case 'dece': case 'decem': case 'decemb': case 'decembe': case 'december': return 12; break;
            default:
                return 0;
        }
    } else {
        if (((month * 1) < 13) && ((month * 1) > 0)) {
            return month * 1;
        } else {
            return 0;
        }
    }
}

function ctrl_timeformat(ctrl) {
    var ampm='', hour=0, min=0, sec=0;
    var am=new Array('a.m.', 'am', 'a.m', 'a');
    var pm=new Array('p.m.', 'pm', 'p.m', 'p');
    var i, x='';

    if (ctrl.value) {
        x = ctrl.value.toString().toLowerCase();
    }
    if (x=='') return true;

    /* determine am/pm */
    for (i=0;i<am.length;i++) {
        if (x.indexOf(am[i]) >= 0) {
            ampm='am';
            x=x.replace(am[i], '');
        }
    }
    for (i=0;i<pm.length;i++) {
        if (x.indexOf(pm[i]) >= 0) {
            ampm='pm';
            x=x.replace(pm[i], '');
        }
    }

    /* determine time format */
    x=x.replace('.', ':');
    var tm=x.split(':');
    switch (tm.length) {
        case 1: // hour
            hour=tm[0] * 1;
            break;

        case 2: // hour:minute
            hour=tm[0] * 1;
            min=tm[1] * 1;
            break;

        case 3: // hour:minute:second
            hour=tm[0] * 1;
            min=tm[1] * 1;
            sec=tm[2] * 1;
            break;

        default: // unknown
            alert('Invalid Time format');
            ctrl.focus();
            ctrl.select();
            break;
    }

    if (isNaN(hour) || isNaN(min) || isNaN(sec)) {
        alert('Invalid Time (time is not numeric)');
        ctrl.focus();
        ctrl.select();
        return false;
    }


    if ((hour > 23) || (hour < 0)) {
        alert('Invalid Time (hour):' + hour);
        ctrl.focus();
        ctrl.select();
        return false;
    }

    if (ampm == 'am') {
        if (hour == 12) {
            hour = 0;
        } else if (hour == 0) {
            alert('Invalid Time (hour)');
            ctrl.focus();
            ctrl.select();
            return false;
        } else if (hour > 12) {
            alert('Invalid Time (hour)');
            ctrl.focus();
            ctrl.select();
            return false;
        }
    } else if (ampm == 'pm') {
        if (hour == 0) {
            alert('Invalid Time (hour)');
            ctrl.focus();
            ctrl.select();
            return false;
        } else if (hour < 12) {
            hour = hour + 12;
        }
    }

    if ((min > 59) || (min < 0)) {
        alert('Invalid Time (minute)');
        ctrl.focus();
        ctrl.select();
        return false;
    }

    if ((sec > 59) || (sec < 0)) {
        alert('Invalid Time (second)');
        ctrl.focus();
        ctrl.select();
        return false;
    }

    ctrl.value = hour.toString() + ':' + lpad(min.toString(), '0', 2);
    return true;
}

function lpad(text, padwith, padlength) {
    TCGlobal_jsErrorLocation='tcweb.js>lpad()';

    var x=padlength-text.length;
    if (x < 0) return text;
    var y=text;
    for (i=0;i<x;i++){
        y=padwith + y;
        x=padlength-text.length;
    }
    return y;
}

