// JScript File

function DateTimePicker_init(id, txtYearId, txtMonthId, txtDayId, txtHourId, txtMinuteId, intMode, strDropDownPosition)
{
	var dateTimePicker = document.getElementById(id);
	
	dateTimePicker.txtYear = document.getElementById(txtYearId);
	dateTimePicker.txtMonth = document.getElementById(txtMonthId);
	dateTimePicker.txtDay = document.getElementById(txtDayId);
	dateTimePicker.txtHour = document.getElementById(txtHourId);
	dateTimePicker.txtMinute = document.getElementById(txtMinuteId);
		
	dateTimePicker.mode = intMode;
	dateTimePicker.dropDownPosition = strDropDownPosition; 
	
	switch(dateTimePicker.mode)
	{
		case 0:
			//Date And Time
			initDateFields(dateTimePicker);
			initTimeFields(dateTimePicker);
			break;
				
		case 1:
			//Date Only
			initDateFields(dateTimePicker);
			
			break;
						
		case 2:
			//Time Only
			initTimeFields(dateTimePicker)
			
			break;
	}
	
	//dateTimePicker.prototype.get_value
	dateTimePicker.get_value = function(e)
	{

	    var objDate = new Date();
	    var intYear = objDate.getFullYear();
	    var intMonth = objDate.getMonth();
	    var intDay = objDate.getDate();
	    if(this.txtYear.value!='' && isNumeric(this.txtYear.value)) 
	    {
	        intYear = this.txtYear.value;
	    }
	    if(this.txtMonth.value!='' && isNumeric(this.txtMonth.value)) 
	    {
	        intMonth = this.txtMonth.value-1;
	    }
	    if(this.txtDay.value!='' && isNumeric(this.txtDay.value)) 
	    {
	        intDay = this.txtDay.value;
	    }	    
        return new Date(intYear, intMonth, intDay); 
	    
		
	}

	dateTimePicker.set_value = function(value)
	{
		this.txtYear.value = value.getFullYear().toString();
		this.txtMonth.value = padLeft((value.getMonth()+1).toString(), 2, '0');
		this.txtDay.value = padLeft(value.getDate(), 2, '0');
	}
}

function initDateFields(dateTimePicker)
{
	dateTimePicker.txtYear.dateTimePicker = dateTimePicker;
	dateTimePicker.txtMonth.dateTimePicker = dateTimePicker;
	dateTimePicker.txtDay.dateTimePicker = dateTimePicker;
	dateTimePicker.txtYear.mode = 'year';
	dateTimePicker.txtMonth.mode = 'month';
	dateTimePicker.txtDay.mode = 'day';
	

	dateTimePicker.txtYear.onfocus = function(){selectAllText(this)};
	dateTimePicker.txtMonth.onfocus = function(){selectAllText(this)};
	dateTimePicker.txtDay.onfocus = function(){selectAllText(this)};
	
	dateTimePicker.txtDay.onkeypress = function(){return filterNumeric(this, event)};
	dateTimePicker.txtMonth.onkeypress = function(){return filterNumeric(this, event)};
	dateTimePicker.txtYear.onkeypress = function(){return filterNumeric(this, event)};
	
	dateTimePicker.txtDay.onblur = function(){validatedDateField(this)};
	dateTimePicker.txtMonth.onblur = function(){validatedDateField(this)};
	dateTimePicker.txtYear.onblur = function(){validatedDateField(this)};
}

function initTimeFields(dateTimePicker)
{
	dateTimePicker.txtHour.dateTimePicker = dateTimePicker;
	dateTimePicker.txtMinute.dateTimePicker = dateTimePicker;
	dateTimePicker.txtHour.mode = 'hour';
	dateTimePicker.txtMinute.mode = 'minute';
	
	dateTimePicker.txtHour.onfocus = function(){selectAllText(this)};
	dateTimePicker.txtMinute.onfocus = function(){selectAllText(this)};
	
	dateTimePicker.txtHour.onkeypress = function(){return filterNumeric(this, event)};
	dateTimePicker.txtMinute.onkeypress = function(){return filterNumeric(this, event)};
	
	dateTimePicker.txtHour.onblur = function(){validatedDateField(this)};
	dateTimePicker.txtMinute.onblur = function(){validatedDateField(this)};
}


function filterNumeric(that, e)
{
	try
	{
		var dateTimePicker = that.dateTimePicker;
		var intKeyCode = (e.which?e.which:e.keyCode);
		var filterValues = '0123456789'; 

		 if((intKeyCode==null) 
			 || (intKeyCode==0) 
			 || (intKeyCode==8) 
			 || (intKeyCode==9) 
			 || (intKeyCode==13) 
			 || (intKeyCode==27))
		{		
			return true; 
		}
		
	   // Get the Pressed Character 
		var Char = String.fromCharCode(intKeyCode); 

		if((filterValues.indexOf(Char) > -1))
		{
			return true; 
		}		

		if(that.value.length == that.maxlength)
		{
			switch(that.mode)
			{
				case 'year':
					if (that.dateTimePicker.mode == 0)
					{
						that.dateTimePicker.txtHour.focus();
					}					
					break;
				case 'month':
					that.dateTimePicker.txtYear.focus();
					break;
				case 'day':
					that.dateTimePicker.txtMonth.focus();
					break;
				case 'hour':
					that.dateTimePicker.txtMinute.focus();
					break;
				case 'minute':
					;
					break;
			}		
		}
	}
	catch(e)
	{
		raiseMessage('error', e.message, that.id);
	}
        
    return false;
}

function validatedDateField(that)
{
	if(that.value == '')
	{
		return;
	}
	
	switch(that.mode)
	{
		case 'year':
			that.value =  toYear(that.value);
			
			try
			{				
				var value = new Date(that.value, that.dateTimePicker.txtMonth.value-1, that.dateTimePicker.txtDay.value); 
				that.value = value.getFullYear().toString();
				that.dateTimePicker.txtMonth.value = padLeft((value.getMonth()+1).toString(), 2, '0');
				that.dateTimePicker.txtDay.value = padLeft(value.getDate(), 2, '0');	
			}
			catch(e)
			{
				raiseMessage('stoperror', e.toString(), that.id);
			}
			
			break;
		case 'month':
			that.value = padLeft(toNumericValueRange(that.value, 1, 12), 2, '0');
			break;
		case 'day':
			that.value =  padLeft(toNumericValueRange(that.value, 1, 31), 2, '0');
			break;
		case 'hour':
			that.value =  padLeft(toNumericValueRange(that.value, 0, 23), 2, '0');
			break;
		case 'minute':
			that.value =  padLeft(toNumericValueRange(that.value, 0, 59), 2, '0');
			break;
	}

}

function toYear(value)
{
	if (value.length == 0)
	{
		value = new Date().getFullYear();
	}
	else if  (value.length == 1)
	{
		value = new Date().getFullYear().toString().substr(0,3) + value;
	}
	else if  (value.length == 2)
	{
		value = new Date().getFullYear().toString().substr(0,2) + value;
	}
	else if  (value.length == 3)
	{
		value = new Date().getFullYear().toString().substr(0,1) + value;
	}

	return value;
}

function toNumericValueRange(value, minimumValue, maximumValue)
{
	if((isNaN(value))||(value==''))
	{
		return minimumValue;
	}
	else if(value<minimumValue)
	{
		return minimumValue;
	}
	else if(value>maximumValue)
	{
		return maximumValue;
	}
	else
	{	
		return value;
	}
}




var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
 
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";        // common values would be "/" or "."
var defaultDateFormat = "dmy"    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldName, displayPosition, displayBelowThisObject, dtFormat, dtSep)
{
	//var targetDateField = document.getElementsByName(dateFieldName)[0];
	var targetDateField = document.getElementById(dateFieldName);
	//    closeLastDropdown();
	
	
	// if we weren't told what node to display the datepicker beneath, just display it
	// beneath the date field we're updating
	if (!displayBelowThisObject)
	{
		displayBelowThisObject = targetDateField;
	}
 
	// if a date separator character was given, update the dateSeparator variable
	if (dtSep)
		dateSeparator = dtSep;
	else
		dateSeparator = defaultDateSeparator;
 
	// if a date format was given, update the dateFormat variable
	if (dtFormat)
		dateFormat = dtFormat;
	else
		dateFormat = defaultDateFormat;
    
	if (typeof(displayPosition) == 'undefined')
	{
		displayPosition = 'Below';
	}
 
	var x = displayBelowThisObject.offsetLeft;
	var y = displayBelowThisObject.offsetTop;
 
	//handle displayPosition  
	switch(displayPosition.toLowerCase())
	{
		case 'below':
			y = y + displayBelowThisObject.offsetHeight ; 
			break;
		case 'above':
			break;
		case 'left':
			break;
		case 'right':
			x = x + displayBelowThisObject.offsetWidth + 20;
			break;
	}
  
	// deal with elements inside tables and such
	var parent = displayBelowThisObject;
	while (parent.offsetParent) 
	{
		parent = parent.offsetParent;
		x += parent.offsetLeft;
		y += parent.offsetTop ;
	}
	drawDatePicker(targetDateField, x, y, displayPosition);
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.
This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y, displayPosition)
{
	var targetDateField1 = document.getElementById(targetDateField.id);
	var dt = targetDateField1.get_value();  
	var pickerDivId = datePickerDivID;

	// the datepicker table will be drawn inside of a <div> with an ID defined by the
	// global datePickerDivID variable. If such a div doesn't yet exist on the HTML
	// document we're working with, add one.
	if (!document.getElementById(datePickerDivID))
	{
		// don't use innerHTML to update the body, because it can cause global variables
		// that are currently pointing to objects on the page to have bad references
		//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
		var newNode = document.createElement("div");
		newNode.setAttribute("id", pickerDivId);
		newNode.setAttribute("class", "dpDiv");
		newNode.setAttribute("style", "visibility: hidden;");
		newNode.setAttribute("mouseOnOut", "restoreBlur(e);");
		document.body.appendChild(newNode);
	}

	// move the datepicker div to the proper x,y coordinate and toggle the visibility
	var pickerDiv = document.getElementById(pickerDivId);
	pickerDiv.style.position = "absolute";
	pickerDiv.style.left = x + "px";
	pickerDiv.style.top = y + "px";
	pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
	pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
	pickerDiv.style.zIndex = 10000;

	// draw the datepicker table
	refreshDatePicker(targetDateField.id, targetDateField.name, displayPosition, x, y, dt.getFullYear(), dt.getMonth(), dt.getDate());

}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(targetDateFieldId, dateFieldName, displayPosition, x, y, year, month, day)
{
	var pickerDivId = datePickerDivID;
	var pickerDiv = document.getElementById(pickerDivId);
	// if no arguments are passed, use today's date; otherwise, month and year
	// are required (if a day is passed, it will be highlighted later)
	var thisDay = new Date();

	if ((month >= 0) && (year > 0)) 
	{
		thisDay = new Date(year, month, 1);
	} 
	else 
	{
		day = thisDay.getDate();
		thisDay.setDate(1);
	}

	// the calendar will be drawn as a table
	// you can customize the table elements with a global CSS style sheet,
	// or by hardcoding style and formatting elements below
	var crlf = "\r\n";
	var TABLE = "<table cols=7 class='dpTable'>" + crlf;
	var xTABLE = "</table>" + crlf;
	var TR = "<tr class='dpTR'>";
	var TR_title = "<tr class='dpTitleTR'>";
	var TR_days = "<tr class='dpDayTR'>";
	var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
	var xTR = "</tr>" + crlf;
	var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
	var TD_title = "<td colspan=5 class='dpTitleTD'>";
	var TD_buttons = "<td class='dpButtonTD'>";
	var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
	var TD_days = "<td class='dpDayTD'>";
	var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
	var xTD = "</td>" + crlf;
	var DIV_title = "<div class='dpTitleText'>";
	var DIV_selected = "<div class='dpDayHighlight'>";
	var xDIV = "</div>";
	var weeksShown = 0;//debugger;

	// start generating the code for the calendar table
	var html = TABLE;

	// this is the title bar, which displays the month and the buttons to
	// go back to a previous month or forward to the next month
	html += TR_title;
	html += TD_buttons + getButtonCode(targetDateFieldId, dateFieldName, displayPosition, x, y, thisDay, -1, "&lt;") + xTD;
	html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
	html += TD_buttons + getButtonCode(targetDateFieldId, dateFieldName, displayPosition, x, y, thisDay, 1, "&gt;") + xTD;
	html += xTR;

	// this is the row that indicates which day of the week we're on
	html += TR_days;
	for(i = 0; i < dayArrayShort.length; i++)
	html += TD_days + dayArrayShort[i] + xTD;
	html += xTR;

	// now we'll start populating the table with days of the month
	html += TR;

	// first, the leading blanks
	for (i = 0; i < thisDay.getDay(); i++)
	html += TD + "&nbsp;" + xTD;

	// now, the days of the month
	do 
	{
		dayNum = thisDay.getDate();
		TD_onclick = " onclick=\"updateDateField('" + targetDateFieldId + "', '" + getDateString(thisDay) + "');\">";

		if (dayNum == day)
			html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
		else
			html += TD + TD_onclick + dayNum + xTD;

		// if this is a Saturday, start a new row
		if (thisDay.getDay() == 6)
		{
			html += xTR + TR;
			weeksShown++;
		}

		// increment the day
		thisDay.setDate(thisDay.getDate() + 1);
	} while (thisDay.getDate() > 1)

	// fill in any trailing blanks
	if (thisDay.getDay() > 0) 
	{
		for (i = 6; i > thisDay.getDay(); i--)
			html += TD + "&nbsp;" + i.toString() + xTD;
	}
	weeksShown++;
	html += xTR;

	// if displaying above and only a 4 week month then fill in an extra row to prevent the selection jumping.
	if((displayPosition.toLowerCase() == 'above')&&(weeksShown != 6))
	{
		html += TR;

		for (i = 0; i < 7; i++)
			html += TD + "&nbsp;" + xTD;

		html += xTR;          
	}



	// add a button to allow the user to easily return to today, or close the calendar
	var today = new Date();
	var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
	html += TR_todaybutton + TD_todaybutton;
	html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + targetDateFieldId + "\",\"" + dateFieldName + "\",\"" + displayPosition + "\"," + x + "," + y + ");'>this month</button> ";
	html += "<button class='dpTodayButton' onClick='updateDateField(\"" + targetDateFieldId + "\");'>close</button>";
	html += xTD + xTR;

	// and finally, close the table
	html += xTABLE;

	pickerDiv.innerHTML = html;  

	//handle displayPosition  
	switch(displayPosition.toLowerCase())
	{
		case 'below':
			break;
		case 'above':
			pickerDiv.style.top = (y - pickerDiv.offsetHeight) + "px";
			break;
		case 'left':
			pickerDiv.style.left = (x - pickerDiv.offsetWidth) + "px";
			break;
		case 'right':
			//pickerDiv.style.left = (x + pickerDiv.offsetWidth) + "px";
			break;
	}

	// add an "iFrame shim" to allow the datepicker to display above selection lists
	adjustiFrame(pickerDiv);
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(targetDateFieldId, dateFieldName, displayPosition, x, y, dateVal, adjust, label)
{
	var newMonth = (dateVal.getMonth () + adjust) % 12;
	var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
	
	if (newMonth < 0)
	{
		newMonth += 12;
		newYear += -1;
	}

	return "<button class='dpButton' onClick='refreshDatePicker(\"" + targetDateFieldId + "\",\"" + dateFieldName + "\",\"" + displayPosition + "\", " + x + ", " + y + ", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
 
  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
 
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      if(y.toString().length == 2)
      {
        y = getFullYear(y);
      }
      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
 
  return dateVal;
}


function splitDateString(dateString)
{
	var dArray;
	if (dateString.indexOf("/") >= 0)
		dArray = dateString.split("/");
	else if (dateString.indexOf(".") >= 0)
		dArray = dateString.split(".");
	else if (dateString.indexOf("-") >= 0)
		dArray = dateString.split("-");
	else if (dateString.indexOf("\\") >= 0)
		dArray = dateString.split("\\");
	else if (dateString.indexOf(" ") >= 0)
		dArray = dateString.split(" ");
	else if ((dateString.length == 6)||(dateString.length == 8))
		dArray = new Array(dateString.substring(0,2) ,dateString.substring(2,2) , dateString.substring(4));
	else
		dArray = false;

	return dArray;
}

function updateDateField(dateFieldId, value)
{
	var targetDateField = document.getElementById(dateFieldId);
	var pickerDivId = datePickerDivID;
	
	if (value)
		targetDateField.set_value(getFieldDate(value));

	var pickerDiv = document.getElementById(pickerDivId);
	pickerDiv.style.visibility = "hidden";
	pickerDiv.style.display = "none";

	adjustiFrame(pickerDiv);
	targetDateField.txtYear.select();
	targetDateField.txtYear.focus();
 
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
  
  // put a try/catch block around the whole thing, just in case
  try 
  {
    if (!document.getElementById(iFrameDivID)) 
    {
      // don't use innerHTML to update the body, because it can cause global variables
      // that are currently pointing to objects on the page to have bad references
      //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
      var newNode = document.createElement("iFrame");
      newNode.setAttribute("id", iFrameDivID);
      newNode.setAttribute("src", "javascript:'';");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      document.body.appendChild(newNode);
    }
    
    if (!pickerDiv)
      pickerDiv = document.getElementById(datePickerDivID);
    if (!iFrameDiv)
      iFrameDiv = document.getElementById(iFrameDivID);
    
    try 
    {
      iFrameDiv.style.position = "absolute";
      iFrameDiv.style.width = pickerDiv.offsetWidth;
      iFrameDiv.style.height = pickerDiv.offsetHeight ;
      iFrameDiv.style.top = pickerDiv.style.top;
      iFrameDiv.style.left = pickerDiv.style.left;
      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } 
    catch(e) 
    {
    }
 
  } 
  catch (ee) 
  {
  }
 
}


// 
var bValidateOverride = false;
var bValidateItemOverride = false;


function CheckPage()
{
    if(typeof(Validate) != 'undefined')
    {
        return Validate.Check();
    }
    else
    {
        return true;
    }
}

function Validator()
{
    //debugger;
    //debug_print('Running Validator()');
    var items = new Array();
    this.count=items.length;
    this.Add = Add;
    this.View = View;
    this.Check = Check;
    this.CheckThis = CheckThis;
    
    function Add(control, conditions, messages, runOnCheckAll, runOnBlur, runOnClick, addToBlur, addToMouseOut)
    {
        if(control != null)
        {
            //debugger;
            //debug_print('Running Validator().Add');
            items[items.length] = new ValidatorItem(control, conditions, messages, runOnCheckAll, runOnBlur, runOnClick);
            
            if (addToMouseOut == true)
            {
                control.onmouseout = function(){Validate.CheckThis(this, event)};
                //AddHandler(control.onClick, 'CheckThis(this)');
            }
            if (addToBlur == true)
            {
                control.onblur = function(){Validate.CheckThis(this, event)};
                //AddHandler(control.onClick, 'CheckThis(this)');
            }
        }
        
    }
    
    
    function ValidatorItem(control, conditions, messages, runOnCheckAll, runOnBlur, runOnClick)
    {
        this.control = control;
        this.rules = new Array();
        
        for(var ruleIndex = 0; ruleIndex < conditions.length; ruleIndex++)
        {
            this.rules[this.rules.length] = new ValidatorRule(conditions[ruleIndex], messages[ruleIndex], runOnCheckAll[ruleIndex], runOnBlur[ruleIndex], runOnClick[ruleIndex]);
        }
        
    }

    function ValidatorRule(condition, message, runOnCheckAll, runOnBlur, runOnClick)
    {
        this.condition = condition;
        this.message = message;
        this.runOnCheckAll = runOnCheckAll;
        this.runOnBlur = runOnBlur;
        this.runOnClick = runOnClick;
    }
    
    function View()
    {
        //debug_print('Running Validator().View');
        for(var iLoop=0;iLoop < items.length; iLoop++)
        {
            //debug_print (items[iLoop][0].id);
        }        
    }
    
    function Check()
    {    
        return CheckThis(null, null);
    }

    function CheckThis(checkcontrol, e)
    {
        //debugger;
	    //Richard: TODO: please add onblur checking when doing a submit (checking all controls)...
        var focusId;
        var eventType  = '';
        if((e)&&(e != null))
        {
			eventType = e.type;
		}
        //Clear the alternativeFocusId
        alternativeFocusId = null;
        if (bValidateOverride)
        {
            //debug_print('Validation override in place. Skipping validation');
            return true;
        }
        else if((bValidateItemOverride) && (checkcontrol != null))
        {
            return false;
        }
        else if ((messageArea)&&(messageArea.messageRaised))
        {
            return false;
        }
        
        for(var iLoop=0;iLoop < items.length; iLoop++)
        {
            //debug_print('Validating : items'+[iLoop]);
            if(items[iLoop].control != null)
            {
                if ((checkcontrol == null)||(items[iLoop].control.id==checkcontrol.id))
                {
                    //debug_print('Validating : '+items[iLoop][0].id);
                    for(var iCondition=0;iCondition < items[iLoop].rules.length; iCondition++)
                    {
                         //Very important. 'that' is the name used to identify the object being tested
                        //'that' must be passed in as part of the test so we can use isNAN(that.value) and such like.
                        var that = items[iLoop].control;
                        if((isDisabled(that)==false)&&(isReadOnly(that)==false))
                        {
                            //Check to see if this is an onblur event.
                            //e.g. do not eval an on blur event on checking all controls.
                            if((checkcontrol != null)||(items[iLoop].rules[iCondition].runOnCheckAll == 'true'))
                            {                                
								if(eval(items[iLoop].rules[iCondition].condition))
								{
									//debug_print('Passed : '+items[iLoop][1][iCondition]);
								}
								else
								{
									//Only display a message if one has been defined.
									if(typeof(items[iLoop].rules[iCondition].message) != 'undefined')
									{                        
										if(alternativeFocusId != null)
										{
											focusId = alternativeFocusId;
										}
										else
										{
											focusId = items[iLoop].control.id;
										}
										var msgShown = raiseMessage('validation',items[iLoop].rules[iCondition].message, focusId);
										//debugger;
										return false;
										break;
									}
								}								
                            }
                        }
                    }
                }
            }
            else
            {
                //debug_print('Invalid validation object : items['+iLoop+']');
            }
        }  
        //debugger;
        return true;
    }
    
    function isDisabled(that)
    {
        //Returns true if the control is disabled.
        //else returns false (e.g. if control is not disabled or control does not have a disabled property).
        if(typeof(that.disabled) == 'boolean')
        {
            return that.disabled;
        }
        else
        {
            return false;
        }
    }
    
	function isReadOnly(that)
    {
        //Returns true if the control is readOnly.
        //else returns false (e.g. if control is not readOnly or control does not have a readOnly property).
        if(typeof(that.readOnly) == 'boolean')
        {
            return that.readOnly;
        }
        else
        {
            return false;
        }
    }
}


/********************************************************************************\
 Functions
\********************************************************************************/

function isMatch(strValue, strExpression)
{
    var rgMatch = new RegExp(strExpression);
    return strValue.match(rgMatch)
}

function upperCase(that)
{
    that.value = that.value.toUpperCase();
    return true;
}

function lowerCase(that)
{
    that.value = that.value.toLowerCase();
    return true;
}

function normalCaseFirst(that)
{
    that.value = toNormalCase(that.value,' ', false);
    return true;
}

function normalCaseAll(that)
{
    that.value = toNormalCase(that.value,' ', true);
    return true;
}

function compareDate(strdate_1, strdate_2, strmode)
{
    //debugger;
    var ret_val = false;
    if(
        typeof(strdate_1) != 'undefined' && 
        typeof(strdate_2) != 'undefined' &&
        strdate_1 != '' &&
        strdate_2 != ''
    )
    {
        //This should really check for valid dates either before or after we have created the date objects.
        var new_date_1=toDate(strdate_1);
	    var new_date_2=toDate(strdate_2);
        switch (strmode)
        {
            case "greater":
                ret_val = new_date_1 > new_date_2;
                break;
            case "less":
                ret_val = new_date_1 < new_date_2;
                break;
            case "equal":
                ret_val = new_date_1 == new_date_2;
                break;
            case "equgreater":
                ret_val = new_date_1 >= new_date_2;
                break;
            case "equless":
                ret_val = new_date_1 <= new_date_2;
                break;
            default:
                //No mode so return false.
                ret_val = false;
                break;
        }
    }
    else
    {
        return true;
    }
    return ret_val;
}

function toNormalCase(this_string, word_seperator, all_words)
{
/*
*toNormalCase sets the first letter of one or more words to capital
*
* this_string    - string ('')     - The string to be capitalised
* word_seperator - string (' ')    - Character between words 
* all_words      - boolean (false) - False capitalises first word only, true capitalises all words
*/
    //Init vars
    var first_letter = new String();
    var other_letters = new String();
    var temp_string = new String();
    //check parameters
    if (word_seperator==null)
    {
        word_seperator = ' ';
    }
    if (all_words!=true)
    {
        all_words=false
    }
    this_string = this_string.toLowerCase();
    //All words or just the first?
    if (all_words)
    {
        //Capitalise all words
        var temp_words = new Array();
        temp_words = this_string.split(word_seperator);
        var word_num = 0;
        //Iterate through words
        for (word_num = 0; word_num<temp_words.length; word_num++)
        {
            first_letter = temp_words[word_num].charAt(0);
            other_letters = temp_words[word_num].substring(1,temp_words[word_num].length);
            first_letter = first_letter.toUpperCase();
            if (temp_string=='')
            {
                temp_string += first_letter + other_letters
            }
            else
            {
                temp_string += word_seperator + first_letter + other_letters
            }
        }
    }
    else
    {
        //Capitalise first word only
        first_letter = this_string.charAt(0);
        other_letters = this_string.substring(1,this_string.length);
        first_letter = first_letter.toUpperCase();
        temp_string = first_letter + other_letters
    }
    return (temp_string);
}

function isMaxLength(that, maxLength)
{
    if (that.value.length > maxLength)
        that.value = that.value.substring(0, maxLength)
}

function isValidDecimalPercent(that, min, max)
{
    /*
    Returns a boolean based on whether the value passed in is a number and is between the min and max values.
        true - if all criteria were met
        false - if any of the criteria were not met. 
    */
    var return_value = true;
    if (isNaN(that))
    {
		return_value = false;
    }
    else
    {
        if (that > max || that < min)
        {
            return_value = false;
        }
        if (that.indexOf('.')>-1)
        {
            var this_value = that.toString();
            var value_array = new Array();
            value_array = this_value.split('.');
            //debug_print(value_array.length);
            if (value_array.length > 0)
            {
                var decimal_part = value_array[1].toString();
                //debug_print(decimal_part);
                if (decimal_part.length > 2)
                {
                    return_value = false;
                }
            }
        }
    }
    return return_value;
}

function keyUpHandler(e)
{
	var kCode = (window.event) ? event.keyCode : e.keyCode; 
    var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE // MSIE : Firefox
    var Enter = (window.event) ? 13 : e.DOM_VK_ENTER // MSIE : Firefox
    var Tab = (window.event) ? 9 : e.DOM_VK_TAB // MSIE : Firefox
    //debug_print('keyUpHandler | '+kCode);
    switch(kCode)
    {        
        case Tab:
            if (doCheckTab)
            {
                return doCheckTab();
            }
	        break;
        default:
            keyDownHandler(e)
		    break;
    }
}

function keyDownHandler(e)
{
	var kCode = (window.event) ? event.keyCode : e.keyCode; 
    var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE // MSIE : Firefox
    var Enter = (window.event) ? 13 : e.DOM_VK_ENTER // MSIE : Firefox
    var Tab = (window.event) ? 9 : e.DOM_VK_TAB // MSIE : Firefox
	var Ctrl = (window.event) ? event.ctrlKey : e.DOM_VK_CONTROL // MSIE : Firefox
	//debug_print('keyDownHandler | '+kCode);
    switch(kCode)
    {
        case Esc:
            doEscape();
	        break;
        case Enter:
            if(event.srcElement.tagName!='TEXTAREA')
            {
                //debugger;
	            doEnter();
	        }
		    break;
	    case Ctrl:
			//debugger
			switch(event.keyCode)
			{
				case 78:
				    //disable CTRL+N
					return doKeyPressStop();
				break;
			}
		    break;
	    case Tab:
	        if(isFormDisabled())
	        {
	            return doKeyPressStop();
	        }
	        break;
    }
    var ele = event.srcElement;
    //disable backspace except in input
    if(
		event.keyCode==8
		&&
		( 
			(ele.tagName.toUpperCase() != 'INPUT' && ele.tagName.toUpperCase() != 'TEXTAREA') 
			|| ele.readOnly == true
			|| ele.type == 'radio'
		)
	)
    {
        return doKeyPressStop();
    }
    
}

function doKeyPressStop()
{
	event.cancelBubble = true;
	event.returnValue = false;
	event.keyCode = false; 
	return false;
}

function doEscape()
{
    var bWarning = false;
    var frMsg ;
    var txtControl;
    switch (self)
    {
         case parent.frames['main']:
			if (document.getElementById('divMainProtect'))
			{
				if (document.getElementById('divMainProtect').style.width != '0px')
				{
					if (parent.frames['message'].__doPostBack)
					{
						parent.frames['message'].__doPostBack('btnMsgCancel','');
					}
				}
			}
			if (parent.frames['main'].__doPostBack)
			{
				frMsg  = parent.frames['message']
				if (frMsg ) { 
				    txtControl = frMsg.document.getElementById('txtValidateCtrl') 
				    if (txtControl) { 
				        if (txtControl.value != '') { 
                            bWarning = true;
				        }
				    }
				}
				if (bWarning) {
				    parent.frames['message'].__doPostBack('btnMsgCancel','');
				} else {
                    parent.frames['main'].__doPostBack('buttonbar:btnCancel','');
                }
	        }
	        break;
        case parent.frames['message']:
            if (parent.frames['message'].__doPostBack)
            {
                parent.frames['message'].__doPostBack('btnMsgCancel','');
            }
	        break;
        case parent.frames['menu']:
            if (parent.frames['main'].__doPostBack)
			{
				frMsg  = parent.frames['message']
				if (frMsg ) { 
				    txtControl = frMsg.document.getElementById('txtValidateCtrl') 
				    if (txtControl) { 
				        if (txtControl.value != '') { 
                            bWarning = true;
				        }
				    }
				}
				if (bWarning) {
				    parent.frames['message'].__doPostBack('btnMsgCancel','');
				} else {
                    parent.frames['main'].__doPostBack('buttonbar:btnCancel','');
                }
			}
            break;
    }
}

function doEnter()
{
    //tries to work out what should be done with 
	if (document.getElementById('buttonbar_imgOk'))
	{
		if (document.getElementById('buttonbar_imgOk').disabled)
		{
			return doKeyPressStop();
		}
	}
	if (parent.frames['message'])
	{
		if (parent.frames['message'].document.getElementById('txtValidateCtrl'))
		{
			if (parent.frames['message'].document.getElementById('txtValidateCtrl').value!='')
			{
				return doKeyPressStop();
			}
		}
		else
		{
			return doKeyPressStop();
		}
	}			
	if (validateWholePage()==0)
	{
		if (parent.frames['main'])
		{
			if (parent.frames['main'].__doPostBack)
			{
				parent.frames['main'].__doPostBack('buttonbar:btnOk','');
			}
		}
		else if (self.__doPostBack!=undefined)
		{
			self.__doPostBack('btnOk','');
		}
	}
}

function doCheckTab()
{
	//Restrains the tab indexing to important areas.
	if(parent.frames['main'])
	{
        if (parent.frames['main'].document.getElementById('divMainProtect'))
	    {
		    /*
		    If the Main area is protected then a message is in place.
		    So don't let tab operate.
		    */
		    if (parent.frames['main'].document.getElementById('divMainProtect').style.width =='100%')
		    {
			    //debug_print('doCheckTab: protection in place : '+parent.frames['main'].document.getElementById('divMainProtect').style.width);
			    return doKeyPressStop();
		    }
	    }
	}
    if (self.name=='main')
    {
        //Normal operation, using tabindex-1 to control where tab is allowed
        //debug_print('doCheckTab : Normal tab indexing being used. located in frame '+self.name+'.');
        return true;
    }
    else
    {
        if(parent.frames['main'])
        {
	        var tab_value=1;
            var these_controls = self.parent.frames['main'].document.getElementsByTagName('input');
            for (iCtl=0; iCtl<these_controls.length; iCtl++)
            {
		        //debug_print('doCheckTab ID :'+these_controls[iCtl].id+' | Class: '+these_controls[iCtl].className);
                if (
					(these_controls[iCtl].type=='text' || these_controls[iCtl].type=='password' || these_controls[iCtl].type=='radio') 
					&& these_controls[iCtl].tabIndex >= tab_value
					&& these_controls[iCtl].readOnly == false
					&& these_controls[iCtl].disabled == false
				)
                {
					try
					{
	                    these_controls[iCtl].focus();
	                    return true;
	                    //debug_print('doCheckTab |focusID :'+these_controls[iCtl].id+' | Class: '+these_controls[iCtl].className);
					}
					catch(e)
					{
						//debug_print('doCheckTab |failed focusID :'+these_controls[iCtl].id+' | Class: '+these_controls[iCtl].className);
					}
                }
//                else
//                {
//					//debug_print('doCheckTab \'not used\' |ID :'+these_controls[iCtl].id+' | Class: '+these_controls[iCtl].className);
//                }
            }
        }
    }
}

function isNumeric(expression)
{
    var validChars = "0123456789.";
    var validSignChars = "-+";
    var charValue;
    var decimalPointCount = 0;
    if((expression != null)&&(expression != 'undefined'))
    {
        for (var charIndex = 0; charIndex < expression.length; charIndex++) 
        { 
            charValue = expression.charAt(charIndex); 
            if (validChars.indexOf(charValue) == -1) 
            {
                //This may have a sign operator
                if (!((charIndex==0)&&(validSignChars.indexOf(charValue) != -1)))
                {
                    return false;
                }   
            }
            if(charValue=='.')
            {
                decimalPointCount++;
            }
        }
        if(decimalPointCount<2)
        {
            return true;
        }
        return true;
    }
    else
    {
        return false;
    }
}

//Nick
function isGenericPhoneNo(strPhone)
{
    // Check for correct phone number
    rePhoneNumber = new RegExp(/^\+?\d[-\s\d]*\d$/);

    if (strPhone == '')
    {
        return true;
    }
    
    if (!rePhoneNumber.test(strPhone)) 
    {
      return false;
    }
 
    return true;
    

    //return isMatch(strPhone,'/^\+?\d[-\s\d]*\d$/')

}

//orv
function isEmail(strEmail)
{
    // Check for valid email address
    reExp = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);

    if (strEmail == '')
    {
        return true;
    }
    
    if (!reExp.test(strEmail)) 
    {
      return false;
    }
 
    return true;

}

function isDate(strDate)
{
	//return !isNaN(new Date(p_Expression));		// <<--- this needs checking
	/* 
	checked, this does not work. or at least not in my tests
	*/
	/*try this
	    known issues:
	        haven't tested all date formats supported
	*/
	if (bValidateOverride)
    {
        //debug_print('Validation override in place. Skipping validation');
        return true;
    }
    /*
        This could be extended to be from a passed in format parameter instead of 'hardcoded' to dd/mm/yyy.
    */
    // order of d/m/y - 0/1/2
    var iDay = 0;
    var iMonth = 1;
    var iYear = 2;
    // splitChar - Default to nothing, this would make it fail if it is left, however if no split char is matched later the function returns false anyway..
    var splitChar = ''; 
    // declaration of our regexp for use later.
    var validformat;
    /*These regexp's force a format of 
        [0][1->9] or 1[0->9] or 2[0->9] 3[0-1] for the day
        [0][1-9] or 1[0->2] for the month
        1[000->999] or 2[000->999] for the year
        This has been changed now to make the leading 0's optional in all relevant places.
        Needs to be heavily tested with many dates and formats.
        Supported should be
        01/01/2006
        1/1/2006
        01.01.2006
        1.1.2006
        01-01-2006
        1-1-2006
        01\01\2006
        1\1\2006
    */
    //find SplitChar and set format regexp.
    if (strDate.indexOf('/') >= 0)
    {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\/)(0?[1-9]|1[0-2])(\/)[129][0-9]{3}/);
        splitChar = '/';
    }
    else if (strDate.indexOf('.') >= 0)
    {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\.)(0?[1-9]|1[0-2])(\.)[129][0-9]{3}/);
        splitChar = '.';
    }
    else if (strDate.indexOf('-') >= 0)
    {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\-)(0?[1-9]|1[0-2])(\-)[129][0-9]{3}/);
        splitChar = '-';
    }
    else if (strDate.indexOf('\\') >= 0)
    {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\\)(0?[1-9]|1[0-2])(\\)[129][0-9]{3}/);
        splitChar = '\\';
    }
    else
    {
        //Failover condition. None of the above matched so return failure.
        return false;
    }
	//debugger;
	if (!strDate.match(validformat))
    {
        //Regexp test, if it fails then return failure.
        return false;
    }
    else
    { 
        //Else process the date further to determine validity as real date.
        //This should be checking for things like feb 29th feb 30th feb 31st.
        var dayfield=strDate.split(splitChar)[iDay]
        var monthfield=strDate.split(splitChar)[iMonth]
        var yearfield=strDate.split(splitChar)[iYear]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
        {
            return false; //alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        }
        else
        {
            return true;
        }
    }
    return true;
}

function toDate(expression)
{
    /*
        returns a valid date object.
        expected date format is that of the calendar control.
        e.g. d/m/yyyy
        NOTE: if the date is not valid then this function will return 
        the current date.
        If you need to check date is valid please use isDateValid()
        before calling.
    */
     var sStartDate = expression.split('/');
     var day = 0;
     var month = 0;
     var year = 0;
     if (sStartDate.length > 0)
     {
        day = parseInt(sStartDate[0]);
     }
     if (sStartDate.length > 1)
     {
        month = parseInt(sStartDate[1]);
     }
     if (sStartDate.length > 2)
     {
        year = parseInt(sStartDate[2]);
     }
     if(day == 0)
     {
        day = new Date().getDate();
     }
     if(month == 0)
     {
        month = new Date().getMonth();
     }
     if(year == 0)
     {
        year = new Date().getYear();
     }
     return new Date(year,month,day);
}

// Numeric
// Ahsan 24/10/2006
function numericComparisons(expression, compareValue, whichComparison)
{
    //debugger;
    var value = null;
    var blnComparison = false;
    
    if (expression == '')
    {
        return true;
    }

    if ((expression != null)&&(expression != 'undefined'))
    {
        switch (whichComparison.toLowerCase())
        {
            case 'numericgreaterthanorequalto':
                value = getNumeric(expression, '-.+', true);
                if (value >= compareValue)
                {
                    blnComparison = true;
                }
                break;
                
            case 'numericlessthanorequalto':
                value = getNumeric(expression, '-.+', true);
                if (value <= compareValue)
                {
                    blnComparison = true;
                }
                break;
            
            case 'numericlessthan':
                value = getNumeric(expression, '-.+', true);
                if (value < compareValue)
                {
                    blnComparison = true;
                }
                break;
            
            case 'numericgreaterthan':
                value = getNumeric(expression, '-.+', true);
                if (value > compareValue)
                {
                    blnComparison = true;
                }
                break;
            
            case 'numericnotlongerthan':
                value = getNumeric(expression, '', true);
                if (value.length <= compareValue)
                {
                    blnComparison = true;
                }
                break;
            
            case 'numericnotshorterthan':
                value = getNumeric(expression, '', true);
                if (value.length >= compareValue)
                {
                    blnComparison = true;
                }
                break;
                
            case 'numericlengthequalto':
                value = getNumeric(expression, '', true);
                if (value.length == compareValue)
                {
                    blnComparison = true;
                }
                break;
            
            case 'numericnotblank':
                value = getNumeric(expression, '', true);
                if (value.length > 0)
                {
                    blnComparison = true;
                }
                break;
                
            case 'numericbutnotdecimal':

                value = getNumeric(expression, '+.-', true);
                var intValue = parseInt(value);

                if (value == intValue)
                {
                    blnComparison = true;
                }
                break;
                
            default:
                blnComparison = false;
        }
    }
    else
    {
        blnComparison = false;
    }
    
    return blnComparison;
}

function getNumericValue(that, allowTheseExtras, blnTreatAsANumber)
{
    //debugger;
    that.value = getNumeric(that.value, allowTheseExtras, blnTreatAsANumber);
    return true;
}

// Function: 
//     getNumeric
// Parameters: 
//     expression: input string.
//     allowTheseExtras: chars to be allowed other than numbers.
//     blnTreatAsANumber: will treat expression as a number. when
//     true, allowTheseExtras should only include +, period or a - sign.
// Returns: 
//     Numeric value of expression (input string)
// Example:
//     getNumeric('£  -1.01d', '.', true) will return -1.01
//     getNumeric('£  -1.01.', '.', true) will return false
// Author: 
//     Ahsan 23/10/2006
function getNumeric(expression, allowTheseExtras, blnTreatAsANumber)
{
    //debugger;
    var blnDecimal = false;
    var blnPositiveNegative = false;
    var strExpression = '';
    var chrAtIndex;
    var numList = '0123456789';
    var iCharIndex = 0;
    
    if((expression != null)&&(expression != 'undefined'))
    {
        for (iCharIndex = 0; iCharIndex < expression.length; iCharIndex++) 
        { 
            chrAtIndex = expression.charAt(iCharIndex);
            
           if ((!(numList.indexOf(chrAtIndex) == -1))||(!(allowTheseExtras.indexOf(chrAtIndex) == -1)))
            {
                if (blnTreatAsANumber)
                {
                    if ((chrAtIndex == '.')&&(blnDecimal))
                    {
                        // allow only one decimal occurance.
                        return false;
                    }
                    else if (chrAtIndex == '.')
                    {
                        // first occurrence of decimal
                        blnDecimal = true;
                    }
                    else if (((blnPositiveNegative)&&(chrAtIndex == '-'))||((chrAtIndex == '+')&&(blnPositiveNegative)))
                    {
                        // allow only one occurrence of + or - sign
                        return false;
                    }
                    else if ((chrAtIndex == '-')||(chrAtIndex == '+'))
                    {
                        // first occurance of - or + sign
                        blnPositiveNegative = true;
                    }
                }

                // concat to return string
                strExpression = strExpression.concat(chrAtIndex);

            }
        }

        return strExpression;
    }
    else
    {
        return false;
    }
}
 

