//--------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	Time_Format
//  Description:	Formats a time value to a given time format
//  Arguments:		timevalue 	- the time value to be formatted
//					format 		- the format to be used
//  Return Value:	A formatted time string
//  Comments:		(none)
//--------------------------------------------------------------------------------------
function Time_Format(timevalue, stripSeconds) {
	var idxH = 0;
	var idxM = 0;
	var idxS = 0;
	var idxT = 0;
	var separator = "";
	var hours = 0;
	var minutes = 0;
	var seconds = 0;
	var sAMPM = "";

	//If the timevalue is empty or contains true, return an empty string
	if (timevalue == "" || timevalue == true) {
		return "";
	}

	var format = window.userTimeFormat;
	if (format == null)
	     format = parent.window.userTimeFormat;
	     
	format = format.replace(/TT/i,"AMPM");
	
	//Determine the structure of the current time format
	idxH = format.indexOf("H", 0);
	idxM = format.indexOf("M", 0);
	idxS = format.indexOf("S", 0);
	idxT = format.indexOf("AMPM", 0);
	separator = format.substring(idxM - 1, idxM);
	//Determine the hours, minute and second values of the time to be formatted
	hours = timevalue.getHours();
	minutes = timevalue.getMinutes();
	seconds = timevalue.getSeconds();

	//Determine whether or not the time is during the morning or afternoon
	if (idxT > -1) {
		if (hours >= 12) {
			sAMPM = " PM";
			if (hours > 12) {
				hours = hours - 12;
			}
		}
		else {
			sAMPM = " AM";
			if (hours == 0) {
				hours = 12;
			}
		}
	}

	//Give all time values leading zeros as needed
	if (hours < 10 && format.substring(idxH, idxH + 2) == "HH") {
		hours = "0" + hours;
	}
	if (minutes < 10 && format.substring(idxM, idxM + 2) == "MM") {
		minutes = "0" + minutes;
	}
	if (seconds < 10 && format.substring(idxS, idxS + 2) == "SS") {
		seconds = "0" + seconds;
	}
	
	//Return the formatted time value
	if (stripSeconds)
	     return buildTimeStringNoSeconds(hours, minutes, sAMPM, separator)
	else
	     return buildTimeString(hours, minutes, seconds, sAMPM, separator);
	
	//return hours + separator + minutes + separator + seconds + sAMPM;

}

//----------------------------------------------------------------------------------------
//  Author:         Heath Matthias
//  Procedure Name: buildTimeStringNoSeconds
//  Description:	Returns the user's current local time, formatted to the user's
//					current time format
//  Arguments:		hours - current hour 
//					minutes - current minutes
//					sAMPM - AM or PM
//					separator - :
//  Return Value:	The form field specified will be updated with the user's 
//					current system time
//  Comments:		This function returns the time with no seconds
//----------------------------------------------------------------------------------------
function buildTimeStringNoSeconds(hours, minutes, sAMPM, separator)
{
	return hours + separator + minutes + sAMPM;	
}

//----------------------------------------------------------------------------------------
//  Author:			Jeremy Marshall
//  Procedure Name:	buildTimeString
//  Description:	Returns the user's current local time, formatted to the user's
//					current time format
//  Arguments:		hours - current hour 
//					minutes - current minutes
//					seconds - current seconds
//					sAMPM - AM or PM
//					separator - :
//  Return Value:	The form field specified will be updated with the user's 
//					current system time
//  Comments:		This function is needed so it can be overriden and return current time
//					without seconds for workflow
//----------------------------------------------------------------------------------------

function buildTimeString(hours, minutes, seconds, sAMPM, separator)
{
	return hours + separator + minutes + separator + seconds + sAMPM;	
}

//----------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	Time_Now
//  Description:	Returns the user's current local time, formatted to the user's
//					current time format
//  Arguments:		field - the name of the HTML form field to store the current time
//  Return Value:	The form field specified will be updated with the user's 
//					current system time
//  Comments:		This function assumes that the form field in question has a
//					populated format attribute
//----------------------------------------------------------------------------------------
function Time_Now(field, stripSeconds) {
	var now = new Date();
	
	if(typeof(field) != "object") //it is a ID
		field = document.getElementById(field);
		
	//Update the form field with the current time formatted to the user's current format
	field.value = Time_Format(now,stripSeconds);
	field.focus();

}


//-------------------------------------------------------------------------------------------------
//  Author:			Sally Xu, Brian Tauke
//  Procedure Name:	Time_onInput
//  Description:	Examines a character entered into a time field and determines
//					whether or not to allow the character to be appended to the 
//					existing time value
//  Arguments:		field - the name of the HTML form field containing the time
//  Return Value:	Boolean - True if the entered character is allowed
//							  False if the entered character is invalid
//  Comments:		This function assumes that the form field in question has a
//					populated format attribute
//--------------------------------------------------------------------------------------------------
function Time_onKeyPress(field, trimSeconds) {
	var inputChar = 0;
	var sInput = "";
	var idxH = 0;
	var idxM = 0;
	var idxS = 0;
	var idxT = 0;
	var separator = "";
	var hours = 0;
	var minutes = 0;
	var seconds = 0;
     

	//Identify the character that was entered by the user
	inputChar = window.event.keyCode;
	
	if(IsMac())//Allow Tab for MAC
	{
		if (inputChar == 9) {
			return true;
		}		
	}
	//Allow the backspace character
	if (inputChar == 8) {
		return true;
	}

	//Read in the field value and format strings
	sInput = field.value;
	
	var format = window.userTimeFormat;
	if (format == null)
	     format = parent.window.userTimeFormat;
	     
	format = format.replace(/TT/i,"AMPM");

	//Determine the structure of the current time format
	idxH = format.indexOf("H", 0);
	idxM = format.indexOf("M", 0);
	idxS = format.indexOf("S", 0);
	idxT = format.indexOf("AMPM", 0);
	separator = format.substring(idxM - 1, idxM);

	//Only numeric digits, the separator value or AM/PM characters are allowed to be input
	if (inputChar < 48 || inputChar > 58) {
		if (idxT == -1) {
			return false;
		}
		else {
			if ((String.fromCharCode(inputChar) != " ") &&
				(String.fromCharCode(inputChar) != "A") &&
				(String.fromCharCode(inputChar) != "a") &&
				(String.fromCharCode(inputChar) != "P") &&
				(String.fromCharCode(inputChar) != "p") &&
				(String.fromCharCode(inputChar) != "M") &&
				(String.fromCharCode(inputChar) != "m")) {
					return false;
			}
		}
	}
	
	//Do not exceed the maximum string length (if no text is selected)
	if (!IsMac()) {
		if (document.selection.type.toLowerCase() != "text") {
			// No Text is selected
			if (idxT < 0) {
				if (sInput.length == 8) {			
					return false;
				}
			}
			else {
				if (sInput.length == 11) {			
					return false;
				}
			}
		}	
	}
	//Determine the hours value
	if (sInput.indexOf(separator) > 0) {
		hours = parseInt(sInput.substring(0, sInput.indexOf(separator)));
	}
	else {
		hours = parseInt(sInput);
	}

	//Determine the minutes value
	if (sInput.indexOf(separator) > 0) {
		if ((sInput.indexOf(separator) != sInput.lastIndexOf(separator)) &&
			(sInput.lastIndexOf(separator) > 0)) {
				minutes = parseInt(sInput.substring(sInput.indexOf(separator) + 1, sInput.lastIndexOf(separator)));
		}
		else {
			minutes = parseInt(sInput.substring(sInput.indexOf(separator) + 1));
		}
	}

	//Determine the seconds value
	
	     if (sInput.indexOf(separator) != sInput.lastIndexOf(separator)) {
		     if (sInput.indexOf(" ") > 0) {
			     seconds = parseInt(sInput.substring(sInput.lastIndexOf(separator) + 1, sInput.indexOf(" ")));
		     }
		     else {
			     seconds = parseInt(sInput.substring(sInput.lastIndexOf(separator) + 1));
		     }
	     }

	//Do not allow consecutive separators or more than two separator characters. Only allow one if trimseconds is true
	if (trimSeconds){
	     if ((String.fromCharCode(inputChar) == separator) && 
		     ((sInput.lastIndexOf(separator) == sInput.length -1) || (sInput.lastIndexOf(separator) > 0))) {		
			     return false;
	     }
	}
	else{
	     if ((String.fromCharCode(inputChar) == separator) && 
		     ((sInput.lastIndexOf(separator) == sInput.length -1) || (sInput.lastIndexOf(separator) > 2))) {		
			     return false;
	     }
	}
	
	//Do not allow an AM/PM character or a separator value at the beginning of the string or immediately following a separator character
	if ((sInput.length == 0 || sInput.substring(sInput.length - 1, sInput.length) == separator) && 
		(inputChar < 48 || inputChar > 58)) {
			return false;
	}

	//Automatically add a separator character between hour, minute and second values. If no seconds, just add one seperator
	if (trimSeconds){
	     if ((String.fromCharCode(inputChar) != separator) && 
		     (sInput.lastIndexOf(separator) != sInput.length -1) &&
		     ((sInput.length == 1 && ((sInput == 2 && inputChar > 51) || sInput > 2)) ||
		      (sInput.length == 2 && sInput.indexOf(separator) == -1))) 
		      //(sInput.length == 3 && sInput.indexOf(separator) == 1 && minutes > 5) ||
		      //(sInput.length == 4 && sInput.indexOf(separator) == 1) ||
		      //(sInput.length == 4 && sInput.indexOf(separator) == 2 && minutes > 5) ||
		      //(sInput.length == 5 && sInput.indexOf(separator) == 2))) 
		      {
			     field.value = field.value + separator;
		      }
    }
    else{
       if ((String.fromCharCode(inputChar) != separator) && 
		     (sInput.lastIndexOf(separator) != sInput.length -1) &&
		     ((sInput.length == 1 && ((sInput == 2 && inputChar > 51) || sInput > 2)) ||
		      (sInput.length == 2 && sInput.indexOf(separator) == -1) ||
		      (sInput.length == 3 && sInput.indexOf(separator) == 1 && minutes > 5) ||
		      (sInput.length == 4 && sInput.indexOf(separator) == 1) ||
		      (sInput.length == 4 && sInput.indexOf(separator) == 2 && minutes > 5) ||
		      (sInput.length == 5 && sInput.indexOf(separator) == 2))) 
		      {
			     field.value = field.value + separator;
		      }
    }    

	//If no errors were found, return true to accept the input character
	return true;

}


//---------------------------------------------------------------------------------------------
//  Author:			Brian Tauke
//  Procedure Name:	Time_Unformat
//  Description:	Formats an already formatted time into a new time format
//  Arguments:		sInput	 - the time value to be reformatted
//					format	 - the old format that was used
//					unformat - the new format to be used
//  Return Value:	A reformatted time string
//	Comments:		This function temporarily will return the time value passed 
//					to it until additional logic is needed
//----------------------------------------------------------------------------------------------
function Time_Unformat(sInput) {

	var format = window.userTimeFormat;
	var unformat = window.serverTimeFormat;
	
	//Return the time value string 
	return sInput;

}
//----------------------------------------------------------------------------------------
//  Author:			Sally Xu
//  Procedure Name:	Time_onChange
//  Description:	Checks the validity of a time value string, and if the time is
//					valid it is formatted to a given time format
//  Arguments:		field - the name of the HTML form field containing the time
//  Return Value:	The form field specified will be updated with the formatted time
//  Comments:		This function assumes that the form field in question has a
//					populated format attribute
//----------------------------------------------------------------------------------------
function Time_onChange(field) {

	//If valid, format the time according to the user's preferred format
	if (Time_Validate(field) != false) {
		field.value = Time_Format(Time_Validate(field), field.format);
	}

}

//-----------------------------------------------------------------------------------------------
//  Author:			Sally Xu, Brian Tauke
//  Procedure Name:	Time_Validate
//  Description:	Verifies that a given HTML form field contains a valid time
//					string
//  Arguments:		field - the name of the HTML form field containing the time
//  Return Value:	True if the field contains an empty string
//					False if the field contains an invalid time
//					A date variable if the field contains a valid time
//  Comments:		This function assumes that the form field in question has a
//					populated format attribute
//------------------------------------------------------------------------------------------------
//DO NOT DELETE USED FOR INBOUND FORM FIELDS
function Time_Validate(field,ignoreSeconds) {
	var sInput = "";
	var format = "";
	var idxH = 0;
	var idxM = 0;
	var idxS = 0;
	var idxT = 0;
	var separator = "";
	var hours = 0;
	var minutes = 0;
	var seconds = 0;
	var thischar = "";
	var nextchar = "";
	var nextchars = "";	
	var res510 = "";

	if (!field)
		return true;
	// Common.js is needed for this call
	if (typeof(ResourceID510) != "undefined")
		res510 = ResourceID510;
	else
		res510 = GetReplacementString(510);
	
	//Read in the field value and format strings
	sInput = field.value.toUpperCase();
	format = format = window.userTimeFormat;
	format = format.replace(/TT/i,"AMPM");
	if (format.indexOf("SS") != -1){
	     if (ignoreSeconds){
	          format = format.substring(0,format.indexOf("SS")-1) + 
	               format.substring(format.indexOf("SS") + 2,format.length);
         }
    }

	//If the field is empty, return true
	if (sInput.length == 0) {
		return true;
	}

	//If there is no specified format, return true
	if (format.length == 0) {
		return true;
	}

	//Determine the structure of the current time format
	idxH = format.indexOf("H", 0);
	idxM = format.indexOf("M", 0);
	idxS = format.indexOf("S", 0);
	idxT = format.indexOf("AMPM", 0);
	separator = format.substring(idxM - 1, idxM);

	//Determine the hour, minute and second values
	if (sInput.indexOf(separator) > -1) {
		hours = parseFloat(sInput.substring(0, sInput.indexOf(separator)));
		if (sInput.lastIndexOf(separator) != sInput.indexOf(separator)) {
			minutes = parseFloat(sInput.substring(sInput.indexOf(separator) + 1, sInput.lastIndexOf(separator)));
			if ((idxT == -1) || (sInput.indexOf(" ") == -1)) {
				seconds = parseFloat(sInput.substring(sInput.lastIndexOf(separator) + 1));
			}
			else {
				seconds = parseFloat(sInput.substring(sInput.lastIndexOf(separator) + 1, sInput.indexOf(" ")));
			}
		}
		else {
	         if (ignoreSeconds){
	              var minRegExp = /:\d*/;
	              var minFound = minRegExp.exec(sInput);
	              if (minFound[0] != "")
	                   minutes = minFound[0].substring(1,minFound[0].length);
	              else{
	                   popMessage(res510 + " " + format, field);
		               return false;
		     }
	    }else{
			popMessage(res510 + " " + format, field);
			return false;
			//minutes = parseFloat(sInput.substring(sInput.indexOf(separator) + 1));
		}
	   }
	} else {
		popMessage(res510 + " " + format, field);
		return false;
	}	
	
	//Verify that only numerics, AM/PM characters and separator values are used in the time
	for (x=0; x < sInput.length; x++) {
		thischar = sInput.substring(x, x+1);
		nextchar = sInput.substring(x+1, x+2);
		nextchars = sInput.substring(x+1, x+3);

		//AM or PM characters must follow a space
		if (thischar == " ") {
			if ((nextchars != "AM") && (nextchars != "PM")) {
				popMessage(res510 + " " + format, field);
				return false;
			}
			else {
				x = x + 2;
			}
		}
		//Numerics, AM/PM and separator values are the only other allowed characters
		else {
			if ((isNaN(thischar)) && 
				(thischar != separator) && 
				(thischar != "A") && 
				(thischar != "P") && 
				(thischar != "M")) {
					popMessage(res510 + " " + format, field);
					return false;
			}
		}
	}
	
	//Verify that the hour, minute and second values are not too large
	if ((idxT < 0 && hours > 24) || 
		(idxT > 0 && hours > 12) || 
		(idxT > 0 && sInput.indexOf(" AM") < 0 && sInput.indexOf(" PM") < 0) ||
		(minutes > 60) || 
		(seconds > 60)) {
			popMessage(res510 + " " + format, field);
			return false;
	}

	//Convert hours to 24-hour JavaScript time
	if ((idxT > -1) && (sInput.indexOf(" PM") > 0) && (hours != 12)) {
		hours = hours + 12;
	}
	if ((idxT > -1) && (sInput.indexOf(" AM") > 0) && (hours == 12)) {
		hours = hours - 12;
	}

	//if seconds are left off the time then assume 0	
	if (isNaN(seconds)) {
		seconds = 0;
	}
				
	//If no errors are found, return the valid time as a JavaScript date variable
	return new Date(1971, 11, 29, hours, minutes, seconds);

}

function ValidateTimeEntryFields(source, arguments)
{
     //make sure that days, hours, and minutes are filled out
     //alert(source.controltovalidate.substring(source.controltovalidate.length-1,source.controltovalidate.length));
     var value = source.controltovalidate.substring(0,source.controltovalidate.length-2)
     var intCnt = source.controltovalidate.substring(source.controltovalidate.length-1,source.controltovalidate.length);
	
     while(document.getElementById(value + '_' + intCnt) != null )
	{
	     if (!((document.getElementById(value + '_' + intCnt).value == null) ||
	         (document.getElementById(value + '_' + intCnt).value == "")))
	     {
	         arguments.IsValid = true;
	         return;
	     }
	     intCnt++
	}
    
	arguments.IsValid = false;
	return;
}

//sets the mulitple select time control with the current time
function Time_Now_Multi(hourFieldID, minuteFieldID,amPmFieldID){
    var hourField = document.getElementById("field" + hourFieldID);
    var minuteField = document.getElementById("field" + minuteFieldID);
    var amPmField = null
    if (amPmFieldID)
         amPmField = document.getElementById("field" + amPmFieldID);
    var now = new Date();
  
     setTimeFields(now,hourField,minuteField,amPmField)
}

function setTimeFields(time,hourField,minuteField,amPmField){   
     var currTime = Time_Format(time,true);
     var hours = currTime.substring(0,currTime.indexOf(":"));
     var minutes = currTime.substring(currTime.indexOf(":")+1,currTime.indexOf(":")+3);
     var amPm = "";
     if (amPmField != null)
        amPm = currTime.substring(currTime.indexOf(":")+4,currTime.length);     
    if (amPmField != null)
    	hourField.selectedIndex = hours-1;
    else
    	hourField.selectedIndex = hours;
    //for minutes, we may have to round if selected items doesn't equal 60
    if (minuteField.options.length == 60)
         minuteField.selectedIndex = minutes;
    else
        roundToMinutes(minuteField,minutes);
    
    if(amPmField != null){
          if (amPm == "AM")
               amPmField.selectedIndex = 0;
          else
               amPmField.selectedIndex = 1;
    }
     
} 

function roundToMinutes(minuteField,minutes){
     var lowValue = 99;
     var selectIndex = -1;
     for(i=0; i<minuteField.options.length; i++){
          var newValue = Math.abs(minuteField.options[i].text-minutes);
          if (newValue < lowValue){
              lowValue =  newValue;
              selectIndex = i;
          }
     }
     minuteField.selectedIndex = selectIndex;
     
}
