//
// Various data verification routines
//
//		dates: makeValidDate
//
//		integers: makeValidInteger
//

var isNav = document.layers;
var isIe = document.all;

//This function will check to make sure that a date is valid
//by running the makeValidDate function, and if the date is not 
//valid it will call the createCalendar function to launch the 
//calendar widget.
function checkDate(field)
{
	var fieldValue = field.value;
	var fieldName = field.name;
	var goodDate = null;
	goodDate = makeValidDate(fieldValue, false);
	//report parameters for certain data extracts allow empty dates; sprpt_modified is the prefix for the affected fields
	if (fieldValue == "" && fieldName.indexOf("sprpt_modified") != -1)
	{
		return;
	}
	else if (goodDate == null || goodDate == "")
	{
	    alert("You have entered an incorrect date.  The correct date format is 'dd-Mon-yyyy'.\nPlease enter a correctly formatted date or use the calendar icon.");
      field.value = "";
      //field.focus();
	    return false;
	}
	else 
    {
	    field.value = goodDate;
	    return true;
    }
}


//This function is being used getting a string in the format of '13-Jan-2000' and 
//converting that into a string in the format of '20000113'
//This will then be used to determine if the dates are in the proper order.
//This function will be used specifically in cases when there are times involved 
//(although this functiond doesn't deal with time.)
 
function formatMyDate(date)
{
    var dateStrLength = date.length;
	var year = date.substr(dateStrLength-4);
	var monthString = date.substr(dateStrLength - 8,3).toLowerCase();
	var day = date.substring(0,dateStrLength - 9);
    if (day.length == 1)
        day = "0" + day;
	var month = 0;
	var returnDate = 0;
    monthString = monthString.toLowerCase();
	if (monthString == "jan")
		month =  "01";
	if (monthString == "feb")
		month =  "02";
	if (monthString == "mar")
		month =  "03";
	if (monthString == "apr")
		month =  "04";
	if (monthString == "may")
		month =  "05";
	if (monthString == "jun")
		month =  "06";
	if (monthString == "jul")
		month =  "07";
	if (monthString == "aug")
		month =  "08";
	if (monthString == "sep")
		month =  "09";
	if (monthString == "oct")
		month =  "10";
	if (monthString == "nov")
		month =  "11";
	if (monthString == "dec")
		month =  "12";
		
	returnDate = year + month + day;
	//alert(returnDate);
	return returnDate;
}

function convertMonthNumToMonthString(num)
{
	if(num == null)
	{
		return "ERROR";
	}
	
	var monthString = "";
	
		if(num == 0)
			monthString = "Jan";
		if(num == 1)
			monthString = "Feb";
		if(num == 2)
			monthString = "Mar";
		if(num == 3)
			monthString = "Apr";
		if(num == 4)
			monthString = "May";
		if(num == 5)
			monthString = "Jun";
		if(num == 6)
			monthString = "Jul";
		if(num == 7)
			monthString = "Aug";
		if(num == 8)
			monthString = "Sep";
		if(num == 9)
			monthString = "Oct";
		if(num == 10)
			monthString = "Nov";
		if(num == 11)
			monthString = "Dec";
	return monthString;
}

// This function is used to convert the time into a properly readable format to determin that
// the times are in order (later on).  This function takes one parameter (time) and should be in
// in the format of "10:30 AM".  This can also take times in the format of "14:20", but must atleast
// be in the format of HH:MM.
function formatThisTime(t)
{
	//alert("test: " + t.length);
	var myTime = "";
	if(t.length > 5)
	{
		var myHour = t.substring(0,2);
		var myMinutes = t.substring(3,5);
		var amOrPm = t.substring(6,8);
		var myNewHour = myHour;
		if(amOrPm != null)
		{
			// Check for AM or PM to convert to army time.
			if(((amOrPm == "pm") || (amOrPm == "PM")) && myNewHour < 13)
			{
				myNewHour = myNewHour + 12;
			}
		}
	} 
	else if(t.length > 4)
	{
		var myHour = t.substring(0,2);
		var myMinutes = t.substring(3,5);
	} 
	else
	{
		var myHour = t.substring(0,1);
		var myMinutes = t.substring(2,4);
	}
			
	myTime = myHour + myMinutes;
	
	return myTime;
}

// This function uses our previous function (formatMyDate) to put the dates in a certain format
// and then checks to make sure that the dates are in the correct order (start date
// preceeding the end date).  This function takes two parameters, (the start date, and
// the end date) and returns either an empty string, or an error msg depending on how
// the function works out.
function checkDatesInOrder(startDate, endDate)
{
	var errMsg = "";
	//alert(startDate + ", " + endDate);
	if((startDate == null) || (startDate ==0) || (endDate == null) || (endDate == 0))
	{
		//alert("I couldn't proccess the dates because one of them was null: startDate= " + startDate + " endDate= " + endDate);
		errMsg += "Error processing dates, they may not be in the proper format.";
		return errMsg;
	}
	else if(formatMyDate(startDate) > formatMyDate(endDate))
	{
		//alert("endDate came before the startDate: startDate= " + startDate + " endDate= " + endDate);
		errMsg += "ERROR: The end date must be greater than or equal to start date.";
		return errMsg;
	}
	else
	{
		return "";
	}
}

// This function uses our previous function (formatMyDate) to put the dates in a certain format
// and then checks to make sure that the dates and times are in the correct order (start date
// preceeding the end date, start time preceeding the end time).  This function takes four parameters,
// (the start date, start time, end date, end time) and returns either an empty string, or an error 
// msg depending on how the function works out.
function checkDatesAndTimesInOrder(startDate, startTime, endDate, endTime)
{
	var errMsg = "";
	if(startDate == null || endDate == null)
	{
		//alert("I couldn't proccess the dates because one of them was null: startDate= " + startDate + " endDate= " + endDate);
		errMsg += "Error processing dates, they may not be in the proper format.\n";
	}
	
	var myStartDate = formatMyDate(startDate);
	var myEndDate = formatMyDate(endDate);
	//alert(myStartDate + " " + myEndDate);
	if(myStartDate > myEndDate)
	{
		//alert("endDate came before the startDate: startDate= " + startDate + " endDate= " + endDate);
		errMsg += "ERROR: The end date must be greater than or equal to start date.\n";
	} else {
		if(myStartDate == myEndDate)
		{
			//alert("startDate is the same day as endDate");
			if(formatThisTime(startTime) > formatThisTime(endTime))
			{
				//alert("endTime came before the startTime (and dates are in order): startTime= " + startTime + " endTime= " + endTime);
				errMsg += "ERROR: The end time must come after the start time.\n";
			}
		}
	}
	
	if(errMsg == "")
	{
		//alert("returning an empty string");
		return "";
	} else {
		//alert("returning an error Msg: errMsg= " + errMsg);
		return errMsg;
	}
}

//This function is always called by some other function 
//to check the validity of a date.  The routineSwitch variable
//is a boolean value that indicates whether the date should be 
//evaluated as mm/dd/yyyy format - a 'true' activates this evaluation.
//the actual validity of the date will still be 'false', but the
//dateDigest function will know to look for the month number in the
//first element instead of a Month name in the second.  The routineSwitch
//'true' action is currently only used by the closeCalendar function which 
//needs to take date stuff input from the calendar routine and turn it 
//into a valid date display.  Very confusing, but it works without breaking
//the carefully designed calendar widget code...
// FUNCTION RETURNS A STRING THAT IS A "STANDARD" DATE FORMAT
// FROM THE ARGUMENT, OR NULL IF THE DATE ISN'T RECOGNIZABLE
function makeValidDate(theDate, routineSwitch)
{
    //the dateDigest object is activated to evaluate the elements of the date
    var dateObject = new dateDigest(theDate, routineSwitch);
    //we ask the dateObject for its year and return null if there is none.
	if (dateObject.year == null || dateObject.year == "" || dateObject.month == null || dateObject.day == null)
    {
        return (null);
    }
    else
    {
        var day = dateObject.day;
        var month = dateObject.month;
        var year = dateObject.year;
        var monthNum = dateObject.monthNum;
        var monthNameUC = new Array ("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
     
        // Check if year is a valid number
        var num_year = (year * 10)/ 10;
        //window.alert("num_year=" + num_year + ", year=" + year);
		if (isNaN(num_year))
			return null;
		
		// Check if day is a valid number - Issue 8309
		if( isNaN( day ) )
			return null;
					
        //we're going to make the month all uppercase to check for validity of characters
        var monthUC = month.toUpperCase();
        var invalidDate = true;
        for (var i = 0; i < 12; i++)
        {
            if (monthNameUC[i] == monthUC)
            {
                invalidDate = false;
            }
        }
        if (invalidDate) return (null);

    	// check the year and adjust it to 1900 or 2000
    	if ( ("" + year).length < 1)
            {
    	    // window.alert("length < 1");
                return null;
            }
    	if ((num_year < 10) || (("" + year).length == 1))
            {
    	    // window.alert("length = 1");
    		year = "200" + num_year;
            }
    	else if (num_year < 100 || (("" + year).length == 2))
    	{
    	    // window.alert("length = 2");
    	    if (num_year > 50)
    		year = "19" + num_year;
    	    else 
                    year = "20" + num_year;
    	}
    	else if (num_year < 1000 || (("" + year).length == 3))
            {
    	    // window.alert("length = 3");
    		return (null);
            }
    	else if ( ("" + year).length > 4)
            {
    	    // window.alert("length > 4");
    		return (null);
            }
    	else if (num_year < 1900 )
            {
    	    // window.alert("length = 4");
    		return (null);
            }
    
    	// check for a reasonable day for the month
       var leapYear=false;
       if (
             (
                (year%4 == 0) //every fourth year is leap year
                &&
                !(year % 100 == 0) //unless evenly divisible by 4
             )
            ||
    	(year % 400 == 0) //except when divisible by 400
          )
       { 
        leapYear=true;
       } 
       var maxDays=31 //all the rest have 31
       if (monthNum==2 || monthUC==monthNameUC[1])    // Issue 8358 Added check for three letter months
       {
          if (leapYear)
          {
             maxDays=29;
          }
          else 
          {
             maxDays=28;
          }
       }
       if (month==4 || month==6 || month==9 || month==11 || monthUC==monthNameUC[3] || monthUC==monthNameUC[5] ||
	   		monthUC==monthNameUC[8] || monthUC==monthNameUC[10] ) // Issue 8358 Added check for three letter months
       {
          maxDays=30;
       }
       if ((day < 1) || (day > maxDays))
       {
        	return (null);
       }
    	// add leading "0" if needed so we show dd
    	if ((day < 10) && (day.length < 2))
        {
    		day = "0" + day;
        }
       
    	stdDate = day + "-" + month + "-" + year;
    	// alert("stdDate = " + stdDate);
    	return (stdDate);
     }
}
//This function is used to grab the components of a date for evaluation somewhere
//else. The date is assumed to be in dd-Mon-yyyy or dd-Mon-yy format unless the 
//routineSwitch is set to true.  If the routineSwitch is set to true, it will 
//evaluate the date as mm/dd/yy or mm/dd/yyyy.
//THIS FUNCTION IS INSTANTIATED AS AN OBJECT AND RETURNS VALUES FOR THE FOLLOWING: 
//day, month, monthNum, year
function dateDigest(theDate, routineSwitch)
{
    if (theDate != null && theDate != "")
    {
        var monthName = new Array ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
        var monthNameUC = new Array ("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
    	var stdDate = null;
    	var dateElements = null;
    	this.day = null;
    	this.month = "";
        this.monthNum = null;
    	this.year = null;
        var foundSep = 0;
    
    	// separators '/', '.', ',', '-' are ok
        stdDate = theDate;
    
         // get out all spaces in our date string
    	if (theDate.match(/ /) != null)
    	{
    	    stdDate = stdDate.replace(/ /g, 'X');
                foundSep = foundSep + 1
    	}
    
    	if (theDate.match(/\//) != null)
    	{
            stdDate = stdDate.replace(/\//g, 'X');
                foundSep = foundSep + 1
    	}
    	if (theDate.match(/\./) != null)
    	{
    	    stdDate = stdDate.replace(/\./g, 'X');
                foundSep = foundSep + 1
    	}
    	if (theDate.match(/,/) != null)
    	{
    	    stdDate = stdDate.replace(/,/g, 'X');
                foundSep = foundSep + 1
    	}
    	if (theDate.match(/-/) != null)
    	{
    	    stdDate = stdDate.replace(/-/g, 'X');
                foundSep = foundSep + 1
    	}
        if (foundSep > 0)
        {
    	    dateElements = stdDate.split('X');
        }
        else return null;
    
    	//alert("dateElements=" + dateElements + ", length=" + dateElements.length);

        if (dateElements[1].length > 2 && !routineSwitch && dateElements.length == 3)
        {
			if ((dateElements[dateElements.length-1].length < 4) || (dateElements[dateElements.length-1].length > 4)){
				return false;
			}else{
				this.year = dateElements[dateElements.length-1];
				if( this.year.match(/[^0-9]/i) ) { // Issue 8307 & 8309 Make sure there are no letters
					this.year = null;
					return;
				}
	            this.year = getTheYear(this.year);
			}
            if (this.year.length < 4 || this.year > 2999) 
            {
                this.year = null;
                return;
            }
        	this.day = dateElements[0];
        	this.month = dateElements[1];
            if (this.month.length > 3)
            {
                this.month = null;
                return;
            }
			else if( !routineSwitch && this.month.match(/[^a-z]/i) ) { // Issue 8307 Make sure there are only letters if
																	   // the format is dd-Mon-yyyy
				this.month = null;
				return; 
            }
			else
            {    
                this.monthNum = 1;
                var monthUC = this.month.toUpperCase();
                for (var x = 0;  monthNameUC[x] != monthUC; x++)
                {
                    this.monthNum = this.monthNum + 1;
                }
             }
        }
        else if (routineSwitch && dateElements.length == 3)
        {
            this.year = dateElements[2];
            this.year = getTheYear(this.year);
        	this.monthNum = dateElements[0];
        	this.day = dateElements[1];
			//alert('We should make it here!!');
            for (var i = 0; (i < this.monthNum); i++)
            {
                this.month = monthName[i];
            }
            //alert("month number is " + this.monthNum + "\nday is " + this.day + "\nyear is " + this.year + "\nmonth is " + this.month);
        }
        else
        {
            this.day = null;
            this.month = null;
            this.monthNum = null;
            this.year = null;
            return;
        }
    }
    //alert("day = " + this.day + ";  month = " + this.month + ";  year = " + this.year + ";  monthNum = " + this.monthNum);
}

function datesInOrder(beginDate, endDate)
{
	// Return true is the endDate is >= to beginDate, else false
	// NOTE: the date args are strings that have gone through makeValidDate()
	if (isEmpty(beginDate) || isEmpty(endDate))
		return false;

	// change the date into a yyyy/mm/dd
	var startDateObject = new dateDigest(beginDate, false);
	if (startDateObject == null || startDateObject.day == null)
		return (false);
		//alert("start day: " + startDateObject.day);
	var beginDateReverse = startDateObject.year + twoDigits(startDateObject.monthNum) + twoDigits(startDateObject.day);
	//alert("Beginning date: " + beginDateReverse);
	var endDateObject = new dateDigest(endDate, false);

	if (endDateObject == null || endDateObject.day == null)
		return (false);
		//alert("end day: " + endDateObject.day);
		//alert(endDateObject.monthNum);
	var endDateReverse = endDateObject.year + twoDigits(endDateObject.monthNum) + twoDigits(endDateObject.day);
	//alert("Ending date: " + endDateReverse);
    
	return (beginDateReverse <= endDateReverse);
}

function twoDigits(theNumberInt) {
  var theNumber = new String(theNumberInt);
  if (theNumber.length < 2) {
  	var	ourNumber = "0" + theNumber;
  	//alert('We got here: ourNumber= ' + ourNumber);
  	return ourNumber;
  } else {
  	return theNumber;
  }
}

function makeValidInteger(keepFormat, s)
{
	var goodInteger = s;
	var integerElements = null;
	var hasDollar = false;
	var hasCommas = false;
	var hasCents = false;

	if ((s == null) || isEmpty(s))
		return ("");

	// First we'll get rid of anything that isn't a number.
	// Then we'll rebuild with extras if keepFormat is true
	// or just return the number as a string if keepFormat is false.

	// any dollar signs?  if so, get rid of them
	if (s.match(/\$/) != null)
		hasDollar = true;

	// any commas?
	if (s.match(/,/) != null)
		hasCommas = true;

	// any cents?
	if (s.match(/\./) != null)
	{
		hasCents = true;
		intElements = s.split('.');
		s = intElements[0];
	}

	// get rid of any letters
	goodInteger = s.replace(/\D/g, '');

	// need to put back formatting?
	if (keepFormat)
	{
		var formattedInt = "";
		// commas
		if (hasCommas)
		{
			i = goodInteger.length - 1;
			comCnt = 0;
			while (i >= 0)
			{
				formattedInt += goodInteger.charAt(i);
				comCnt++;
				if ((comCnt % 3 == 0) && (i > 0))
				{
					formattedInt += ',';
				}
				i--;
			}
			straight = "";
			for (i = formattedInt.length - 1; i >= 0; i--)
				straight += formattedInt.charAt(i);
			goodInteger = straight;
		}
		if (hasDollar)
			goodInteger = "$" + goodInteger;
	}

	return(goodInteger);

}

function makeValidDecimal(s)
{
	var decimalPart = null;
	var nonDecimalPart = null;
	var numberParts = null;

	if ((s == null) || isEmpty(s))
		return ("");

	// split the string on decimal point(s)
	numberParts = s.split('.');
	//alert("s = " + s + "; part1 = " + numberParts[0] + "; part2 = " + numberParts[1]);

	// now get rid of anything in the 1st number part that isn't a number
	nonDecimalPart = numberParts[0].replace(/[^\d]/g, '');
	if (nonDecimalPart.length == 0)
		nonDecimalPart = "0";

	// do the same if we have a decimalPart
	if (numberParts.length > 1)
	{
		decimalPart = numberParts[1].replace(/[^\d]/g, '');

		if (decimalPart.length == 0)
			decimalPart = ".00";
		else if (decimalPart.length == 1)
			decimalPart = "." + decimalPart + "0";
		else if (decimalPart.length == 2)
			decimalPart = "." + decimalPart;
		else {
			var extraDigit = decimalPart.charAt(2);

			decimalPart = "." + decimalPart.substr(0,2);

			decimalPart = decimalPart - 0;  // convert to number
			if( extraDigit >= 5 ) // do proper rounding
			{
				// Special case because in Javascript .09 + .01 = .09999999999999999 (grrr)
				if( decimalPart == 0.09 )
					decimalPart = 0.1;
				else decimalPart += 0.01;
			}
	
			if( decimalPart == 1 )  // .99 got rounded to 1.0
			{
				nonDecimalPart -= 0; //convert to number
				nonDecimalPart += 1;
				nonDecimalPart += "";  // convert back to string
				decimalPart = ".00";
			}
			else if( decimalPart == 0 )
			{
				decimalPart = ".00";
			}
			else
			{
				decimalPart = decimalPart + "0000";  // convert back to string
				if( decimalPart.charAt(0) == '0' )
					decimalPart = decimalPart.substr(1,3); // remove extra 0 before decimal point
				else decimalPart = decimalPart.substr(0,3); // just truncate extra digits
			}
		}
	}
	else decimalPart = ".00";

	return(nonDecimalPart + decimalPart);
}

//very fine decimal formatting function
//from Danny Goodman's Javascript Bible
function format(expr, decplaces)
{
	if (!verifyNumberFormat(expr))
	{
		//alert(expr + " not valid format.");
		return "";
	}
	expr = removeCommas(expr);
	var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces));
	while(str.length <= decplaces)
	{
		str = "0" + str;
	}
	var decpoint = str.length - decplaces;
	var result = str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
	result = addCommas(result);
	return result;
}

function verifyNumberFormat(newValue)
{
	var legalChar = /[0-9\,\.]/;
	var containsIllegal = false;
	for (var i = 0; i < newValue.length; i++)
	{
		var myChar = newValue.charAt(i);
		if (legalChar.test(myChar) == false)
		{
			containsIllegal = true;
			break;
			//alert(myChar + " =  illegal character");
		}
	}
	
	return !containsIllegal;
}

//removes commas from an argument
function removeCommas(changeString)
{
	changeString = changeString + "";//force to string
	changeString = changeString.replace(/,/g, "");
	return changeString;
}

//format number/string with commas
//start with string where commas have been removed
//depends on removeCommas(), reverseString()
function addCommas(value)
{
	value = removeCommas(value);//just to be sure!
	value = reverseString(value);
	var result = "";
	var count = 1;
	var decIndex;
	if (value.indexOf(".") != -1)
	{//check for decimal
		decIndex = value.indexOf(".");
	}
	for (var i = 0; i < value.length; i++)
	{
		result += value.charAt(i);
		if ( (decIndex != null) && (decIndex >= i) )
		{//no commas at all after and including the decimal
			continue;
		}
		if (count % 3 == 0)
		{
			result += ",";
		}
		count++;
	}
	result = reverseString(result);
	if (result.charAt(0) == ",")
	{//remove leading comma, if present
		result = result.substring(1,result.length);
	}
	//alert(result);
	return result;
}

//used by addCommas function
function reverseString(value)
{
	value = value + "";//force to string
	var result = "";
	for (var i = value.length; i >= 0; i--)
	{
		result += value.charAt(i);
	}
	//alert(result);
	return result;
}

function checkAllocPct(f)
{
	var data = null;
	var integerPart = null;
	var decimalPart = null;
	var numberParts = null;

	data = f;
	if (data.split(".").length != 1)//the number contains a decimal point
		{
		numberParts = data.split(".");
		integerPart = numberParts[0];
		//alert("integerPart = " + integerPart);
		decimalPart = numberParts[1];
		//alert("decimalPart = " + decimalPart);
		
		if ( (integerPart.match(/[^\d]/) != null) || (decimalPart.match(/[^\d]/) != null) )//first check strings for non-number characters
		{
			//alert("bad number");
			return false;
		}
		if (decimalPart.length > 2)
		{
			//alert("bad number 2");
			return false;
		}
	} else {//no decimal point
		if (data.match(/[^\d]/) != null)
		{
			return false;
		}
	}
	//alert("good number");
	return true;
}

function isEmpty(s)
{
	if ((s == null) || (s == ""))
		return (true);
	else return(isBlank(s));
    
}

function isBlank(s)
{
    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t'))
            return false;
    }
    return true;
}

function isDigit(s)
{
    // This returns true if the string is a sigle digit.
    // match takes a regular expression and returns an array of matches if
    // there is a match and null if there is not. /d is a single digit (0-9)

    return s.match(/^\d$/) != null;
}

function isValidSQLName(string)
{
   if(string.match(/[^a-zA-Z0-9_ ]/)) { 
    return false;
   } else {
    return true;
   }
}
 //
 //	This is a copy of the "isNumber" function used on the search pages - <pg>

function checkNumber(number) 
{
  if (isNaN(number.value))
  {
    alert("This field only accepts an integer value. \nPlease enter only a number.");
    number.value="";
    number.focus();
  }
}

function checkInteger(field, mustEnter)
{
	var fieldValue = field.value;
	var goodInteger = null;

	// good integer?
	goodInteger = makeValidInteger(true, fieldValue);
	if (isEmpty(goodInteger))
	{
		window.alert("Please re-enter a valid integer (ddd,ddd) or nothing.");
		field.value = "";
		if (mustEnter)
			field.focus();
	}
	else field.value = goodInteger;
}

function checkDecimal(field, mustEnter)
{
	var fieldValue = field.value;
	var goodDecimal = null;

	// good decimal?
	goodDecimal = makeValidDecimal(fieldValue);
	if (isEmpty(goodDecimal))
	{
		field.value = "0.00";
		window.alert("Please enter a valid decimal (dd.dd).");
		if (mustEnter)
			field.focus();
	}
	else field.value = goodDecimal;
}


function mustEnter(field)
{
	var fieldValue = field.value;

	if (isEmpty(fieldValue) || isBlank(fieldValue))
	{
		window.alert("Please enter data into field.");
		field.focus();
	}
}

//START OF CALENDAR CODE
//THIS IS A SEPARATE SET OF ROUTINES THAT HAS BEEN INCORPORATED INTO DATAVALID
//FOR EASE OF IMPLEMENTATION

// routines to save/retrieve the fields whose input must be modified
var targetField = null;
var exFinish = 0; // Var for Expense

//opens a new window for the calendar checks for any valid year
// Exfin added for the widget in the Expense UI
function createCalendar(inputDate, returnField, xPos, yPos, exFin, msg)
{

	exFinish = exFin;
	//use the same argument for a different purpose: check dates in closeCalendar() for reportAdvanced.jsp
	var checkOrder = exFinish;
	checkOrder += "";
	if (checkOrder.indexOf("checkOrder=") != -1)
	{
		checkOrder = checkOrder.substring(checkOrder.indexOf("checkOrder=") + 11, checkOrder.length);
		exFinish = false;
	}
	else
	{
		checkOrder = false;
	}
	targetField = returnField;
	var dateOk = false;
	var goodDate = null;
	goodDate = makeValidDate(inputDate, false);
	inputDate = goodDate;

   if (navigator.appVersion.indexOf("Mac",0) != -1) 
   {
		calendarWindow = window.open("","Calendar","width=230,height=205,resizable=yes,scrollbars=no");
		if (calendarWindow.blur) calendarWindow.focus();
   } 
   else if( navigator.appVersion.indexOf("SunOS",0) != -1 ) {	 
		var calendarString = "width=326,height=300,resizable=yes,scrollbars=no,screenX=" + xPos + ",screenY=" + yPos + ",left=" + xPos + ",top=" + yPos;
		calendarWindow = window.open("","Calendar", calendarString);
		if (calendarWindow.blur) calendarWindow.focus();
   }
   else if( navigator.appVersion.indexOf("Linux",0) != -1 ) {
		var calendarString = "width=260,height=245,resizable=yes,scrollbars=no,screenX=" + xPos + ",screenY=" + yPos + ",left=" + xPos + ",top=" + yPos;
		calendarWindow = window.open("","Calendar", calendarString);
		if (calendarWindow.blur) calendarWindow.focus();
   }
   else 
   {
		var calendarString = "width=201,height=200,resizable=no,scrollbars=no,screenX=" + xPos + ",screenY=" + yPos + ",left=" + xPos + ",top=" + yPos;
		calendarWindow = window.open("","Calendar", calendarString);
		if (calendarWindow.blur) calendarWindow.focus();
   }
   if (inputDate != null && inputDate != "") 
   {
       var dateElements = new dateDigest(inputDate, false);
       //alert("the day is " + dateElements.day + "\nthe month is " + dateElements.monthNum + "\nthe year is " + dateElements.year);
       
       if (dateElements.day != null || dateElements.monthNum != null)
       {
           var aDate = dateElements.monthNum + "/" + dateElements.day + "/" + dateElements.year;   
           var theDate = new Date(aDate);
        
           var theMonth = dateElements.monthNum/1;
           var theDay =  dateElements.day/1;
           var theYear = dateElements.year/1;
        
          if (theMonth <= 12 && theMonth > 0 ) 
          {
                if (theDay > 0 && theDay <= getDaysInMonth(theMonth, theYear) )
                {
                   dateOk = true;
                }
                else //wrong day, clear field but accept month and year
                {
                    dateOk = true;
                    theDay = getDaysInMonth(theMonth, theYear);
                    returnField.value="";
                }
           }
           if ( dateOk != true )
           {
              var today = new Date();
              var thisYear = today.getFullYear();
              //alert(today.toLocaleString() + thisyear);
              var thismonth = today.getMonth() + 1;
              theMonth = thismonth;
              theYear = thisyear;
              theDay = today.getDate()
            }
       }
       else
       {
          var today = new Date();
          if (dateElements.year != null && dateElements.year != "" && dateElements.year.length == 4)
          {
             var thisyear = dateElements.year;
          }
          else 
          {
              var thisYear = today.getFullYear();
              //alert(today.toLocaleString() + thisyear);
          }
			
          var thismonth = today.getMonth() + 1;
          theMonth = thismonth;
          theYear = thisyear;
          theDay = today.getDate();
         
       }
    }
    else
    {
        returnField.value = "";
        var today = new Date();
        var thisyear = today.getFullYear();
        //alert(today.toLocaleString() + ", " + thisyear);
        var thismonth = today.getMonth() + 1;
        theMonth = thismonth;
        theYear = thisyear;
        theDay = today.getDate();
     }
       
   //call the function to populate the window
   generateCalendar(calendarWindow,theMonth,theDay,theYear, returnField.name, checkOrder, msg)
   return calendarWindow;
}
function browserVersion()
{
    if (document.all)
    {
        var stringVersion = navigator.appVersion;
        var result = stringVersion.match(5);
        if (result != null) return true;
        
        else return false;
    }
    else return false;
}

//generates the meat of the calendar
function generateCalendar(target, month, day, year, fieldName, checkOrder, msg) 
{
   //window.alert("The field is " + fieldName);
   var monthName = new Array ("January","February","March",
                               "April","May","June",
                               "July","August","September",
                               "October","November","December"
                              );
   //window.alert("month " + month + " day " + day + " year " + year); 
   target.document.open(); //begin table for calendar
   calendar = "<html><head><title>calendar</title>\n";
   calendar +="</head><body bgcolor='#577696' topmargin=0 leftmargin=0>\n";
   calendar +="<table border=0 cellspacing=1 cellpadding=4 width=200 align=left>\n";
   calendar +="<tr valign=top>\n";
   if (document.all && browserVersion())
   {
   calendar += "<STYLE TYPE='text/css'>\n";
   calendar += ".nav {\n";
   calendar += "font-size: 8px;\n";
   calendar += "font-family: clean, 'Trebuchet MS', Arial, Helvetica, Geneva, Swiss, SunSans-Regular;\n";
   calendar += "font-weight: bold }\n";
   calendar += ".calendarheader {\n";
   calendar += "    color: #333333;\n";
   calendar += "    font-size: 11px;\n";
   calendar += "    font-weight: bold;\n";
   calendar += "    line-height: 11px;\n";
   calendar += "    font-family: clean, \"Trebuchet MS\", Arial, Helvetica, Geneva, Swiss, SunSans-Regular;\n";
   calendar += "    background-color: #cccccc; }\n";
   calendar += ".calendarnumber {\n";
   calendar += "	color: black;\n";
   calendar += "	font-size: 11px;\n";
   calendar += "	line-height: 11px;\n";
   calendar += "	font-family: clean, \"Trebuchet MS\", Arial, Helvetica, Geneva, Swiss, SunSans-Regular;}\n";
   calendar += "a:link {text-decoration: none }\n";
   calendar += "a:active {text-decoration: underline }\n";
   calendar += "a:visited {text-decoration: none }\n";
   calendar += "a:hover {text-decoration: underline }\n";
   calendar += "</STYLE>\n";
   }
   var mthIdx = month/1;
   var endday = getDaysInMonth(mthIdx, year);

   //next month and previous month buttons
   var goPrevMonth = prevMonth(mthIdx)
   var goNextMonth = nextMonth(mthIdx)
   var nextPosYear = anotherYear("next",month,year)
   var prevPosYear = anotherYear("prev",month,year)
   var nextYear = year + 1;
   var prevYear = year - 1;

   calendar +="<tr><td align=left colspan=2 class=nav>&lt;&lt;<font color=white'><a href='javascript:opener.generateCalendar(self,"+month+",0,"+prevYear+",\""+fieldName+"\"," + checkOrder + ",\"" + msg + "\")' style='color: rgb(0,0,0)'>PREV</a></font></td>\n";
   calendar +="<td align=center colspan=3><font color='white' face='Helvetica,Arial,Futura'><b>Year</b></font></td>\n";
   calendar +="<td align=right colspan=2 class=nav><a href='javascript:opener.generateCalendar(self,"+month+",0,"+nextYear+",\""+fieldName+"\"," + checkOrder + ",\"" + msg + "\")' style='color: rgb(0,0,0)'>NEXT</a>&gt;&gt;</td></tr>\n";
   calendar +="<tr><td align=left bgcolor=#C0C0C0><a href='javascript:opener.generateCalendar(self,"+goPrevMonth+",0,"+prevPosYear+",\""+fieldName+"\"," + checkOrder + ",\"" + msg + "\")' style='color: rgb(0,0,0)'>&lt;&lt;</a></td>\n";
   calendar +="<td colspan=5 align=center bgcolor=#C0C0C0 width='130' nowrap>\n"; //month header
   var index = (mthIdx-1);
   calendar +="<b><font face='Helvetica,Arial,Futura'>" + monthName[index]; 
   calendar += " " + year + "</font></b></td>\n";
   calendar +="<td align=right bgcolor=#C0C0C0><a href='javascript:opener.generateCalendar(self,"+goNextMonth+",0,"+nextPosYear+",\""+fieldName+"\"," + checkOrder + ",\"" + msg + "\")' style='color: rgb(0,0,0)'>&gt;&gt;</a></td></tr>\n";
   calendar +="</tr><tr align=center valign=top>\n"; //write in the day of week labels
   calendar +="<td width=10 class=calendarheader nowrap><font color='#FF0000'><b>&nbsp;S</b></font></td>\n";
   calendar +="<td width=10 class=calendarheader nowrap><b>&nbsp;M</b></td>\n";
   calendar +="<td width=10 class=calendarheader nowrap><b>&nbsp;T</b></td>\n";
   calendar +="<td width=10 class=calendarheader nowrap><b>&nbsp;W</b></td>\n";
   calendar +="<td width=10 class=calendarheader nowrap><b>&nbsp;T</b></td>\n";
   calendar +="<td width=10 class=calendarheader nowrap><b>&nbsp;F</b></td>\n";
   calendar +="<td width=10 class=calendarheader align=right nowrap><font color='#FF0000'><b>&nbsp;S</b></font></td>\n";
   calendar +="</tr>";
   if (day != 0)
   {
      origyear = year;
      origday = day;
      origmonth = month;
   }
   wholeDate = month + "/01/" + year;
   thedate = new Date(wholeDate);
   firstDay = thedate.getDay();

   selectedmonth = mthIdx;
   var today = new Date();
   var thisyear = today.getFullYear();
   var thismonth = today.getMonth() + 1;
   selectedyear = year
   var lastDay = (endday + firstDay+1);
   if (lastDay % 7 != 0)
    {
        while (lastDay % 7 != 0)
        { 
        lastDay = lastDay + 1;
        }
     }
   calendar +="<tr>"
   for (var i = 1; i <= lastDay; i++)
   {
      if (i <= firstDay)
      {
         calendar +="<td class=calendarnumber bgcolor='#eeeeee'>&nbsp;</td>\n"; // 'empty' boxes prior to first day
      }
      else if (i-firstDay > endday) 
      {
          calendar +="<td class=calendarnumber bgcolor='#eeeeee'>&nbsp;</td>\n";
      }  
      else 
      {
          // enter date number
         if (
             selectedyear == origyear 
             && 
             selectedmonth == origmonth 
             && i-firstDay == origday
            )  
         {
  	       calendar += "<td class=calendarnumber bgcolor='#ffbd29' align=center>\n";
           calendar += "<a href='JavaScript:self.close();opener.closeCalendar";
           calendar += "( \"" + fieldName +"\","+selectedmonth + ","+(i-firstDay)+",";
           calendar += selectedyear + "," + checkOrder + ",\"" + msg + "\")' style='color: rgb(255,0,0)' > "+(i-firstDay)+"</a></td>\n";
         }
         else
         {
            calendar +="<td class=calendarnumber bgcolor='#eeeeee' align=center>\n";
            calendar +="<a href='JavaScript:self.close();opener.closeCalendar";
            calendar += "(\"" + fieldName + "\", " + selectedmonth + ","+(i-firstDay)+",";
            calendar +=  selectedyear + "," + checkOrder + ",\"" + msg + "\")'> "+(i-firstDay)+"</a></td>\n";
         }
      }

      if (i % 7 == 0 &&  i != lastDay) //must start new row after each week
      {
         calendar +="</tr><tr>\n";
      }
   }
   calendar +="</tr>\n";

   //separator line
  // calendar +="";

    calendar +="</table></body></html>";
    target.document.write(calendar);
    target.document.close()	
}

function isLeapYear(year)
{
   var leapYear=false;
   if (
         (
            (year%4 == 0) //every fourth year is leap year
            &&
            !(year % 100 == 0) //unless evenly divisible by 4
         )
        ||
	(year % 400 == 0) //except when divisible by 400
      )
   { 
      leapYear=true;
   }  
   return leapYear;
}


function getDaysInMonth(mth, Yr)
{
   var maxDays=31 //all the rest have 31
   if (mth==2)    // Feb is the problem
   {
      if (isLeapYear(Yr))
      {
         maxDays=29;
      }
      else 
      {
         maxDays=28;
      }
   }
   if (mth==4 || mth==6 || mth==9 || mth==11)// thirty days hath...
   {
      maxDays=30;
   }
   return maxDays;
}


// The Calendar

//calculation functions
function getTheYear(theYear)
{
    var _year = theYear;
    var num_year = (theYear * 10)/ 10;
    if (_year.length == 4 && num_year > 100)
        return _year;
            
    else if (_year.length == 2 || num_year < 100)
    {
	    if (num_year > 50)
		_year = "19" + num_year;
	    else 
        _year = "20" + num_year;
    } 

    if (_year.length < 4 || num_year > 2999) 
    {
        _year = null;
    }

    return _year;
}
function nextMonth(theMonth) 
{
   if (theMonth==12)
   {
      theMonth = 1;
   }
   else
   {
      theMonth++; 
   }
   return theMonth;
}


function prevMonth(theMonth) 
{
   if (theMonth==1)
   {
      theMonth = 12;
   }
   else
   {
      theMonth--;
   } 
   return theMonth
}

//increments or decrements month when it goes past Jan or Dec
function anotherYear(direction,month,year)
{
   var theYear =  year;
   if (direction=="next")
   {
      if (month == 12)
      {
         theYear += 1;
      }
   }
   if (direction=="prev")
   {
      if (month == 1)
      {
         theYear -= 1;
      }
   }
   return theYear
}

function closeCalendar(inputFieldName, month, day, year, checkOrder, msg)
{

	var inputField = eval(targetField);
	valueString = new String(month) + "-" + new String(day) + "-" + new String(year);
	inputField.value = makeValidDate(valueString, true);
	
	if (checkOrder)
	{
		var errMsg = checkDatesInOrder(makeToday(),valueString);
		if (errMsg == "")
		{
			inputField.value = makeValidDate(valueString, true);
		}
		else
		{
			inputField.value = "";
			inputField.focus();
			alert(msg);
		}
	}	
	
	// This was added for the Calendar widget needing to update the list view in Expense
	if( exFinish ) {
		var newDate = makeValidDate(valueString, true);
		setExDate(newDate,document.forms[0],1);
	}
}

function makeToday()
{
	var today = new Date();
	var theYear = today.getFullYear();
	var theMonth = today.getMonth();
	var theDay = today.getDate()
	var todaysDate = theDay + "-" + convertMonthNumToMonthString(theMonth) + "-" + theYear;
	return todaysDate;
}
function calendarWidget(theFieldName)
{

var targetPrefix = "";
var yPos = "200";
var xPos = "200";
if (document.all)
{

targetPrefix = "document.forms[0].";
var theField = new Object;
var evalstring = targetPrefix + theFieldName
theField = eval(evalstring);

evalstring = targetPrefix + theFieldName + ".value";
var theDate = eval(evalstring);


}
else
{
targetPrefix = "document.forms[0].";
var theField = targetPrefix + theFieldName;

evalstring = targetPrefix + theFieldName+ ".value";

var theDate = eval(evalstring);

}
createCalendar(theDate, theField, xPos, yPos);
}
//  End hide from old browsers -->

