//Original:  Mike Welagen (welagenm@hotmail.com)
//The JavaScript Source!! http://javascript.internet.com
DateInput = {
		
    /// <summary>
    /// Initialize this object with format parameters specific to the current locale.
    /// </summary>
    initialize: function(locale, invalidDateError, invalidRangeError)
    {
        this.locale = locale.toLowerCase();
        this.invalidDateError = invalidDateError;
        this.invalidRangeError = invalidRangeError;        
        this.err = 0;
    },
    
    /// <summary>
    /// Insure that the date entered in the date input is valid. Format the date if it's valid.
    /// </summary>
    checkdate: function(dateInput) 
    {
		try
		{   			
			if (!this.chkdate(dateInput))
			{
				dateInput.select();
	                
				//Boris 2/21/07:  If the user enters a year that is less then 1753 or greater than 3000, provide 
				//them with a customized error message.

		                //TRB 10/22/08: if error in date, clear it out.	--> hmmm.. changed mind.. don't clear.. leave. but 
				// allow error to be ok too, so that we can render message in browser during internal validation, 
				// that the date entered is no good. 			
				//if (this.err == 15)				
				    //dateInput.value = "";
				    //alert(this.invalidRangeError);
				//else
				    //dateInput.value = "";
				    //alert(this.invalidDateError);
	            
				this.err = 0;
	            		
				//TRB 10/22/08; fixed the focus problem with a timeout. BUT, now all ERRORS are OK, so don't go back. 
				// Also set RETURN condition to TRUE case. (originally false).
				//setTimeout(function(){dateInput.focus()}, 10);

				return true;
			}
			else
				return true;
	    }
	    catch (ex)
	    {
            alert("Error occurred: [DateInput.checkdate]\n\n" + ex.message);
	        return '';
	    }
    },

    /// <summary>
    /// Get the date style of the current locale.
    /// </summary>
    /// <returns>
    /// US for MM/DD/YYYY and EU for DD/MM/YYYY.
    /// </returns>
    getDateStyle: function()
    {
        if (this.locale == 'en-us' || this.locale == 'en-ca') 
            return 'US'; 
        else
            return 'EU'; 
    },
    
    /// <summary>
    /// Do the work of validating the date entered and format if valid.
    /// </summary>
    /// <param name="objName">
    /// The date input element to validate.
    /// </param>
    /// <returns>
    /// True if valid. False if invalid.
    /// </returns>
    chkdate: function(objName) 
    {
        var strDatestyle = this.getDateStyle();
        var strDate;
        var strDateArray;
        var strDay;
        var strMonth;
        var strYear;
        var intDay;
        var intMonth;
        var intYear;
        var booFound = false;
        var datefield = objName;
        var strSeparatorArray = new Array(" "); //Boris 2/14/07:  Since all date delimiter characters are replaced with a space down below, it only makes sense to use a space as a separator for the date string.
        //var strSeparatorArray = new Array("-", " ", "/", ".", ",");
        var intElementNr;
        var strMonthSplitArray;
        var strMonthArray = new Array(12);
        var booIsMothValid = false;

        this.err = 0;
                
        //Boris 2/14/07:  Include both the long and short month description in the array.
        //TRB 10/22/08:   Internationalied. Make sure to SRC proper include.
        // initialization
        if (strMonthArray[0] == undefined) {
		    for (var i = 0; i < 12; i++) {		       
			   strMonthArray[i] = DateInput._MN[i];
			}         		
	    }
        
        //Trim beginning and trailing spaces from date value.
        strDate = datefield.value.replace(/^\s+|\s+$/g,"");
        
        strDate = strDate.replace(/[\-,./]/g, " "); //Boris 2/14/07:  This will replace any of the following characters with a space:  "-", ",", ".", "/".
        strDate = strDate.replace(/\s+/g, " "); //Boris 2/14/07:  This will replace any instances of multiple whitespace characters with just one whitespace character.

        //If nothing is entered then the field should be considered valid.
        if (strDate.length < 1) {
            return true;
        }
        
        for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
            if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
                strDateArray = strDate.split(strSeparatorArray[intElementNr]);
            
                if (strDateArray.length != 2 && strDateArray.length != 3) {
                    this.err = 1;
                    return false;
                }
                else 
                {
                    strDay = strDateArray[0];
                    strMonth = strDateArray[1];
                    strYear = strDateArray[2] == null || strDateArray[2] == "" ? (new Date()).getFullYear().toString() : strDateArray[2];  //Boris 2/14/07:  If the year value was not supplied, set the year to the current year.
                }
                
                booFound = true;
            }
        }
        
        if (booFound == false) {
        
            //Boris 12/15/07:  At this point the function assumes that a date was entered without
            //any separators.  Thus we should check for the strDate variable to make sure its numeric.
            if (isNaN(strDate)) {
                return false;
            }
        
            if (strDate.length > 5) {
                strDay = strDate.substr(0, 2);
                strMonth = strDate.substr(2, 2);
                strYear = strDate.substr(4);
            }
        }
            
        //Boris 12/16/07:  Make sure to invalidate the date if its not numeric or if contains an 'e' character in it.
        //Note:  If you don't explicitly check for 'e', the isNaN function will treat it as valid numeric value.
        //For example, '20e01' would be treated as valid number, while '20w01' would not be a valid number.
        if (isNaN(strYear) || strYear.indexOf("e") > -1) {
            this.err = 12;
            return false;
        }    
        
    //    //Boris 2/14/07:  Make sure that no one enters a year that is one or three characters long.
    //    if (strYear.length == 3 || strYear.length == 1) {
    //        this.err = 11;
    //        return false;
    //    }
       
        //Boris 2/16/07:  If the year value is only 2 digits prepend the first 2 digits 
        //of the year based on weather the 2 numbers provide are greater or less then 30.
        if (strYear.length == 2) {
            if (parseInt(strYear) <= 30) {
                strYear = '20' + strYear;
            }
            else {
                strYear = '19' + strYear;     
            }
        }
        
        //Boris 2/21/07:  Do not allow year values that are less then 1753 or greater then 3000. Don't immediately return false so that the date
        //will be formatted, even if out of bounds.
        if (strYear.length != 0 && (parseInt(strYear) < 1753 || parseInt(strYear) > 3000)) {
            this.err = 15;
        }
        
        // US style
        if (strDatestyle == "US") {
            strTemp = strDay;
            strDay = strMonth;
            strMonth = strTemp;
        }
        
        //Boris 2/14/07:  This conditional statement checks to see if the month was entered as a string
        //rather then a number while at the same time the day was entered as a numeric value.  If the condition
        //is met, the date will be formatted correctly no matter what order the day and month are typed in.  
        //This applies to both the US and EU date formats.  Note:  This piece of code is sensitive to it's
        //location within this file.  So, you need to be careful when editing.  Make sure to place 
        //this code after the adjustment for US style dates is performed.
        if ((isNaN(strDay) || (isNaN(strDay) == false && strDay.indexOf("e") > -1)) && (isNaN(strMonth) == false && strMonth.indexOf("e") == -1))
        {
            if (strDay.match(/[\-,./]/g) == null) {
                strTemp = strMonth;
                strMonth = strDay;
                strDay = strTemp;
            }
            else {
                this.err = 14;
                return false;
            }
        }
        
        intDay = parseInt(strDay, 10);
        
        if (isNaN(intDay)) {
            this.err = 2;
            return false;
        }
        
        intMonth = parseInt(strMonth, 10);
        
        if (isNaN(intMonth)) {
            strMonth = strMonth.toLowerCase();
            intMonth = 0;        
            for (i = 0; i < 12; i++) {                
                strMonthSplitArray = strMonthArray[i].split(","); //Boris 2/14/07:  Seperate the month strings within the array element for comparison purposes.  For example, separate "February,Feb" into "February" and "Feb".
                for (j = 0; j < strMonthSplitArray.length; j++)
                {
                    if (strMonth == strMonthSplitArray[j])
                    {
                        intMonth = i + 1;
                        break;
                    }
                }
                if (intMonth != 0) break;
            }
           
            if (intMonth == 0) 
            {
                this.err = 3;
                return false;
            }
        }

        intYear = parseInt(strYear, 10);
        
        if (isNaN(intYear)) 
        {
            this.err = 4;
            return false;
        }
        
        if (intMonth>12 || intMonth<1) 
        {
            this.err = 5;
            return false;
        }
        
        if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) 
        {
            this.err = 6;
            return false;
        }
        
        if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) 
        {
            this.err = 7;
            return false;
        }
        
        if (intMonth == 2) 
        {
            if (intDay < 1) 
            {
                this.err = 8;
                return false;
            }
            
            if (this.leapYear(intYear) == true) 
            {
                if (intDay > 29) 
                {
                    this.err = 9;
                    return false;
                }
            }
            else 
            {
                if (intDay > 28) 
                {
                    this.err = 10;
                    return false;
                }
            }
        }
        
        if (strDatestyle == "US") 
        {
            //datefield.value = strMonthArray[intMonth - 1] + " " + intDay + " " + strYear;
            //datefield.value = intMonth + "/" + intDay + "/" + intYear; //Boris 2/14/07:  The final date string should be formatted with "/" characters.
            // trb make sure to use 2 digit month and days when needed. IGAM uses that standard.
            datefield.value = (intMonth < 10 ? "0" + intMonth : intMonth) + "/" + (intDay < 10 ? "0" + intDay : intDay) + "/" + intYear; //Boris 2/14/07:  The final date string should be formatted with "/" characters.
        }
        else 
        {
            //datefield.value = intDay + " " + strMonthArray[intMonth - 1] + " " + strYear;
            //datefield.value = intDay + "/" + intMonth + "/" + intYear; //Boris 2/14/07:  The final date string should be formatted with "/" characters.
            // trb make sure to use 2 digit month and days when needed. IGAM uses that standard.
            datefield.value = (intDay < 10 ? "0" + intDay : intDay) + "/" + (intMonth < 10 ? "0" + intMonth : intMonth) + "/" + intYear; //Boris 2/14/07:  The final date string should be formatted with "/" characters.
        }

        if (this.err == 15) 
            return false;
        else        
            return true;
    },

    /// <summary>
    /// Determine if the indicated year is a leap year.
    /// </summary>
    /// <param name="intYear">
    /// The year to check. 
    /// </param>
    /// <returns>
    /// True if the year is a leap year.
    /// </returns>
    leapYear: function(intYear) 
    {
        if (intYear % 100 == 0) 
            if (intYear % 400 == 0) return true;
        else 
            if ((intYear % 4) == 0) return true;
        
        return false;
    },

    /// <summary>
    /// Set the enabled property of the DateBox (both the textbox and the visibility of the calendar image).
    /// </summary>
    /// <param name="dateBoxId">
    /// The id of the datebox to enable or disable.
    /// </param>
    dateBoxSetEnabled: function(dateBoxId, enabled)
    {
        try
        {
            var calendarImage = document.getElementById(dateBoxId + "_calendar");
            var dateBox = document.getElementById(dateBoxId);
            if (enabled)
                calendarImage.style.visibility = "visible";
            else
                calendarImage.style.visibility = "hidden";
                
            dateBox.disabled = !enabled; 
	    }
	    catch (ex)
	    {
            alert("Error occurred: [DateInput.dateBoxSetEnabled]\n\n" + ex.message);
	        return '';
	    }
    },

    /// <summary>
    /// Get the date value of the element with the indicated id.    
    /// </summary>
    /// <param name="id">
    /// The id of the element whose value to return. 
    /// </param>
    /// <returns>
    /// The date value of the element.
    /// </returns>
	getValue: function(id) 
	{
	    try
	    {
		    var value = document.getElementById(id);
		    if (value && value.value != '')
		    {
				//Validate entry and return a formatted date if valid. Format the date, even if out of bounds (this.err = 15).
				if (this.chkdate(value) || this.err == 15)
				{
					//Return the value as a string formatted Y-M-D since this is what MySql takes.
					value = value.value.split('/');
	    			
					var dateStyle = this.getDateStyle();
					if (dateStyle == 'US')
						return value[2] + '-' + value[0] + '-' + value[1];
					else
						return value[2] + '-' + value[1] + '-' + value[0];
				}
				else
					return value.value;
		    }
		    return '';
	    }
	    catch (ex)
	    {
            alert("Error occurred: [DateInput.getValue]\n\n" + ex.message);
	        return '';
	    }
	},

    /// <summary>
    /// Clear the DateBox (at this point, just clear the textbox)
    /// </summary>
    /// <param name="dateBoxId">
    /// The client Id of the DateBox to enable or disable. 
    /// </param>
    dateBoxClear: function (dateBoxId)
    {    
        var dateBox = document.getElementById(dateBoxId);
        
        dateBox.value = "";
    }
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 