// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. Instead,
// please just point to my URL to ensure the most up-to-date versions
// of the files. Thanks.
// ===================================================================


// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDateValid ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDateValid(val,format) {
    var date=getDateFromFormat(val,format);
    if (date==0) { return false; }
    return true;
}


function checkValidDate(val, format) {
    if (isDateValid(val, format))
        return true;
    alert("checkValidDate: This is an invalid date format, please re-enter");
    return false;
}


// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
    var d1=getDateFromFormat(date1,dateformat1);
    var d2=getDateFromFormat(date2,dateformat2);
    if (d1==0 || d2==0) {
        return -1;
    }
    else if (d1 > d2) {
        return 1;
    }
    return 0;
}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
    format=format+"";
    var result="";
    var i_format=0;
    var c="";
    var token="";
    var y=date.getYear()+"";
    var M=date.getMonth()+1;
    var d=date.getDate();
    var H=date.getHours();
    var m=date.getMinutes();
    var s=date.getSeconds();
    var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;

    // Convert real date parts into formatted versions
    var value=new Object();
    if (y.length < 4) {y=""+(y-0+1900);}
    value["y"]=""+y;
    value["yyyy"]=y;
    value["yy"]=y.substring(2,4);
    value["M"]=M;
    value["MM"]=LZ(M);
    value["MMM"]=MONTH_NAMES[M-1];
    value["d"]=d;
    value["dd"]=LZ(d);
    value["H"]=H;
    value["HH"]=LZ(H);
    if (H==0){value["h"]=12;}
    else if (H>12){value["h"]=H-12;}
    else {value["h"]=H;}
    value["hh"]=LZ(value["h"]);
    if (H>11){value["K"]=H-12;} else {value["K"]=H;}
    value["k"]=H+1;
    value["KK"]=LZ(value["K"]);
    value["kk"]=LZ(value["k"]);
    if (H > 11) { value["a"]="PM"; }
    else { value["a"]="AM"; }
    value["m"]=m;
    value["mm"]=LZ(m);
    value["s"]=s;
    value["ss"]=LZ(s);
    while (i_format < format.length) {
        c=format.charAt(i_format);
        token="";
        while ((format.charAt(i_format)==c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        if (value[token] != null) { result=result + value[token]; }
        else { result=result + token; }
    }
    return result;
}

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
    var digits="1234567890";
    for (var i=0; i < val.length; i++) {
        if (digits.indexOf(val.charAt(i))==-1) { return false; }
    }
    return true;
}
function _getInt(str,i,minlength,maxlength) {
    for (var x=maxlength; x>=minlength; x--) {
        var token=str.substring(i,i+x);
        if (token.length < minlength) { return null; }
        if (_isInteger(token)) { return token; }
    }
    return null;
}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
    if (val == null || val == "")
        return 0;
    if (format == null || format == "")
        return 0;
    var realDate = getRealDateFromFormat(val,format);
    if (realDate == null)
        return 0;
    if (realDate == "")
          return 0;
    if (realDate == 0)
        return;
    return realDate.getTime();
}

// remove nulls
function getRealDateFromFormat(val, format) {
    val=val+""; 
    format=format+"";

    // set indices
    var i_val=0;
    var i_format=0;

    // set parsing variables
    var c="";
    var token="";
    var token2="";

    // variable sizes
    var x,y;

    // current date / time
    var now=new Date();
    var year=now.getYear();
    var month=now.getMonth()+1;
    var date=now.getDate();
    var dateAssigned = 0;
    var hh=now.getHours();
    var mm=now.getMinutes();
    var ss=now.getSeconds();

    // work field for am or pm
    var ampm="";

    // the text has to character for character match format string
    while (i_format < format.length) {

        // Get next token from format string
        c=format.charAt(i_format);
        token="";
        while ((format.charAt(i_format)==c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }

        // Extract contents of value based on format token
        if (token=="yyyy" || token=="yy" || token=="y") {
            if (token=="yyyy") { x=4;y=4; }
            if (token=="yy")   { x=2;y=2; }
            if (token=="y")    { x=2;y=4; }
            year=_getInt(val,i_val,x,y);
            if (year==null) { return 0; }
            i_val += year.length;
            if (year.length==2) {
                if (year > 70) { year=1900+(year-0); }
                else { year=2000+(year-0); }
            }
        }
        else if (token=="MMM"){
            month=0;
            for (var i=0; i<MONTH_NAMES.length; i++) {
                var month_name=MONTH_NAMES[i];
                if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
                    month=i+1;
                    if (month>12) { month -= 12; }
                    i_val += month_name.length;
                    break;
                }
            }
            if ((month < 1)||(month>12)){return 0;}
        }
        else if (token=="MM"||token=="M") {
            month=_getInt(val,i_val,token.length,2);
            if(month==null||(month<1)||(month>12)){return 0;}
            i_val+=month.length;}
        else if (token=="dd"||token=="d") {
            date=_getInt(val,i_val,token.length,2);
            dateAssigned = 1;
            if(date==null||(date<1)||(date>31)){return 0;}
            i_val+=date.length;}
        else if (token=="hh"||token=="h") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<1)||(hh>12)){return 0;}
            i_val+=hh.length;}
        else if (token=="HH"||token=="H") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<0)||(hh>23)){return 0;}
            i_val+=hh.length;}
        else if (token=="KK"||token=="K") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<0)||(hh>11)){return 0;}
            i_val+=hh.length;}
        else if (token=="kk"||token=="k") {
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<1)||(hh>24)){return 0;}
            i_val+=hh.length;hh--;}
        else if (token=="mm"||token=="m") {
            mm=_getInt(val,i_val,token.length,2);
            if(mm==null||(mm<0)||(mm>59)){return 0;}
            i_val+=mm.length;}
        else if (token=="ss"||token=="s") {
            ss=_getInt(val,i_val,token.length,2);
            if(ss==null||(ss<0)||(ss>59)){return 0;}
            i_val+=ss.length;}
        else if (token=="a") {
            if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
            else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
            else {return 0;}
            i_val+=2;}
        else {
            if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
            else {i_val+=token.length;}
        }
    }

    // If there are any trailing characters left in the value, it doesn't match
    if (i_val != val.length) {
        alert("i_val " + i_val + " length " + val.length);
        return 0;
    }

    // Is date valid for month?
    if (month==2) {
        // Check for leap year
        if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) {
            if (date > 29) {
                if (dateAssigned) return false;
                date = 29;
            }
        }
        else if (date > 28) {
            if (dateAssigned)  return false;
            date = 28;
        }
    }
    // 30 days hath sep, apr, jun & nov
    if ((month==4)||(month==6)||(month==9)||(month==11)) {
        if (date > 30) {
            if (dateAssigned) return false;
            date = 30;
        }
    }

    // Correct hours value
    if (hh<12 && ampm=="PM") 
        hh+=12; 
    else if (hh>11 && ampm=="AM")
        hh-=12;

    // convert first to date, then to time integer
    var result = new Date(year,month-1,date,hh,mm,ss);
    return result;
}



// ------------------------------------------------------------------
// getFormatFromTradex( tradex_string , format_string )
//
// This function takes a tradex string and a format string. It converts
// the tradex date into a formated date based on the format string.
// ------------------------------------------------------------------
function getFormatFromTradex( trdxDate , format ) {
    if (trdxDate == null)
        return "";
    if (trdxDate == "")
        return "";

    dateWrk = getDateFromTradex( trdxDate );
    if (dateWrk == "")
        return "";

    return formatDate( dateWrk , format );
}
        



// ------------------------------------------------------------------
// getDateFromTradex( tradex_string )
//
// This function takes a tradex string. It converts the tradex
// date into an internal javascript date.
// ------------------------------------------------------------------
function getDateFromTradex( trdxDate ) {
    if (trdxDate == null)
        return "";
    if (trdxDate == "")
        return "";
    if (trdxDate.length < 2)
        return "";
    if (trdxDate.length == 2)
        trdxDate += "0101";
    if (trdxDate.length < 4)
        return "";
    if (trdxDate.length == 4)
        trdxDate += "01";
    if (trdxDate.length < 6)
        return "";

    y1 = getFourDigitYear(trdxDate.substring(0,2));
    if (y1 == "")
        return "";

    m1 = trdxDate.substring(2,4);
    if (m1.substring(0,1) == "0")
        m1 = m1.substring(1,2);
    m1 = m1 - 1;
    d1 = trdxDate.substring(4,6);
    if (d1.substring(0,1) == "0")
        d1 = d1.substring(1,2);

    return new Date(y1, m1, d1);
}


// ------------------------------------------------------------------
// getTradexFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It converts
// the date into a string compatible with the internal tradex format
// ------------------------------------------------------------------
function getTradexFromFormat(formatDate, format) {
    if (formatDate == null)
        return "";
    if (formatDate == "")
        return "";
    if (format == null)
        return "";
    if (format == "")
        return "";
    
    var date = getRealDateFromFormat(formatDate , format);

    return getTradexFromDate( date , format);
}

    


// ------------------------------------------------------------------
// getTradexFromDate( date )
//
// This function takes a date and a format. It converts the date
// into a string compatible with the internal tradex format.  The
// format is used to determine if we need the month and year
// ------------------------------------------------------------------
function getTradexFromDate( date , format ) {
    if (date == null)
        return "";
    if (date == "")
        return "";

    // get the components
    y1 = date.getYear();
    if (y1 < 2000) 
        y1 = 1900 + y1;
    m1 = date.getMonth() + 1;
    if (m1 < 10)
        m1 = "0" + m1;
    d1 = date.getDate();
    if (d1 < 10)
        d1 = "0" + d1;

    // piece together
    var result = getTradexYear(y1);
    if (format.indexOf("M") != -1)
        result += m1;
    if (format.indexOf("d") != -1)
        result += d1;

    return result;
}




// ------------------------------------------------------------------
// getTradexYear( year_string )
//
// This function takes a four digit year string converts it to
// a two character tradex year
// ------------------------------------------------------------------
function getTradexYear(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 "";
}


// ------------------------------------------------------------------
// getFourDigitYear( tradex_year )
//
// This function takes a tradex year string converts it to
// a four digit year string
// ------------------------------------------------------------------
function getFourDigitYear(trdxYear) {

    // need a year
    if (trdxYear == null)
        return "";
    if (trdxYear.length < 2)
        return "";

    // we need a switch on the first character of the year
    var firstChar = trdxYear.substring(0,1);
    if (firstChar < 'A')
        return ("19" + trdxYear);
    var secondChar = trdxYear.substring(1,2);

    if (firstChar == "A")
        return "200" + secondChar;
    if (firstChar == "B")
        return "201" + secondChar;
    if (firstChar == "C")
        return "202" + secondChar;
    if (firstChar == "D")
        return "203" + secondChar;
    if (firstChar == "E")
        return "204" + secondChar;
    if (firstChar == "F")
        return "205" + secondChar;
    if (firstChar == "G")
        return "206" + secondChar;
    if (firstChar == "H")
        return "207" + secondChar;
    if (firstChar == "I")
        return "208" + secondChar;
    if (firstChar == "J")
        return "209" + secondChar;
    if (firstChar == "K")
        return "210" + secondChar;
    if (firstChar == "L")
        return "211" + secondChar;
    if (firstChar == "M")
        return "212" + secondChar;
    if (firstChar == "N")
        return "213" + secondChar;
    if (firstChar == "O")
        return "214" + secondChar;
    if (firstChar == "P")
        return "215" + secondChar;
    if (firstChar == "Q")
        return "216" + secondChar;
    if (firstChar == "R")
        return "217" + secondChar;
    if (firstChar == "S")
        return "218" + secondChar;
    if (firstChar == "T")
        return "219" + secondChar;
    if (firstChar == "U")
        return "220" + secondChar;
    if (firstChar == "V")
        return "221" + secondChar;
    if (firstChar == "W")
        return "222" + secondChar;
    if (firstChar == "X")
        return "223" + secondChar;
    if (firstChar == "Y")
        return "224" + secondChar;
    if (firstChar == "Z")
        return "225" + secondChar;
    return "";
}


