

//JS Functions @0-5E65E7E8
var isNN = (navigator.appName.indexOf("Netscape") != -1);
var isIE = (navigator.appName.indexOf("Microsoft") != -1);
var IEVersion = (isIE ? getIEVersion() : 0);
var EditableGrid = false;

function ccsShowError(control, msg)
{
  alert(msg);
  control.focus();
  return false;
}

function getIEVersion()
{
  var userAgent = window.navigator.userAgent;
  var MSIEPos = userAgent.indexOf("MSIE");
  return (MSIEPos > 0 ? parseInt(userAgent.substring(MSIEPos+5, userAgent.indexOf(".", MSIEPos))) : 0);
}

function inputMasking(evt)
{
  if (isIE && IEVersion > 4)
  {
    if (window.event.altKey) return false;
    if (window.event.ctrlKey) return false;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = window.event.keyCode;
      this.value = applyMask(keycode, mask, this.value);
    }
    return false;
  }
  else
    return true;
}

function applyMask(keycode, mask, value)
{
  var digit = (keycode >= 48 && keycode <= 57);
  var plus = (keycode == 43);
  var dash = (keycode == 45);
  var space = (keycode == 32);
  var uletter = (keycode >= 65 && keycode <= 90);
  var lletter = (keycode >= 97 && keycode <= 122);
  
  var pos = value.length;
  switch(mask.charAt(pos))
  {
    case "0":
      if (digit)
        value += String.fromCharCode(keycode);
      break;
    case "L":
      if (uletter || lletter)
        value += String.fromCharCode(keycode);
    default:
      var isMatchMask = (String.fromCharCode(keycode) == mask.charAt(pos));
      while (pos < mask.length && mask.charAt(pos) != "0")
        value += mask.charAt(pos++);
      if (!isMatchMask && pos < mask.length)
        value = applyMask(keycode, mask, value);
  }  
  return value;
}

function validate_control(control)
{
/*
ccsCaption - string
ccsErrorMessage - string

ccsRequired - boolean
ccsMinLength - integer
ccsMaxLength - integer
ccsRegExp - string

ccsValidator - validation function

ccsInputMask - string
*/
  var errorMessage = control.ccsErrorMessage;
  var customErrorMessage = (typeof(errorMessage) != "undefined");
   
  if (typeof(control.ccsRequired) == "boolean" && control.ccsRequired)
    if (control.value == "")
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is required.");

  if (typeof(control.ccsMinLength) == "number")
    if (control.value != "" && control.value.length < parseInt(control.ccsMinLength))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The length in field " + control.ccsCaption + " can't be less than " + parseInt(control.ccsMinLength) + " symbols.");

  if (typeof(control.ccsMaxLength) == "number")
    if (control.value != "" && control.value.length > parseInt(control.ccsMaxLength))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The length in field " + control.ccsCaption + " can't be greater than " + parseInt(control.ccsMaxLength) + " symbols.");

  if (typeof(control.ccsRegExp) == "string")
    if (control.value != "" && (control.value.search(new RegExp(control.ccsRegExp, "i")) > 0))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is not valid.");
  
  if (typeof(control.ccsValidator) == "function")
    if (!control.ccsValidator())
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is not valid.");

  return true;
}

function validate_row(rowId, form)
{
  var result = true;
  var isInsert = false;
  if(typeof(eval(form + "EmptyRows")) == "number")
    if(eval(form + "Elements").length - rowId <= eval(form + "EmptyRows"))
      isInsert = true;
    for (var i = 0; i < eval(form + "Elements")[rowId].length && isInsert; i++)
      isInsert = GetValue(eval(form + "Elements")[rowId][i]) == "";
  if(isInsert) return true;

  if(typeof(eval(form + "DeleteControl")) == "number")
    {
      var control = eval(form + "Elements")[rowId][eval(form + "DeleteControl")];
      if(control.type == "checkbox")
        if(control.checked == true ) return true;
      if(control.type == "hidden")
        if(control.value != "" ) return true;
    }

  for (var i = 0; i < eval(form + "Elements")[rowId].length && (result = validate_control(eval(form + "Elements")[rowId][i])); i++);
  return result;
}

function GetValue(control) {
    if (typeof(control.value) == "string") {
        return control.value;
    }
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
        var j;
        for (j=0; j < control.length; j++) {
            var inner = control[j];
            if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
                return inner.value;
            }
        }
    }
    else {
        return GetValueRecursive(control);
    }
    return "";
}

function GetValueRecursive(control)
{
    if (typeof(control.value) == "string" && (control.type != "radio" || control.status == true)) {
        return control.value;
    }
    var i, val;
    for (i = 0; i<control.children.length; i++) {
        val = GetValueRecursive(control.children[i]);
        if (val != "") return val;
    }
    return "";
}


function validate_form(form)
{
var result = true;

  if(typeof(form) == "object") {
	if (typeof(eval(form.name + "Elements")) == "object") 
	  for (var j = 0; j < eval(form.name + "Elements").length && result; j++) result = validate_row(j, form.name);
	else 
	  for (var i = 0; i < form.elements.length && (result = validate_control(form.elements[i])); i++);
  }

  if(typeof(form) == "string")
    if(typeof( eval(form + "Elements")) == "object"){
      for (var j = 0; j < eval(form + "Elements").length && result; j++)
        result = validate_row(j, form);
    }
    else
      for (var i = 0; i < document.forms[form].elements.length && (result = validate_control(form.elements[i])); i++);
  return result;
}

function forms_onload()
{
  var forms = document.forms;
  var i, j, elm, form;
  for(i = 0; i < forms.length; i++)
  {
    form = forms[i];
    if (typeof(form.onLoad) == "function") form.onLoad();
    for (j = 0; j < form.elements.length; j++)
    {
      elm = form.elements[j];
      if (typeof(elm.onLoad) == "function") elm.onLoad();
    }
  }
  return true;
}

//
// If element exist than bind function func to element on event.
// Example: check_and_bind('document.NewRecord1.Delete1','onclick',page_NewRecord1_Delete1_OnClick);
//
function check_and_bind(element,event,func) {
  if (eval(element)) {
    eval(element+'.'+event+'='+func);
  }
}

function createRequestObject() { 
FORM_DATA = new Object(); 
// The Object ("Array") where our data will be stored. 
separator = ','; 
// The token used to separate data from multi-select inputs 
query = '' + this.location; 
qu = query 
// Get the current URL so we can parse out the data. 
// Adding a null-string '' forces an implicit type cast 
// from property to string, for NS2 compatibility. 
query = query.substring((query.indexOf('?')) + 1); 
// Keep everything after the question mark '?'. 
if (query.length < 1) { return false; } // Perhaps we got some bad data? 
keypairs = new Object(); 
numKP = 1; 
// Local vars used to store and keep track of name/value pairs 
// as we parse them back into a usable form. 
while (query.indexOf('&') > -1) { 
keypairs[numKP] = query.substring(0,query.indexOf('&')); 
query = query.substring((query.indexOf('&')) + 1); 
numKP++; 
// Split the query string at each '&', storing the left-hand side 
// of the split in a new keypairs[] holder, and chopping the query 
// so that it gets the value of the right-hand string. 
} 
keypairs[numKP] = query; 
// Store what's left in the query string as the final keypairs[] data. 
for (i in keypairs) { 
keyName = keypairs[i].substring(0,keypairs[i].indexOf('=')); 
// Left of '=' is name. 
keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1); 
// Right of '=' is value. 
while (keyValue.indexOf('+') > -1) { 
keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1); 
// Replace each '+' in data string with a space. 
} 
keyValue = unescape(keyValue); 
// Unescape non-alphanumerics 
if (FORM_DATA[keyName]) { 
FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue; 
// Object already exists, it is probably a multi-select input, 
// and we need to generate a separator-delimited string 
// by appending to what we already have stored. 
} else { 
FORM_DATA[keyName] = keyValue; 
// Normal case: name gets value. 
} 
} 
return FORM_DATA; 
} 
FORM_DATA = createRequestObject(); 
// This is the array/object containing the GET data. 
// Retrieve information with 'FORM_DATA [ key ] = value'. 

//End JS Functions
//JS DatePicker @0-D72D8EC5

// Date formatting functions begin ---------------------------------------------------


var listMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var listShortMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var firstWeekDay = "Sun";
var listWeekdays = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var listShortWeekdays = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

var DateMasks = new Array();
	DateMasks["d"] = 0;
	DateMasks["dd"] = 2;
	DateMasks["m"] = 0;
	DateMasks["mm"] = 2;
	DateMasks["mmm"] = 3;
	DateMasks["mmmm"] = 0;
	DateMasks["yy"] = 2;
	DateMasks["yyyy"] = 4;
	DateMasks["h"] = 0;
	DateMasks["hh"] = 2;
	DateMasks["H"] = 0;
	DateMasks["HH"] = 2;
	DateMasks["n"] = 0;
	DateMasks["nn"] = 2;
	DateMasks["s"] = 0;
	DateMasks["ss"] = 2;
	DateMasks["am/pm"] = 2;
	DateMasks["AM/PM"] = 2;
	DateMasks["A/P"] = 1;
	DateMasks["a/p"] = 1;
	DateMasks["w"] = 0;
	DateMasks["q"] = 0;
	DateMasks["S"] = 0;

function isInArray(strValue, arrArray)
{
  var intResult = -1;
  for ( var j = 0; j < arrArray.length && (strValue != arrArray[j]); j++ );
  if ( j != arrArray.length )
    intResult = j;    
  return intResult;
}

function parseDateFormat(strMask)
{
  var UNDEF;
  var arrResult = new Array();             
  if (strMask == "" || typeof(strMask) == "undefined")
    return arrResult;
  var arrMaskTokens = new Array(
	"d", "w", "m", "q", "y", "h", "H", "n", "s", 
	"dd", "ww", "mm", "yy", "hh", "HH", "nn", "ss", "S",
	"ddd", "mmm", "A/P", "a/p", "dddd", "mmmm", 
	"yyyy", "AM/PM", "am/pm", "LongDate", "LongTime", 
	"ShortDate", "ShortTime", "GeneralDate");
  var arrMaskTokensFirstLetters = new Array("d", "w", "m",
	"q", "y", "h", "H", "n", "s", "A", "a", "L", "S", "G");
  var strMaskLength = strMask.length;
  var i = 0, intMaskPosition = 0;
  var arrMask = new Array();
  var strToken = "";
  while (i < strMaskLength)
  {
	if (strMask.charAt(i) == "\\")
	{
	  strToken += strMask.charAt(++i);
	  i ++;
	}
	else if (strMask.charAt(i) == "'")
	{
	  i ++;
	  while ((i < strMask.length) && (strMask.charAt(i) != "'"))
		strToken += strMask.charAt(i++);
	  i ++;
	}
	else
	{
	  var j = isInArray(strMask.charAt(i), arrMaskTokensFirstLetters);
	  if ( j != -1 )
	  {
		var k;
		for (k = (arrMaskTokens.length - 1); k >= 0 && 
		  strMask.slice(i, i + arrMaskTokens[k].length) != arrMaskTokens[k]; k--);
		if (k != -1)
		{
		  if (strToken.length > 0)
		  {
			if ( isInArray(strToken, arrMaskTokens) == -1)
			  arrMask[intMaskPosition ++] = strToken;
			else
			  arrMask[intMaskPosition ++] = "\\" + strToken;
			strToken = "";
		  }
		  arrMask[intMaskPosition ++] = arrMaskTokens[k];
		  i += arrMaskTokens[k].length;
		}
		else
		{
		  strToken = strMask.charAt(i);
		  i ++;
		}
	  }
	  else
	  {
		strToken += strMask.charAt(i);
		i ++;
	  }
	}
  }
  if (strToken.length > 0)
  {
	if ( isInArray(strToken, arrMaskTokens) == -1)
	  arrMask[intMaskPosition ++] = strToken;
	else
	  arrMask[intMaskPosition ++] = "\\" + strToken;
	strToken = "";
  }
  arrResult = arrMask;
  return arrResult;
}

function getDayOfYear(year, month, day)
{
	var firstDay = new Date(year, 0, 1);
	var date = new Date(year, month, day);
	return (date-firstDay)/(1000*60*60*24);
}

function get12Hour(hoursNumber)
{
  if (hoursNumber == 0)
    hoursNumber = 12;
  else if (hoursNumber > 12)
    hoursNumber = hoursNumber - 12;
  return hoursNumber;
}

function addZero(value, resultLength)
{
  var countZero = resultLength - String(value).length;
  var result = String(value);
  for (var i=0; i<countZero; i++)
    result = "0" + result;
  return result;
}

function getAMPM(HoursNumber, AnteMeridiem, PostMeridiem)
{
  if (HoursNumber >= 0 && HoursNumber < 12)
    return AnteMeridiem;
  else
    return PostMeridiem;
}

function formatDate(dateToFormat, parsedFormat)
{
	var resultArray = new Array(parsedFormat.length);
	for (var i=0; i<parsedFormat.length; i++)
	{
		switch (parsedFormat[i]) 
		{
			case "d": 
				resultArray[i] = dateToFormat.getDate(); 
				break;
			case "w":
				resultArray[i] = dateToFormat.getDay()+1;
				break;
			case "m": 
				resultArray[i] = dateToFormat.getMonth()+1;
				break;
			case "q": 
				resultArray[i] = Math.floor((dateToFormat.getMonth()+4)/4);
				break;
			case "y": 
				resultArray[i] = getDayOfYear(dateToFormat.getFullYear(), dateToFormat.getMonth(), dateToFormat.getDate());
				break;
			case "h": 
				resultArray[i] = "";//get12Hour(dateToFormat.getHours());
				break;
			case "H": 
				resultArray[i] = "";//dateToFormat.getHours();
				break;
			case "n": 
				resultArray[i] = "";//dateToFormat.getMinutes();
				break;
			case "s": 
				resultArray[i] = "";//dateToFormat.getSeconds();
				break;
			case "dd": 
				resultArray[i] = addZero(dateToFormat.getDate(), 2);
				break;
			case "ww": 
				resultArray[i] = Math.floor(getDayOfYear(dateToFormat.getFullYear(), dateToFormat.getMonth(), dateToFormat.getDate())/7)+1;
				break;
			case "mm": 
				resultArray[i] = addZero(dateToFormat.getMonth()+1, 2);
				break;
			case "yy": 
				resultArray[i] = String(dateToFormat.getFullYear()).substr(2);
				break;
			case "hh": 
				resultArray[i] = "";//addZero(get12Hour(dateToFormat.getHours()), 2);
				break;
			case "HH": 
				resultArray[i] = addZero(dateToFormat.getHours(), 2);
				break;
			case "nn": 
				resultArray[i] = addZero(dateToFormat.getMinutes(), 2);
				break;
			case "ss": 
				resultArray[i] = addZero(dateToFormat.getSeconds(), 2);
				break;
			case "S": 
				resultArray[i] = "";//"000";
				break;
			case "ddd": 
				resultArray[i] = listShortWeekdays[dateToFormat.getDay()];
				break;
			case "mmm": 
				resultArray[i] = listShortMonths[dateToFormat.getMonth()];
				break;
			case "A/P": 
				resultArray[i] = "";//getAMPM(dateToFormat.getHours(), "A", "P");
				break;
			case "a/p": 
				resultArray[i] = "";//getAMPM(dateToFormat.getHours(), "a", "p");
				break;
			case "dddd": 
				resultArray[i] = listWeekdays[dateToFormat.getDay()];
				break;
			case "mmmm": 
				resultArray[i] = listMonths[dateToFormat.getMonth()];
				break;
			case "yyyy": 
				resultArray[i] = dateToFormat.getFullYear();
				break;
			case "AM/PM": 
				resultArray[i] = getAMPM(dateToFormat.getHours(), "AM", "PM");
				break;
			case "am/pm": 
				resultArray[i] = "";//getAMPM(dateToFormat.getHours(), "am", "pm");
				break;
			case ":": 
				resultArray[i] = ":";
				break;
			case "LongDate": 
				resultArray[i] = formatDate(dateToFormat, parseDateFormat("dddd, mmmm dd, yyyy"));
				break;
			case "LongTime": 
				resultArray[i] = "";//formatDate(dateToFormat, parseDateFormat("h:nn:ss AM/PM"));
				break;
			case "ShortDate": 
				resultArray[i] = formatDate(dateToFormat, parseDateFormat("m/d/yy"));
				break;
			case "ShortTime": 
				resultArray[i] = "";//formatDate(dateToFormat, parseDateFormat("H:nn"));
				break;
			case "GeneralDate": 
				resultArray[i] = formatDate(dateToFormat, parseDateFormat("m/d/yy hh:nn AM/PM"));
				break;
			default:
			    if (String(parsedFormat[i]).charAt(0)=="\\")
					resultArray[i] = String(parsedFormat[i]).substr(0);
				else
					resultArray[i] = parsedFormat[i];
		}
	}

    return resultArray.join("");
}

function parseDate(dateToParse, parsedMask)
{
	var resultDate, resultDateArray = new Array(8);
	var MaskPart, MaskLength, TokenLength;
	var IsError;
	var DatePosition, MaskPosition;
	var Delimiter, BeginDelimiter;
	var MonthNumber, MonthName;
	var DatePart;

	var IS_DATE_POS, YEAR_POS, MONTH_POS, DAY_POS, IS_TIME_POS, HOUR_POS, MINUTE_POS, SECOND_POS;

	IS_DATE_POS = 0;	YEAR_POS = 1;	MONTH_POS = 2;	DAY_POS = 3;
	IS_TIME_POS = 4;	HOUR_POS = 5;	MINUTE_POS = 6;	SECOND_POS = 7;

	if (!parsedMask)
	{
		resultDate = null;
	}
	else if (parsedMask[0] == "GeneralDate" && String(dateToParse)!="")
		resultDate = parseDate(dateToParse, parseDateFormat("m/d/yy hh:nn AM/PM"));
	else if (parsedMask[0] == "LongDate" && String(dateToParse)!="")
		resultDate = parseDate(dateToParse, parseDateFormat("dddd, mmmm dd, yyyy"));
	else if (parsedMask[0] == "ShortDate" && String(dateToParse)!="")
		resultDate = parseDate(dateToParse, parseDateFormat("m/d/yy"));
	else if (parsedMask[0] == "LongTime" && String(dateToParse)!="")
		resultDate = parseDate(dateToParse, parseDateFormat("h:nn:ss AM/PM"));
	else if (parsedMask[0] == "ShortTime" && String(dateToParse)!="")
		resultDate = parseDate(dateToParse, parseDateFormat("H:nn"));
	else if (String(dateToParse) == "") resultDate = null;
	else
	{
		DatePosition = 0;
		MaskPosition = 0;
		MaskLength = parsedMask.length;
		IsError = false;

		// Default date
		resultDateArray[IS_DATE_POS] = false;
		resultDateArray[IS_TIME_POS] = false;
		resultDateArray[YEAR_POS] = 0;	resultDateArray[MONTH_POS] = 12;	resultDateArray[DAY_POS] = 1;
		resultDateArray[HOUR_POS] = 0;	resultDateArray[MINUTE_POS] = 0;	resultDateArray[SECOND_POS] = 0;

		while ((MaskPosition < MaskLength) && !IsError)
		{
			MaskPart = parsedMask[MaskPosition];
			if (DateMasks[MaskPart] != null)
			{
				TokenLength = DateMasks[MaskPart];
				if (TokenLength > 0)
				{
					DatePart = String(dateToParse).substr(DatePosition, TokenLength);
					DatePosition = DatePosition + TokenLength;
				}else
				{
					if (MaskPosition < MaskLength)
					{
						Delimiter = parsedMask[MaskPosition + 1];
						BeginDelimiter = dateToParse.indexOf(Delimiter, DatePosition);
						if (BeginDelimiter == -1)
						{
							//alert("ParseDate function: The number doesn't match the mask.");
							return null;
						}else 
						{
							DatePart = String(dateToParse).substr(DatePosition, BeginDelimiter - DatePosition);
							DatePosition = BeginDelimiter;
						}
					}else DatePart = String(dateToParse).substr(DatePosition);
				}
				switch (MaskPart)
				{
					case "d": case "dd":
						resultDateArray[DAY_POS] = Math.floor(DatePart);
						resultDateArray[IS_DATE_POS] = true;
						break;
					case "m": case "mm":
						resultDateArray[MONTH_POS] = Math.floor(DatePart);
						resultDateArray[IS_DATE_POS] = true;
						break;
					case "mmm": case "mmmm":
						MonthNumber = 0;
						MonthName = String(DatePart).toUpperCase();
						if (MaskPart == "mmm") 
							MonthNamesArray = listMonths;
						else
							MonthNamesArray = listShortMonths;
						while (MonthNumber < 11 && String(MonthNamesArray[MonthNumber]).toUpperCase() != MonthName)
						{
							MonthNumber = MonthNumber + 1;
						}
						if (MonthNumber == 11) 
						{
							if (String(MonthNamesArray[11]).toUpperCase() != MonthName) 
							{
								//alert("ParseDate function: The number doesn't match the mask.");
								return null;
							}
						}
						resultDateArray[MONTH_POS] = MonthNumber + 1;
						resultDateArray[IS_DATE_POS] = true;
						break;
					case "yy": 
					        var last2Digits = Math.floor(DatePart);
						var centuryDigits = (last2Digits>=50)?1900:2000;
						resultDateArray[YEAR_POS] = centuryDigits + last2Digits;
						resultDateArray[IS_DATE_POS] = true;
						break;
					case "yyyy":
						resultDateArray[YEAR_POS] = Math.floor(DatePart);
						resultDateArray[IS_DATE_POS] = true;
						break;
					case "h": case "hh":
						if (Math.floor(DatePart) == 12) 
							resultDateArray[HOUR_POS] = 0;
						else 
							resultDateArray[HOUR_POS] = Math.floor(DatePart);
						resultDateArray[IS_TIME_POS] = true;
						break;
					case "H": case "HH":
						resultDateArray[HOUR_POS] = Math.floor(DatePart);
						resultDateArray[IS_TIME_POS] = true;
						break;
					case "n": case "nn":
						resultDateArray[MINUTE_POS] = Math.floor(DatePart);
						resultDateArray[IS_TIME_POS] = true;
						break;
					case "s": case "ss":
						resultDateArray[SECOND_POS] = Math.floor(DatePart);
						resultDateArray[IS_TIME_POS] = true;
						break;
					case "am/pm": case "a/p": case "AM/PM": case "A/P":
						if (String(DatePart).toLowerCase().charAt(0) == "p") 
							resultDateArray[HOUR_POS] = resultDateArray[HOUR_POS] + 12;
						else if (String(DatePart).toLowerCase().charAt(0) == "a") 
							resultDateArray[HOUR_POS] = resultDateArray[HOUR_POS];
						resultDateArray[IS_TIME_POS] = true;
						break;
					case "w": case "q": case "S":
						//Do Nothing
						break;
				}
			}else DatePosition = DatePosition + parsedMask[MaskPosition].length;
			MaskPosition = MaskPosition + 1
		}
		if (resultDateArray[IS_DATE_POS] && resultDateArray[IS_TIME_POS]) 
		{
			resultDate = new Date(resultDateArray[YEAR_POS], resultDateArray[MONTH_POS] - 1, resultDateArray[DAY_POS], resultDateArray[HOUR_POS], resultDateArray[MINUTE_POS], resultDateArray[SECOND_POS]);
		}else if (resultDateArray[IS_DATE_POS])
		{
			resultDate = new Date(resultDateArray[YEAR_POS], resultDateArray[MONTH_POS] - 1, resultDateArray[DAY_POS]);
		}else if (resultDateArray[IS_DATE_POS])
		{
			resultDate = new Date(0, 0, 0, resultDateArray[HOUR_POS], resultDateArray[MINUTE_POS], resultDateArray[SECOND_POS]);
		}
	}
	return resultDate;
}

function checkDateRange(date)
{
	var minDate = new Date(1753, 0, 1);
	var maxDate = new Date(9999, 11, 31);
	if (date < minDate) return minDate;
	if (date > maxDate) return maxDate;
	return date;
}

// Date formatting functions end ---------------------------------------------------

var DatePickerObject = new Object();

var disableEvents = false;

// Determine browser brand
var isNav = false;
var isIE  = false;

// Assume it's either Netscape or MSIE
if (navigator.appName == "Netscape") {
    isNav = true;
}
else {
    isIE = true;
}

// Get currently selected language
selectedLanguage = navigator.language;

// DatePicker functions begin here ---------------------------------------------------

// Set the initial value of the global date field
function setDateField(dateField,control) {

    // Assign the incoming field object to a global variable
    calDateField = dateField;

    // Get the value of the incoming field
    inDate = dateField.value;

    // Set calDate to the date in the incoming field or default to today's date
    setInitialDate(control);

    // The DatePicker frameset documents are created by javascript functions
    calDocTop    = buildTopCalFrame(control);
    calDocBottom = buildBottomCalFrame(control);
}

// Set the initial DatePicker date to today or to the existing value in dateField
function setInitialDate(control) {
   
    // Create a new date object 
    calDate = parseDate(inDate, parseDateFormat(eval(control+'.format')));

    if (calDate) calDate = checkDateRange(calDate);

    // If the incoming date is invalid, use the current date
    if (isNaN(calDate) || !calDate) {

        // Simply create a new date object which defaults to the current date
        calDate = new Date();
    }
    
    eval(control+'.currentDate = new Date(calDate.getFullYear(), calDate.getMonth(), calDate.getDate());');

    // KEEP TRACK OF THE CURRENT DAY VALUE
    calDay  = calDate.getDate();

    // Set day value to 1... to avoid javascript date calculation anomalies
    // (if the month changes to feb and the day is 30, the month would change to march
    //  and the day would change to 2.  setting the day to 1 will prevent that)
    calDate.setDate(1);
}

// Popup a window with the DatePicker in it
function showDatePicker(format, style, form_name, form_control) {

    disableEvents = false;

    var control = 'DatePickerObject';

    DatePickerObject = new Object();
    DatePickerObject.format           = format;
    DatePickerObject.style            = String(style);
    DatePickerObject.control          = String("document."+form_name+"."+form_control);
    DatePickerObject.selectedDate     = new Date();

    // Pre-build portions of the DatePicker when this js library loads into the browser !!!!!!
    buildCalParts(control);

    // Set initial value of the date field and create top and bottom frames
    setDateField(eval(eval(control+'.control')), control);

    // Use the javascript-generated documents (calDocTop, calDocBottom) in the frameset
    calDocFrameset = 
        "<HTML><HEAD><TITLE>Date Picker</TITLE><SCRIPT SRC='DatePicker.js' language='JScript'><"+"/SCRIPT></HEAD>\n" +
        "<FRAMESET ROWS='55,*' FRAMEBORDER='0' FRAMESPACING='0'>\n" +
        "  <FRAME NAME='topCalFrame' SRC='javascript:parent.opener.calDocTop' SCROLLING='no' NORESIZE MARGINHEIGHT='0'>\n" +
        "  <FRAME NAME='bottomCalFrame' SRC='javascript:parent.opener.calDocBottom' SCROLLING='no' NORESIZE MARGINHEIGHT='0'>\n" +
        "</FRAMESET>\n";

    // Display the DatePicker in a new popup window
    if (typeof(eval("top.newWin" + control)) != "object") {
      eval("top.newWin" + control + " = window.open('javascript:parent.opener.calDocFrameset', 'calWin'+control, 'dependent=yes,width=240,height=210,screenX=200,screenY=300,titlebar=yes, center: yes, help: no, resizable: yes, status: no');");
    }
    try{
      eval("top.newWin" + control + ".focus();")
    }catch(e){
      eval("top.newWin" + control + " = window.open('javascript:parent.opener.calDocFrameset', 'calWin'+control, 'dependent=yes,width=240,height=210,screenX=200,screenY=300,titlebar=yes, center: yes, help: no, resizable: yes, status: no');");
    }
}

// Create the top DatePicker frame
function buildTopCalFrame(control) {

    // Create the top frame of the DatePicker
    var calDoc =
        "<HTML>" +
        "<HEAD>" +
        // Stylesheet defines appearance of DatePicker
		"<link rel=\"stylesheet\" type=\"text/css\" href=\""+eval(control+".style")+"\">"+
        "</HEAD>" +
        "<BODY TOPMARGIN='0' LEFTMARGIN='0'>" +
        "<FORM NAME='calControl' onSubmit='return false;'>" +
        "<CENTER>" +
        "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=0>" +
        "<TR><TD COLSPAN=7>" +
        "<CENTER>" +
        getMonthSelect(control) +
        "<INPUT class=\"CalendarControls\" NAME='year' VALUE='" + calDate.getFullYear() + "'TYPE=TEXT SIZE=4 MAXLENGTH=4 onChange='parent.opener.setYear(\""+control+"\")'>" +
        "</CENTER>" +
        "</TD>" +
        "</TR>" +
        "<TR>" +
        "<TD COLSPAN=7>" +
        "<INPUT " +
        "TYPE=BUTTON CLASS=\"CalendarButtons\" NAME='previousYear' VALUE='<<'		onClick=\"parent.opener.setPreviousYear('" + control + "')\"><INPUT " +
        "TYPE=BUTTON CLASS=\"CalendarButtons\" NAME='previousMonth' VALUE=' < '		onClick=\"parent.opener.setPreviousMonth('" + control + "')\"><INPUT " +
        "TYPE=BUTTON CLASS=\"CalendarButtons\" NAME='today' VALUE='Today'			onClick=\"parent.opener.setToday('" + control + "')\"><INPUT " +
        "TYPE=BUTTON CLASS=\"CalendarButtons\" NAME='nextMonth' VALUE=' > '			onClick=\"parent.opener.setNextMonth('" + control + "')\"><INPUT " +
        "TYPE=BUTTON CLASS=\"CalendarButtons\" NAME='nextYear' VALUE='>>'			onClick=\"parent.opener.setNextYear('" + control + "')\">" +
        "</TD>" +
        "</TR>" +
        "</TABLE>" +
        "</CENTER>" +
        "</FORM>" +
        "</BODY>" +
        "</HTML>";

    return calDoc;
}

// Create the bottom DatePicker frame 
function buildBottomCalFrame(control) {       

    // Start DatePicker document
    var calDoc = DatePickerBegin;

    // Get month, and year from global DatePicker date
    month   = calDate.getMonth();
    year    = calDate.getFullYear();


    // Get globally-tracked day value (prevents javascript date anomalies)
    day     = calDay;

    var i   = 0;

    // Determine the number of days in the current month
    var days = getDaysInMonth();

    // If global day value is > than days in month, highlight last day in month
    if (day > days) {
        day = days;
    }

    // Determine what day of the week the DatePicker starts on
    var firstOfMonth = new Date (year, month, 1);

    // Get the day of the week the first day of the month falls on
    var startingPos  = firstOfMonth.getDay() - firstWeekDayIndex;
    days += startingPos;

    // Keep track of the columns, start a new row after every 7 columns
    var columnCount = 0;

    // Make beginning non-date cells blank
    for (i = 0; i < startingPos; i++) {

        calDoc += blankCell;
	columnCount++;
    }

    // Set values for days of the month
    var currentDay = 0;
    var dayType    = "weekday";

    // Date cells contain a number
    for (i = startingPos; i < days; i++) {

	var paddingChar = "&nbsp;";

        // Adjust spacing so that all links have relatively equal widths
        if (i-startingPos+1 < 10) {
            padding = "&nbsp;&nbsp;";
        }
        else {
            padding = "&nbsp;";
        }

        // Get the day currently being written
        currentDay = i-startingPos+1;

        // Set the type of day, the focusDay generally appears as a different color
        var currentDate = eval(control+'.currentDate');
	//if (currentDate) currentDate = checkDateRange(currentDate);
        //if (isNaN(currentDate) || !currentDate) currentDate = new Date();
        if (currentDay == day && month==currentDate.getMonth() && year==currentDate.getFullYear()) {
            dayType = "focusDay";
        }
        else {
            dayType = "weekDay";
        }


		// Add the day to the DatePicker string depending on workday or not. 
        if (columnCount % 7 == 0 || columnCount % 7 == 6 ) {
        calDoc += "<TD align=center class=\"weekend\">" +
                  "<a class=\"" + dayType + "\" href=\"javascript:parent.opener.returnDate(" + 
                  currentDay + ",'" + control + "')\">" + padding + currentDay + paddingChar + "</a></TD>";
        }
		else {
        calDoc += "<TD align=center class=\"workday\">" +
                  "<a class=\"" + dayType + "\" href=\"javascript:parent.opener.returnDate(" + 
                  currentDay + ",'" + control + "')\">" + padding + currentDay + paddingChar + "</a></TD>";
		}
        columnCount++;

        // Start a new row when necessary
        if (columnCount % 7 == 0) {
            calDoc += "</TR><TR>";
        }
    }

    // Make remaining non-date cells blank
    for (i=days; i<42; i++)  {

        calDoc += blankCell;
	columnCount++;

        // Start a new row when necessary
        if (columnCount % 7 == 0) {
            calDoc += "</TR>";
            if (i<41) {
                calDoc += "<TR>";
            }
        }
    }

    // Finish the new DatePicker page
    calDoc += DatePickerEnd;

    // Return the completed DatePicker page
    return calDoc;
}

// Write the monthly DatePicker to the bottom DatePicker frame
function writeDatePicker(control) {

    // Create the new DatePicker for the selected month & year
    calDocBottom = buildBottomCalFrame(control);

    // Write the new DatePicker to the bottom frame
    eval("top.newWin" + control + ".frames['bottomCalFrame'].document.open();");
    eval("top.newWin" + control + ".frames['bottomCalFrame'].document.write(calDocBottom);");
    eval("top.newWin" + control + ".frames['bottomCalFrame'].document.close();");
}

// Set the DatePicker to today's date and display the new DatePicker
function setToday(control) {

    // Set global date to today's date
    calDate = new Date();

    // Set day month and year to today's date
    var month = calDate.getMonth();
    var year  = calDate.getFullYear();

    // Set month in drop-down list
    eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.month.selectedIndex = month;");

    // Set year value
    eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value = year;");

    // Display the new DatePicker
    writeDatePicker(control);
}

// Set the global date to the newly entered year and redraw the DatePicker
function setYear(control) {

    if (disableEvents) return false;

    // Get the new year value
    eval("var year  = top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value;");

    // If it's a four-digit year then change the DatePicker
    if (isFourDigitYear(year,control)) {
        calDate.setFullYear(year);
        if (calDate) calDate = checkDateRange(calDate);
        year = calDate.getFullYear();
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value = year;");
        writeDatePicker(control);
    }
    else {
        // Highlight the year if the year is not four digits in length
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.focus();");
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.select();");
    }
}

// Set the global date to the selected month and redraw the DatePicker
function setCurrentMonth(control) {

    if (disableEvents) return false;

    // Get the newly selected month and change the DatePicker accordingly
    eval("var month = top.newWin" + control + ".frames['topCalFrame'].document.calControl.month.selectedIndex;");

    calDate.setMonth(month);
    if (calDate) calDate = checkDateRange(calDate);
    writeDatePicker(control);
}

// Set the global date to the previous year and redraw the DatePicker
function setPreviousYear(control) {

    eval("var year  = top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value;");

    if (isFourDigitYear(year,control) && year > 1000) {
        year--;
        calDate.setFullYear(year);
        if (calDate) calDate = checkDateRange(calDate);
        year = calDate.getFullYear();
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value = year;");
        writeDatePicker(control);
    }
}

// Set the global date to the previous month and redraw the DatePicker
function setPreviousMonth(control) {

    eval("var year  = top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value;");
    if (isFourDigitYear(year,control)) {
        eval("var month = top.newWin" + control + ".frames['topCalFrame'].document.calControl.month.selectedIndex;");

        // If month is january, set month to december and decrement the year
        if (month == 0) {
            month = 11;
            if (year > 1000) {
                year--;
                calDate.setFullYear(year);
                if (calDate) calDate = checkDateRange(calDate);
                year = calDate.getFullYear();
                eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value = year;");
            }
        }
        else {
            month--;
        }
        calDate.setMonth(month);
        if (calDate) calDate = checkDateRange(calDate);
        month = calDate.getMonth();
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.month.selectedIndex = month;");
        writeDatePicker(control);
    }
}

// Set the global date to the next month and redraw the DatePicker
function setNextMonth(control) {

    eval("var year = top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value;");

    if (isFourDigitYear(year,control)) {
        eval("var month = top.newWin" + control + ".frames['topCalFrame'].document.calControl.month.selectedIndex;");

        // If month is december, set month to january and increment the year
        if (month == 11) {
            month = 0;
            year++;
            calDate.setFullYear(year);
            if (calDate) calDate = checkDateRange(calDate);
            year = calDate.getFullYear();
            eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value = year;");
        }
        else {
            month++;
        }
        calDate.setMonth(month);
        if (calDate) calDate = checkDateRange(calDate);
        month = calDate.getMonth();
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.month.selectedIndex = month;");
        writeDatePicker(control);
    }
}

// Set the global date to the next year and redraw the DatePicker
function setNextYear(control) {

    eval("var year  = top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value;");
    if (isFourDigitYear(year,control)) {
        year++;
        calDate.setFullYear(year);
        if (calDate) calDate = checkDateRange(calDate);
        year = calDate.getFullYear();
        eval("top.newWin" + control + ".frames['topCalFrame'].document.calControl.year.value = year;");
        writeDatePicker(control);
    }
}

// Get number of days in month
function getDaysInMonth()  {

    var days;
    var month = calDate.getMonth()+1;
    var year  = calDate.getFullYear();

    // Return 31 days
    if (month==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12)  {
        days=31;
    }
    // Return 30 days
    else if (month==4 || month==6 || month==9 || month==11) {
        days=30;
    }
    // Return 29 days
    else if (month==2)  {
        if (isLeapYear(year)) {
            days=29;
        }
        // Return 28 days
        else {
            days=28;
        }
    }
    return (days);
}

// Check to see if year is a leap year
function isLeapYear (Year) {

    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
    }
    else {
        return (false);
    }
}

// Ensure that the year is four digits in length
function isFourDigitYear(year,control) {

    if (year.length != 4) {
        eval("top.newWin" + control +".frames['topCalFrame'].document.calControl.year.value = calDate.getFullYear();");
        eval("top.newWin" + control +".frames['topCalFrame'].document.calControl.year.select();");
        eval("top.newWin" + control +".frames['topCalFrame'].document.calControl.year.focus();");
    }
    else {
        return true;
    }
}

// Build the month select list
function getMonthSelect(control) {

    // Determine month to set as default
    var activeMonth = calDate.getMonth();

    // Start html select list element
    monthSelect = "<SELECT class=\"CalendarControls\" NAME='month' onChange='parent.opener.setCurrentMonth(\""+control+"\")'>";

    // Loop through month array
    for (i in listMonths) {
        
        // Show the correct month in the select list
        if (i == activeMonth) {
            monthSelect += "<OPTION SELECTED>" + listMonths[i] + "\n";
        }
        else {
            monthSelect += "<OPTION>" + listMonths[i] + "\n";
        }
    }
    monthSelect += "</SELECT>";

    // Return a string value which contains a select list of all 12 months
    return monthSelect;
}

// Set days of the week depending on language
function createWeekdayList(control) {
    firstWeekDayIndex = 0;
    newWeekdayArray = new Array(7);
    newWeekdayList = new Array(7);
    for (var i=0; i<listShortWeekdays.length; i++)
        if (listShortWeekdays[i]==firstWeekDay) firstWeekDayIndex = i;
    for (var i=firstWeekDayIndex; i<listShortWeekdays.length; i++)
    {
        newWeekdayArray[i-firstWeekDayIndex] = listShortWeekdays[i];
        newWeekdayList[i-firstWeekDayIndex] = listWeekdays[i];
    }
    for (var i=0; i<firstWeekDayIndex; i++)
    {
        newWeekdayArray[7-firstWeekDayIndex-i] = listShortWeekdays[i];
        newWeekdayList[7-firstWeekDayIndex-i] = listWeekdays[i];
    }

    // Start html to hold weekday names in table format
    var weekdays = "<TR>";

    // Loop through weekday array
    for (i in listShortWeekdays) {

        weekdays += "<TH class=\"calendar\" align=\"center\">" + newWeekdayArray[i] + "</TH>";
    }
    weekdays += "</TR>";

    // Return table row of weekday abbreviations to display above the DatePicker
    return weekdays;
}

// Pre-build portions of the DatePicker (for performance reasons)
function buildCalParts(control) {

    // Generate weekday headers for the DatePicker
    weekdays = createWeekdayList(control);

    // Build the blank cell rows
    blankCell = "<TD align=center class=\"workday\">&nbsp;&nbsp;&nbsp;</TD>";

    // Build the top portion of the DatePicker page using css to control some display elements
    DatePickerBegin =
        "<HTML>" +
        "<HEAD>" +
        // Stylesheet defines appearance of DatePicker
		"<link rel=\"stylesheet\" type=\"text/css\" href=\""+eval(control+".style")+"\">"+
        "</HEAD>" +
        "<BODY TOPMARGIN='0' LEFTMARGIN='0'>" + "<CENTER>";

        // Navigator needs a table container to display the table outlines properly
        if (isNav) {
            DatePickerBegin += 
                "<TABLE CELLPADDING=0 CELLSPACING=1 ALIGN=CENTER CLASS=\"Table\"><TR><TD>";
        }

        // Build weekday headings
        DatePickerBegin +=
            "<TABLE CELLPADDING=0 CELLSPACING=1 CLASS=\"Table\">" +
            weekdays +
            "<TR>";


    // Build the bottom portion of the DatePicker page
    DatePickerEnd = "";

        // Navigator needs a table container to display the borders properly
        if (isNav) {
            DatePickerEnd += "</TD></TR></TABLE>";
        }

        // End the table and html document
        DatePickerEnd +=
            "</TABLE>" +
            "</CENTER>" +
            "</BODY>" +
            "</HTML>";
}

// Set field value to the date selected and close the DatePicker window
function returnDate(inDay,control)
{
    disableEvents = true;

    // inDay = the day the user clicked on
    calDate.setDate(inDay);

    if (calDate) calDate = checkDateRange(calDate);

    // Set the date returned to the user
    var dateFormat = eval(control + ".format");

    outDate = formatDate(calDate, parseDateFormat(dateFormat));

    // Set the value of the field that was passed to the DatePicker
    calDateField.value = String(outDate).replace(/\s*$/, "");

    // Give focus back to the date field
    calDateField.focus();

    // Close the DatePicker window
    eval("top.newWin" + control + ".close()");
}

//End JS DatePicker








