
function  FormatAndValidateDate(source,args) {
// This function re-formats and validates a date. It needs access to the
// html input tag. To get it, it reads the "controltovalidate" property
// from the asp.net custom validation span tag. 

    //Get a reference to the custom validator span tag
    var CustomValidationTag = document.getElementById(source.id);
    //Get the id of the control which is validated
    var ControlToValidateId = CustomValidationTag.controltovalidate;
    //Get a reference to the control to validate
    var ControlToValidate = document.getElementById(ControlToValidateId);
   
    //Reformat the date m/d/yyyy
    
    ReformatDate(ControlToValidate, "");
    
     if (!DateIsValid(ControlToValidate)) {
        args.IsValid = false;
     } else {
        args.IsValid = true;
     }
}

function ValidateMaxOf2Decimals (source, args) {

    if (CountDecimals(args.value) > 2) {
        args.IsValid = false;
    }
}

function CountDecimals(num) {
    var posOfDecimal  = args.value.indexOf(".") + 1    
    if (posOfDecimal > 1 && (args.value.length - posOfDecimal > 2)) {
        args.IsValid = false
    }

}


//Reformats the date into mm/dd/yyyy.  Valid formats are mmddyy or mm/dd/yy or
// mm/dd/yyyy.  This function was copied from ll2 . It only reformats the date.
// It does not validate it.
function ReformatDate(source, args)
{
	if(source == null || source.value == null)
		return;
	
	var value = source.value;
	
	var exp = null;
	var m = null;
	var month = null;
	var day = null;
	var year = null;
	
	exp = /^\d{6}(\d{2})?$/; // match either 6 or 8 digits
	m = value.match(exp)
	
	if(m != null)
	{
		month = value.substring(0,2);
		day = value.substring(2,4);
		year = value.slice(4);
		
	}
	else
	{
		// try to match 6 or 8 digits with either - or /
		// characters interspersed in date format.
		exp = /^(\d{1,2})([-/])(\d{1,2})\2(\d{2}(\d{2})?)$/;
		m = value.match(exp);
		if (m == null)
			return;
			
		month = m[1];
		day = m[3];
		year = m[4];
	}

	if(year.length == 2)
		year = ValidatorGetFullYear(year);
	else
		year = parseInt(year,10);
		
	if(year == null)
		return;

    if (month.length == 1) {
        month = "0" + month
    }
    
    if (day.length == 1) {
        day = "0" + day
    }

    source.value = month + "/" + day + "/" + year

// The code below does not work when dealing the date object because for some 
// reason, the date object will return valid dates even though the date may be invalid.
	
//	month = parseInt(month,10);
//	
//	day = parseInt(day,10);
//	

//	
//	// jscript month is one less than we expect
//	var date = new Date(year, month -1, day);	
//	
//	
//	//Make a 2 digit month
//	var displayMonth  = (date.getMonth() + 1).toString()
//	if (displayMonth.length == 1) {displayMonth = "0" + displayMonth }
//	
//	//Make a 2 digit day
//    var displayDay = date.getDate().toString()
//	if (displayDay.length == 1) {displayDay = "0" + displayDay }
//	
//	//Display mm/dd/yyyy
//	source.value =
//		displayMonth + "/" + 
//		displayDay + "/" + 
//		date.getFullYear().toString();
//		
		
		
//old code - display m/d/yyyy
//	source.value =
//		(date.getMonth() + 1).toString() + "/" + 
//		date.getDate().toString() + "/" + 
//		date.getFullYear().toString();
//		
}


function ValidatorGetFullYear(year)
{
	year = parseInt(year,10);
	if(isNaN(year))
		return null;
	if(year < 0 || year > 99 )
		return null;
		
	var currentYear = (new Date()).getFullYear();
	var cuttoffYear = currentYear - 50;
	var currentCentury = Math.floor(currentYear/100.0) * 100;
	var cuttoff2DigitYear = cuttoffYear - (Math.floor(cuttoffYear/100.0) * 100);
	
	if(year <= cuttoff2DigitYear)
		return currentCentury + year;
	else
		return currentCentury - 100 + year;
}

    
function DateIsValid(myItem){
    var myArrayDate, myDay, myMonth, myYear, myString, myYearDigit;
    myString = myItem.value + "";
    if (myString == "" || myString == "mm/dd/yyyy"){
            //myItem.value = "mm/dd/yyyy";
            return true;
    }
    myArrayDate = myString.split("/");
    
    myDay = Math.round(parseFloat(myArrayDate[1]));
    myMonth = Math.round(parseFloat(myArrayDate[0]));
    myYear = Math.round(parseFloat(myArrayDate[2]));
    myString = myYear + "";
    myYearDigit = myString.length;
    
    if (isNaN(myDay) || isNaN(myMonth) || isNaN(myYear) || (myYear < 1) || (myDay < 1) || (myMonth < 1) || (myMonth > 12) || (myYearDigit != 4) || (myDay > days_in(myMonth, myYear))){
        //alert("Please check your Date format. (mm/dd/yyyy)");
        return false
    } else{
        return true;
    }
};


function isLeap(year){
    if(year % 400 == 0){
        return true;
    } else if((year % 4 == 0) && (year % 100 != 0)){
        return true
    } else return false;
};
    
function days_in(month, year){
    if(month == 4 || month == 6 || month == 9 || month == 11){
        return 30;
    } else if(!isLeap(year) && month == 2){
        return 28;
    } else if(isLeap(year) && month == 2){
        return 29;
    } else return 31;
};



//Only let the user hit specific keys
function ValidateKeyDown(event, type) {

	//Cross browser
	var target = (event.target) ? event.target : event.srcElement;
	//Defeat Safari bug
	if (target.nodeType == 3) target = target.parentNode;

    //If the control or alt key was pressed, then do not validate the keypress.
    if (event.ctrlKey || event.altKey ) {
        return
    }

    // Store the keyboard code that was pressed. (not the ascii code of the character)
    
    var evt = window.event || event;
	var code;

	//Firefox returns 0 for all keycodes so we have to use charCode.
	//All other browsers support keyCode. (charCode has inconsistent support at this time.)
	if (evt.keyCode == 0) {
		code = evt.charCode;
	}
	else {
		code = evt.keyCode;
	}

    // Boolean value whether the shift key was pressed
    var shft = evt.shiftKey

    // Only validate a displayable character.
    
    if (IsDisplayableKey(code)) {

        // Do not let any shift key combination display on the screen.
        if (shft) {
			if (evt) {event.returnValue = false;} // IE only
			else {evt.preventDefault();}
			return false;
        } else {
        
            switch (type) {
                case "9":
                    //Only let 0-9 be pressed.
                    if ((code < 48 || code > 57) && (code < 96 || code > 105))   {
						if (window.event) {event.returnValue = false;} // IE only
						else {evt.preventDefault();} //w3c
						return false;
                    }
                    break;
                case "9.":   // Any decimal number with no limit on the number of digits to the right of the decimal point.
                    if (code == 190 || code == 110) {
                        //check to make sure only 1 period has been pressed
                        if (target.value.indexOf(".") > -1) {
							if (window.event) {event.returnValue = false;} // IE only
							else {evt.preventDefault();} //w3c
							return false;
                        }
                    } else {
                        //Only let 0-9 be pressed OR the period
                        if ((code < 48 || code > 57) && (code < 96 || code > 105) && (code != 190)) {
							if (window.event) {event.returnValue = false;} // IE only
							else {evt.preventDefault();} //w3c
							return false;
                        }
                    }
                    break;
                case "9.99":
                    if (code == 190 || code == 110) {
                        //check to make sure only 1 period has been pressed
                        if (target.value.indexOf(".") > -1) {
							if (window.event) {event.returnValue = false;} // IE only
							else {evt.preventDefault();}
							return false;
                        }
                    } else {
                        //Only let 0-9 be pressed OR the period
                        if ((code < 48 || code > 57) && (code < 96 || code > 105) && (code != 190)) {
							if (window.event) {event.returnValue = false;} // IE only
							else {evt.preventDefault();} //w3c
							return false;
                        }
                    }
                    break;                
                default:
                    alert ("Type parameter not passed in ValidateKeyDown event: " + type )
					if (window.event) {event.returnValue = false;} // IE
					else {evt.preventDefault();} //w3c
					return false;
                    break;
            }
         }

    }

	if (window.event) {event.returnValue = true;} // IE only
	return true;
    
}

// Return if the keyboard code is displayable. 
function IsDisplayableKey(code) {
    var returnValue 

    returnValue = false

    // all keyboard codes above 48 are displayable on the screen. This information is taken from
    // Page 1281 of the book "Dynamic HTML The Definitive Reference" by Danny Goodman.
    // Space (code 32) is a displayable key.
    if (code == 32 || code >= 48) {
        returnValue = true
    }
    return returnValue
}


//Formats a number into currency.
// removeCents=true if you do not want to display a decimal place
function formatCurrency(num, removeCents) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)  cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    
    if (removeCents == true) {
        return (((sign)?'':'-') + '$' + num);
    } else {
        return (((sign)?'':'-') + '$' + num + '.' + cents);
    }
    
}

//Validates a time string using asp.net custom validation
function ValidateTime(source, args) {
	args.IsValid = isValidTimeString(args.Value);
}

//Validate a time in  HH:MM PM format
//this function is copied from V3 and slightly changed.
function isValidTimeString(timeStr)
{
	if (timeStr != "") // Check the start time field
	{
		var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
		var matchArray = timeStr.match(timePat);
		if (matchArray == null)
		{
//			alert("Time is not in a valid format. \n Format = HH:MM AM/PM");
//			theField.focus();
			return false;
		}
		hour = matchArray[1];
		minute = matchArray[2];
		second = matchArray[4];
		ampm = matchArray[6];
		if (second=="")
		{
			second = null;
		}
		if (ampm=="")
		{
			ampm = null
		}
		if (hour < 1  || hour > 12)
		{
//			alert("Hour must be between 1 and 12.");
//			theField.focus();	
			return false;
		}
		if (hour <= 12 && ampm == null)
		{
//			alert("You must specify AM or PM.");
//			theField.focus();
			return false;
		}
		if (minute<0 || minute > 59)
		{
//			alert ("Minute must be between 0 and 59.");
//			theField.focus();
			return false;
		}
		if (second != null && (second < 0 || second > 59))
		{
//			alert ("Second must be between 0 and 59.");
//			theField.focus();
			return false;
		}
		return true;
	}
}
