//scr - 15804 disable the back button
document.onkeydown = function () {
 if (event.keyCode == 8)
 	event.keyCode = 0;
}

function open_window(wPage, wName, wToolbar, wMenubar, wLocation, wDirectories, wResizable, wScrollbars, wHeight, wWidth)
{

/*
status:    		The status bar at the bottom of the window.
toolbar:   		The standard browser toolbar, with buttons such as Back and Forward.
menubar:      The menu bar of the window
location:  		The Location entry field where you enter the URL.
directories:  The standard browser directory buttons, such as What's New and What's Cool
resizable:		Allow/Disallow the user to resize the window.
scrollbars:  	Enable the scrollbars if the document is bigger than the window
height: 			Specifies the height of the window in pixels. (example: height='350')
width:  			Specifies the width of the window in pixels.
*/

	wName 			 = typeof wName=='undefined' 			  ? 'TM4WebDialog':wName;
	wToolbar 		 = typeof wToolbar=='undefined' 	  ? 'yes':wToolbar;
	wMenubar 		 = typeof wMenubar=='undefined' 	  ? 'yes':wMenubar;
	wLocation 	 = typeof wLocation=='undefined' 	  ? 'yes':wLocation;
	wDirectories = typeof wDirectories=='undefined' ? 'yes':wDirectories;
	wResizable 	 = typeof wResizable=='undefined' 	? 'yes':wResizable;
	wScrollbars  = typeof wScrollbars=='undefined' 	? 'yes':wScrollbars;
	wHeight 	   = typeof wHeight=='undefined' 			? 600:wHeight;
	wWidth 		   = typeof wWidth=='undefined' 			? 800:wWidth;

	var xPos = (screen.width / 2) - (wWidth / 2);
	var yPos = (screen.height / 2) - (wHeight / 2);
	var wfeatures = "status=1"+
									",toolbar="+wToolbar+
									",menubar="+wMenubar+
									",location="+wLocation+
									",directories="+wDirectories+
									",resizable="+wResizable+
									",scrollbars="+wScrollbars+
									",height="+wHeight+
									",width="+wWidth+
									",left="+1+
									",top="+1;

  OpenWin = window.open(wPage, wName, wfeatures);
}

function OpenDialog(page)
{
  if(page.indexOf("?")!=-1 && page.indexOf("&")!=-1){
    var query_string = page.split("?");
    var fields = query_string[1].split("&");
    page = query_string[0]+"?";
    for(var i=0; i < fields.length; i++){
      var a = fields[i].split("=");
      if(i>0){page += "&";}
      if(a[0]=='target'){
        page += "target="+a[1]+"&search_val="+document.getElementById(a[1]).value;
      }else{
        page += a[0]+"="+document.getElementById(a[1]).value;
      }
    }
  }
  var wHeight = 550;
  var wWidth  = 650;
	var xPos    = (screen.width / 2) - (wWidth / 2);
	var wOptions = "height="+wHeight+",width="+wWidth+",left="+xPos+",top=50,status=yes,scrollbars=yes,resizable=yes";
  OpenWin = this.open(page, "LookUp", wOptions);
  document.body.onunload = function() { OpenWin.close() };
}

function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		return 1; //alert("Time is not in a valid format.");
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }

	if (hour < 0  || hour > 23) {
		return 1; //alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
	}
	if (hour <= 12 && ampm == null) {
		if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
			return 1; //alert("You must specify AM or PM.");
	  }
	}
	if  (hour > 12 && ampm != null) {
		return 1; //alert("You can't specify AM or PM for military time.");
	}
	if (minute<0 || minute > 59) {
		return 1; //alert ("Minute must be between 0 and 59.");
	}
	if (second != null && (second < 0 || second > 59)) {
		return 1; //alert ("Second must be between 0 and 59.");
	}
	return 0;
}


function checkdate(objName) {
	var datefield = objName;
	if (chkdate(objName) == false) {
		//datefield.select();
		//datefield.focus();
		return 1; //alert("That date is invalid.  Please try again.");
	} else {
		return 0;
  }
}

function chkdate(objName) {
	var strDatestyle = "US"; //United States date style
	//var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = datefield.value;
	if (strDate.length < 1) {
		return true;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			} else {
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
	  }
	}
	if (booFound == false) {
		if (strDate.length>5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
	  }
	}
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}
	// US style
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
	    }
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
	  }
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		err = 7;
		return false;
	}
	if (intMonth == 2) {
		if (intday < 1) {
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
				err = 9;
				return false;
			}
		} else {
			if (intday > 28) {
				err = 10;
				return false;
			}
		}
	}
	/*
	if (strDatestyle == "US") {
		datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
	}	else {
		datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
	}
	*/
	return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) {
			return true;
		}
	} else {
		if ((intYear % 4) == 0) {
			return true;
		}
	}
	return false;
}

function doDateCheck(from, to, valToday) {
	if (Date.parse(from.value) <= Date.parse(to.value)) {
		return 0; //alert("The dates are valid.");
	} else {
		if (from.value == "" || to.value == "") {
			return 1; //alert("Both dates must be entered.");
		} else {
			return 2; //alert("To date must occur after the from date.");
		}
  }
}

function round (n) {
   n = Math.round(n * 100) / 100;
   n = (n + .001) + "";
   return n.substring(0, n.indexOf('.') + 3);
}

function numbersOnly(){
  if ((event.keyCode < 48 && event.keyCode != 46) || event.keyCode > 57) event.returnValue = false;
}

function allowInteger(number){
  if(number.substring(0,1) == "0"){
    number = number.substring(1,number.length);
  }
  number = number+String.fromCharCode(event.keyCode);
  if(number != parseInt(number)) {
    event.returnValue = false;
   }
}

function allowFloat(number){
  number = number+String.fromCharCode(event.keyCode);
  if(number != parseFloat(number)) {
   event.returnValue = false;
 }
}

function allowCurrency(obj)
{
  ch = String.fromCharCode(event.keyCode);
  if(!/\d|,|\$|\./.test(ch))
  {
    window.event.returnValue = false;
    return;
  }
  window.event.returnValue = true;
}

function lettersOnly()
{
  allowedLetters = /^[a-zA-z]+$/;
  letter = String.fromCharCode(event.keyCode);
	if(!allowedLetters.test(letter)) event.returnValue = false;
}

function alphanumericOnly()
{
  allowedValues = /\w/;
  the_value = String.fromCharCode(event.keyCode);
	if(!allowedValues.test(the_value)) event.returnValue = false;
  //if ((event.keyCode < 48 || event.keyCode > 57)&&(event.keyCode < 97 || event.keyCode > 122)) event.returnValue = false;
}

function contains_lowerCase(str){
  allowedLetters = /^[a-z]+$/;
  for(var i=0; i < str.length; i++){
    letter = str.substring(i,i+1);
	  if(allowedLetters.test(letter)) return true;
  }
  return false;
}

function contains_upperCase(str){
  allowedLetters = /^[A-Z]+$/;
  for(var i=0; i < str.length; i++){
    letter = str.substring(i,i+1);
	  if(allowedLetters.test(letter)) return true;
  }
  return false;
}

function contains_number(str){

  nums = /^[0-9]+$/;
  for(var i=0; i < str.length; i++){
    letter = str.substring(i,i+1);
	  if(nums.test(letter)) {return true;}
  }
  return false;
}

function first_char_num(str){
	nums = /^[0-9]+$/;
	letter = str.substring(0,1);
	//alert(letter);
	if(nums.test(letter)) return false;
	return true;
}

function no_repeats(str){
  cnt = 0;
  letter_1 = str.substring(0,1);
  for(var i=1; i < str.length; i++){
    letter_2 = str.substring(i,i+1);
	  if(letter_1 == letter_2) cnt++;
	  letter_1 = letter_2;
  }

  if(cnt > 1) return false;
  return true;
}

function allowed_sp_chars(str){
  sp_chars = new String(',<?=get_sys_value("PASSWORD_ALLOWED_SPECIAL_CHARS")?>');
  sp_chars = sp_chars.replace(/\,/g, "//");
  allowedChars = new RegExp("^[a-zA-z0-9"+sp_chars+"]+$");
	for(var i=0; i < str.length; i++){
    letter = str.substring(i,i+1);
	  if(!allowedChars.test(letter)) {return false;}
  }
  return true;
}

function resrtircted_words(str){
  str = str.toLowerCase();
  resrtirctedWords = '<?=get_sys_value("PASSWORD_RESTRICTED_WORDS")?>';
  resrtirctedWords = resrtirctedWords.replace("Seasons", "winter,spring,summer,fall");
  resrtirctedWords = resrtirctedWords.replace("Months", "January,February,March,April,May,June,July,August,September,October,November,December");
  var a_restricted = resrtirctedWords.split( "," );
  for(var i=0; i < a_restricted.length; i++){
    word = a_restricted[i].toLowerCase();
    if (str.indexOf(word)!=-1){return false;}
  }
  return true;
}

function selectThis(selectList, optionVal){
	for (i=0; i<selectList.length; i++){
		if (selectList.options[i].value == optionVal){
			selectList.options[i].selected = true;
			break;
		}
	}

}

function selectText(selectList, optionText)
{
	for (i=0; i<selectList.length; i++){
		if (selectList.options[i].text == optionText){
			selectList.options[i].selected = true;
			break;
		}
	}
}

function findThis(selectList, findMe){
	for (i=0; i<selectList.length; i++){
		if (selectList.options[i].value == findMe){
			return i;
		}
	}
  return false;
}

function fillThis(selectList, the_array)
{
  for(var i=0; i<the_array.length; i++)
  {
    if(findThis(selectList, the_array[i].name)===false){
      var option = new Option(the_array[i].name, the_array[i].name);
      selectList.options[selectList.options.length] = option;
    }
  }
}

function trim(s){
	s = rtrim(s);
	s = ltrim(s);
	return s;
}

function ltrim(s){
	s = s.replace(/^\s*/gi, "");//ltrim
	return s;
}

function rtrim(s){
	s = s.replace(/\s+$/gi, "");//rtrim
	return s;
}

/* START Sort table columns functions ************************************************************/
function SortTable(rowAr, contTable, contRow)
{
  //alert("SortTable");
   this.table = contTable;
   this.contRow = contRow;
   this.rowAr = rowAr;
   this.rowColnes = new Array();
   for(var c = 0; c < rowAr.length;c++){
      this.rowColnes[c] = rowAr[c].cloneNode(true);
   }
   this.arrow = document.createElement("SPAN");
   this.arrowUp = document.createElement("SPAN");
   //this.arrowUp.appendChild(document.createTextNode("    \/\\"));
   this.arrowUp.className = "arrow";
   this.arrowDown = document.createElement("SPAN");
   //this.arrowDown.appendChild(document.createTextNode("    \\\/"));
   this.arrowDown.className = "arrow";
  //alert("done sort table");
}

SortTable.prototype.setRows = function(srtAr)
{
	//alert("SortTable.prototype.setRows("+srtAr+")");
   var temp;
   var tempParent;
   for(var c = 0;c < this.rowAr.length;c++){
      temp = srtAr[c].cloneNode(true);
      this.setNode(this.rowAr[c], temp);
      this.rowAr[c] = temp;
      //alert(c); //IE 5.0 on NT 4 works with this alert in..?
   }
   //alert("setRows this.rowAr.length = "+this.rowAr.length);
}

SortTable.prototype.setNode = function(oldNode, newNode)
{
	//alert("SortTable.prototype.setNode");
	if(oldNode.parentNode){
    //SortColumn.init;
    oldNode.parentNode.replaceChild(newNode, oldNode);
	}
}

SortTable.prototype.cellsOf = function()
{
	//alert("SortTable.prototype.cellsOf");
   for(var c = 0;c < this.contRow.length;c++){
      this.contRow[c].SortColumn.displayOff();
   }
}

function SortColumn(index, cell, tableOb)
{
	//alert("SortColumn("+index+", "+cell+", "+tableOb+")");
  this.direction = 'up';
  this.tabelOb = tableOb;
  this.cell = cell;
  this.arrow = this.tabelOb.arrow.cloneNode(true);
  this.arrowup = this.tabelOb.arrowUp.cloneNode(true);
  this.arrowdown = this.tabelOb.arrowDown.cloneNode(true);
  this.dispNode = this.cell.appendChild(this.arrow);
  this.index = index;
}

SortColumn.prototype.displayOff = function()
{
	//alert("SortColumn.prototype.displayOff");
   if(this.arrow != this.dispNode){
      this.cell.replaceChild(this.arrow, this.dispNode);
      this.dispNode = this.arrow;
   }
}

SortColumn.prototype.displayOn = function()
{
	//alert("SortColumn.prototype.displayOn");
   this.tabelOb.cellsOf();
   this.cell.replaceChild(this['arrow'+this.direction],this.dispNode);
   this.dispNode = this['arrow'+this.direction];
}

SortColumn.prototype.getTableRows = function()
{
	//alert("SortColumn.prototype.getTableRows");
   var a = new Array();
   var t = this.tabelOb.rowColnes;
   for(var c = 0; c < t.length;c++){
      a[c] = t[c];
   } return a;
}

SortColumn.getParent = function(el, pTagName)
{
	//alert("SortColumn.getParent");
   if(el != null){
      if((el.nodeType == 1)&&
         (el.tagName.toUpperCase() == pTagName.toUpperCase())){
         return el;
      }else if(el.parentNode){
         return SortColumn.getParent(el.parentNode, pTagName);
      }
   } return null;
}

SortColumn.getDecendentByTagName = function(el, dTagName)
{
	//alert("SortColumn.getDecendentByTagName");
   var ndList;
   if(el.getElementsByTagName){
      ndList = el.getElementsByTagName(dTagName)
   }else if(el.all){   ndList = el.all.tags(dTagName);
   }
   if(!ndList){
      ndList = new Array();
   }else if(typeof ndList.length == 'undefined'){   ndList = new Array(ndList);
   } return ndList;
}

SortColumn.init = function(cel)
{
	//alert("SortColumn.init("+cel+")");
  var switchRow = SortColumn.getParent(cel, "TR");
  //alert("switchRow");
  if((switchRow)&&(switchRow.cells)&&(switchRow.parentNode)&&
  (switchRow.replaceChild)&&(switchRow.cloneNode)&&
  (document.createElement)&&(switchRow.appendChild)){


  if(typeof switchRow.innerText != 'undefined')
  {
    //alert("in init Q "+switchRow.innerText);
    SortColumn.getInnerText = SortColumn.getInnerTextQ;
    //alert("after Q ");
  }else if(typeof switchRow.childNodes != 'undefined')
  {
    SortColumn.getInnerText = SortColumn.getInnerTextW;
  }

      if(SortColumn.getInnerText){
         var contTable = SortColumn.getParent(switchRow, "TABLE");
         if(contTable){
            var rowArr = new Array();
            var rowList;
            var ndList =
              SortColumn.getDecendentByTagName(contTable, 'TBODY');
            if(ndList.length == 0)ndList = new Array(contTable);
            for(var c = 0;c < ndList.length;c++){
               rowList =
                 SortColumn.getDecendentByTagName(ndList[c], 'TR');
               for(var i = 0;i < rowList.length;i++){
                  if(switchRow != rowList[i]){
                     rowArr[rowArr.length] = rowList[i];
                  }
               }
            }
            var switchCells = switchRow.cells;
            contTable.sortTable =
               new SortTable(rowArr, contTable, switchCells);
            for(var c = 0;c < switchCells.length;c++){
               switchCells[c].SortColumn =
                new SortColumn(c, switchCells[c], contTable.sortTable);
            }
            return;
         }
      }

   }
   //SortColumn.byCase = SortColumn.byDate = SortColumn.byNoCase =
     //SortColumn.byNumber = function(){return;}; //disable code
}

SortColumn.getInnerTextQ = function(el)
{
	//alert("SortColumn.getInnerTextQ = *"+el.innerText+"*");
  return el.innerText;
}

SortColumn.getInnerTextW = function(el)
{
	//alert("SortColumn.getInnerTextW");
   var str = "";
   for (var i=0; i<el.childNodes.length; i++) {
      switch (el.childNodes.item(i).nodeType){
         case 1: //ELEMENT_NODE
            str += SortColumn.getInnerText(el.childNodes.item(i));

            break;
         case 3: //TEXT_NODE
            str += el.childNodes.item(i).nodeValue;

            break;
         default:
            break;
      }
   } return str;
}

SortColumn.prototype.sortIt = function(type)
{
  //alert("SortColumn.prototype.sortIt");
  this.direction = (this.direction == 'up')?'down':'up';
  //alert(this.direction);
  if(!this[this.direction]){
      if(!this['_f'+this.direction]){
         var st = 'this._f'+this.direction+' = function (n1, n2){'+
         'var d1 = n1.childNodes['+this.index+
          '];var d2 = n2.childNodes['+this.index+'];';
         var d1sortKey = 'SortColumn.getInnerText(d1)';
         var d2sortKey = 'SortColumn.getInnerText(d2)';
         //alert("d2sortKey = "+d2sortKey);
         var subtest = '';
         var firstTest = 'd1.sortKey < d2.sortKey';
         //alert("firstTest = "+firstTest);
         var secondTest = 'd1.sortKey > d2.sortKey';
         //alert("secondTest = "+secondTest);
//alert("type = "+type);
         switch(type){
            case 'noCase':
               d1sortKey = d1sortKey+'.toUpperCase()';
               d2sortKey = d2sortKey+'.toUpperCase()';
//alert("d1sortKey = "+d1sortKey);
            case 'case':
               break;
            case 'number':
               d1sortKey = 'parseFloat('+
                d1sortKey+'.replace(\/[^0-9\\.]\/g, ""))';
               d2sortKey = 'parseFloat('+d2sortKey+
                '.replace(\/[^0-9\\.]\/g, ""))';
               subtest = 'var dif = d1.sortKey - d2.sortKey;';
               firstTest = 'dif < 0';
               secondTest = 'dif > 0';
               break;
            case 'date':
               d1sortKey = 'Date.parse('+d1sortKey+
                '.replace(\/\\-\/g, \'\/\'))';
               d2sortKey = 'Date.parse('+d2sortKey+
                '.replace(\/\\-\/g, \'\/\'))';
               subtest = 'var dif = d1.sortKey - d2.sortKey;';
               firstTest = 'dif < 0';
               secondTest = 'dif > 0';
               break;
         }
         st += 'if(!d1.sortKey)d1.sortKey = '+d1sortKey+
              ';if(!d2.sortKey)d2.sortKey = '+d2sortKey+';'+subtest+
              'if('+firstTest+'){return '+
              ((this.direction == 'up')?'-1':'+1')+
              ';}else if('+secondTest+'){return '+
              ((this.direction == 'up')?'+1':'-1')+
              ';}else{return 0;}}';
//alert("st = "+st);
         eval(st);

      }
//alert("this.direction "+ this.getTableRows().sort(this['_f'+this.direction]));
      this[this.direction] =
       this.getTableRows().sort(this['_f'+this.direction]);
      //alert("this.direction");
      var a =
       this[((this.direction == 'up')?'down':'up')] = new Array();
      for(var c = (this[this.direction].length - 1),d = 0;c >= 0;c--){
         a[d++] = this[this.direction][c];
      }
  }

  this.displayOn();
  this.tabelOb.setRows(this[this.direction]);
  //alert("done sortit");
}
SortColumn.prototype.byNumber = function(){
	//alert("SortColumn.prototype.byNumber");
  this.sortIt('number');
}
SortColumn.prototype.byNoCase = function(){
	//alert("SortColumn.prototype.byNoCase");
  this.sortIt('noCase');
}
SortColumn.prototype.byCase = function(){
	//alert("SortColumn.prototype.byCase");
  this.sortIt('case');
}
SortColumn.prototype.byDate = function(){
	//alert("SortColumn.prototype.byDate");
  this.sortIt('date');
}
SortColumn.byNumber = function(cel){
	//alert("SortColumn.byNumber");
  SortColumn.init(cel);
  if(cel.SortColumn)cel.SortColumn.sortIt('number');
}
SortColumn.byNoCase = function(cel){
	//alert("SortColumn.byNoCase"+cel);
  SortColumn.init(cel);
  if(cel.SortColumn)cel.SortColumn.sortIt('noCase');
}
SortColumn.byCase = function(cel){
  //alert("SortColumn.byCase");
  SortColumn.init(cel);
  if(cel.SortColumn)cel.SortColumn.sortIt('case');
}
SortColumn.byDate = function(cel){
	//alert("SortColumn.byDate");
  SortColumn.init(cel);
  if(cel.SortColumn)cel.SortColumn.sortIt('date');
}
/* END * Sort table columns functions ************************************************************/

function make_chkBox_Readonly(chkBox){
	if(chkBox.checked){chkBox.checked = false}
	else{chkBox.checked = true}
}

function ucfirst(tmpStr){
	var tmpChar;
	var postString;
	var strlen;
	tmpStr = trim(tmpStr);
	tmpStr = tmpStr.toLowerCase();
	strLen = tmpStr.length;
	if (strLen == 0){return;}
	tmpChar = tmpStr.substring(0, 1).toUpperCase();
	postString = tmpStr.substring(1,strLen);
	tmpStr = tmpChar + postString;
	return tmpStr;
}


function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	//alert(fld.maxLength);
	//alert(fld.value.length);
	if (fld.value.length>fld.maxLength){
	  fld.value = fld.value.substr(1, fld.value.length);
		//return false;
	}
	if (whichCode == 13) return true;  // Enter

	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';

	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}

	return false;
}

function open_pdf(dld, reportName, table, max_detail_lines, path)
{
	theURL = path+"pdf_create.msw?dld="+dld+"&table="+table+"&reportname="+reportName+"&max_detail_lines="+max_detail_lines;
	var winName = reportName;
	w = 600;
	h = 500;
	var winl = Math.round((screen.width - w) / 2);
	var wint = Math.round((screen.height - h) / 2);
	features = 'scrollbars=yes,resizable=yes, height='+h+',width='+w+',top='+wint+',left='+winl;
  window.open(theURL,winName,features);
  return;
}

function valid_email(str){
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

		if (str.indexOf(at)==-1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false;
		 }

		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

 		 return true;
}

// Used in the order_entry page ***********/
// to add contacts, Carrier emails to the emailling options... ***********/
//function update_email() // SCR# 19496.
function update_email(the_list)
{
   if(typeof(the_list) == 'undefined'){ // SCR# 19496.
	// PUR *************************************************/
	  pur_pdf_email = document.getElementById ("pdf_email_pur");
	  if(pur_pdf_email){
	  	add_contacts_to_email_list(pur_pdf_email);
	  }

		pur_order_email = document.getElementById ("order_email_pur");
		if(pur_order_email){
	  	add_contacts_to_email_list(pur_order_email);
	  }

		// SHIPMENT ********************************************/
		ship_pdf_email = document.getElementById ("pdf_email_ship");
		if(ship_pdf_email){
	  	add_contacts_to_email_list(ship_pdf_email);
	  }

		ship_order_email = document.getElementById ("order_email_ship");
		if(ship_order_email){
	  	add_contacts_to_email_list(ship_order_email);
	  }
// SCR# 19496.
   }else{
	add_contacts_to_email_list(the_list);
   }
}

function add_contacts_to_email_list(list)
{
	var cnt = 0;

	// Clear the select list...
	list.options.length = cnt;

	// first option is 'none'...
	list.options.length = cnt + 1;
  list.options[cnt].text = "None";
  list.options[cnt].value = 'none';

	var all = '';

  //caller ...
  if(document.all.caller_email_address.value != ""){
  	if(valid_email(document.all.caller_email_address.value)){
	  	cnt = cnt + 1;
	  	list.options.length = cnt + 1;
	  	list.options[cnt].text = "Caller";
	  	list.options[cnt].value = document.all.caller_email_address.value;
	  	all = document.all.caller_email_address.value+",";
  	}
  }

  //shipper ...
  if(document.all.shipper_email_address.value != ""){
  	if(valid_email(document.all.shipper_email_address.value)){
	  	cnt = cnt + 1;
	  	list.options.length = cnt + 1;
	  	list.options[cnt].text = "Shipper";
	  	list.options[cnt].value = document.all.shipper_email_address.value;
	  	all += document.all.shipper_email_address.value+",";
  	}
  }

  //consignee ...
  if(document.all.consignee_email_address.value != ""){
  	if(valid_email(document.all.consignee_email_address.value)){
	  	cnt = cnt + 1;
	  	list.options.length = cnt + 1;
	  	list.options[cnt].text = "Consignee";
	  	list.options[cnt].value = document.all.consignee_email_address.value;
	  	all += document.all.consignee_email_address.value+",";
	  }
  }

  //carrier ...
  //only add to the shipment options
  if(list.name == 'pdf_email_ship' || list.name == 'order_email_ship'){
	  if(document.all.carrier_email.value != ""){
	  	if(valid_email(document.all.carrier_email.value)){
		  	cnt = cnt + 1;
		  	list.options.length = cnt + 1;
		  	list.options[cnt].text = "Carrier";
		  	list.options[cnt].value = document.all.carrier_email.value;
		  	all += document.all.carrier_email.value+",";
		  }
	  }
	}

  //last option is all ...
  if (cnt > 1){
  	all = all.substr(0,(all.length - 1));
  	cnt = cnt + 1;
  	list.options.length = cnt + 1;
  	list.options[cnt].text = "All";
  	list.options[cnt].value = all;
  }
}

var the_selectValue = "";
var item_selected_value;
function auto_complete_list(keyCode, list)
{
  if(keyCode == 9){return;}
  /* This function will find the next posible match for the text keyed into the select box */
  if(keyCode > 36 && keyCode < 41){return;}
  //number key pad...
  if(keyCode > 95 && keyCode < 106){keyCode -= 48;}
  //96 48  = 0
  //97 49  == 1
  //99 51  == 3
  //105 57 == 9
  char = String.fromCharCode(keyCode);
  //alert(char);

  //alert(list.options.length);
  the_selectValue = the_selectValue + char;
  var itemSelected = -1;
	var stillLooking = true;
	while (stillLooking) {
		for (i = 0; i < list.options.length; i++) {
			a = list.options[i].value.substr(0, the_selectValue.length).toUpperCase();
			//alert(a+"\n"+the_selectValue.toUpperCase());
			if (a == the_selectValue.toUpperCase()){
				itemSelected = i;
				stillLooking = false;
				break;
			}
		}
		if(stillLooking){
				the_selectValue = the_selectValue.substr(1 , the_selectValue.length -1);
				//reset_list(list, a_commodity_list, list.value);
				//alert("stillLooking selval= "+the_selectValue);
				if (the_selectValue == ""){stillLooking = false;}
		}

	}
	//alert(itemSelected);
	list.selectedIndex = itemSelected;
	//alert("itemSelected = "+itemSelected);
	//alert("end the_selectValue = "+the_selectValue);
	//alert("end");
	if(itemSelected == -1){
		item_selected_value = "";
	}else{
		item_selected_value = list.options[itemSelected].value;
		//filter_list(list, a_commodity_list, '^'+the_selectValue)
		//myfilter.set('^'+the_selectValue);
	}
}

//***********************************************************************/

function validate_email(str)
{
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);

		if (str.indexOf(at)==-1){return false;}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){return false;}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){return false;}

		if (str.indexOf(at,(lat+1))!=-1){return false;}

		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){return false;}

		if (str.indexOf(dot,(lat+2))==-1){return false;}

		if (str.indexOf(" ")!=-1){return false;}

 		return true;
}



function toggle_section(ElementID)
{
  obj = document.getElementById ("span_"+ElementID);
  img = document.getElementById ("img_"+ElementID);
  txt = document.getElementById ("txt_"+ElementID);

  if (obj.style.display=="")
  {
    obj.style.display="none";
  	img.src = imgExpand.src;
  	txt.style.textDecoration = "";
  }else
  {
  	obj.style.display="";
  	img.src = imgCollapse.src;
  	txt.style.textDecoration = "underline";
  }
}

function place_cursor(the_field, the_value)
{
  /* place cursor and select remaining text */

	if (the_field.createTextRange){
		var cursorKeys ="9;8;46;37;38;39;40;33;34;35;36;45;";
		//alert(cursorKeys.indexOf(event.keyCode+";"));
		//if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = the_field.createTextRange();
			var oldValue = r1.text;
			var newValue = the_value;
			//alert(newValue+"\n"+the_field.value);
			if (newValue != the_field.value){

			  the_field.value = newValue;
				var rNew = the_field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
			}
		//}
	}
}

function quickSort(arrTable, intColumn, sp, zg)
{
  //alert("quickSort \nintColumn = "+intColumn+"\nsp = "+sp+"\nzg = "+zg);
  //alert("go "+intColumn);
   var k = arrTable[Math.round((sp+zg)/2)][intColumn].toLowerCase();
   //alert("k = "+k);
   var i = sp;
   var j = zg;
   while  (j > i) {
    //alert("i = " + i + "\nintColumn= "+intColumn +"\n"+arrTable[i][intColumn]);
    while (arrTable[i][intColumn].toLowerCase() < k) ++i;
    //alert("i = " + i+"\nj = "+j);
    while (k < arrTable[j][intColumn].toLowerCase()) j = j - 1;
    //alert("j = " + j);
    if (i <= j)
    {
      var d = arrTable[i];
      arrTable[i] = arrTable[j];
      arrTable[j] = d;
      ++i;
      j = j - 1;
    }
  }


  if (sp<j)
    quickSort(arrTable, intColumn, sp, j);
  if (i<zg)
    quickSort(arrTable, intColumn, i, zg);
}



function binary_Search(array, find, caseInsensitive, getSubstring, arrayCheckThisIndex)
{
  window.status = "Binary Search for: "+find;
  //alert("start binary_Search:*"+find+"*\nindex = "+arrayCheckThisIndex+"\ncaseInsensitive = "+caseInsensitive+"\ngetSubstring = "+getSubstring);
  if(!array || typeof(array)!="object" || typeof(find)=="undefined" || !array.length){return null};
  var low  = 0;
  var high = array.length-1;
  var highOnTop=(array[0]>array[high])?1:0;
  find = (!caseInsensitive) ? find : find.toLowerCase();
  if(array[0].sorted_by!=arrayCheckThisIndex){
    quickSort(array, arrayCheckThisIndex, 0, high);
    //alert("After quickSort sorted_by = "+arrayCheckThisIndex);
    array[0].sorted_by = arrayCheckThisIndex;
  }
  //alert("length = "+(high)+"\nfind = "+find+"\nindex = "+arrayCheckThisIndex+"\nsorted by = "+array[0].sorted_by);
  //alert(array[0].sorted_by+"\n"+array[20][arrayCheckThisIndex]+"\n"+array[25][arrayCheckThisIndex]+"\n"+array[26][arrayCheckThisIndex]);
  while(low<=high)
  {
    var aTry=parseInt((low+high)/2);

    var checkThis=(typeof(arrayCheckThisIndex)=="undefined")? array[aTry]:array[aTry][arrayCheckThisIndex];
    checkThis=unescape(checkThis);
    //alert(aTry+" checkthis = "+checkThis);
    checkThis=(!caseInsensitive)?checkThis:checkThis.toLowerCase();
    checkThis=(!getSubstring)?checkThis:checkThis.substring(0, find.length);
    //alert(aTry+" checkthis = "+checkThis);
    //alert("search for "+find+"\n["+aTry+"]."+arrayCheckThisIndex+" = "+checkThis);
  	if(!highOnTop){

  		if(checkThis<find){
  		  //alert("array["+aTry+"]["+arrayCheckThisIndex+"] checkThis = "+checkThis+"\nfind = "+find+"\nhigh = "+high+"\nchange low = "+(aTry+1));
  		  low=aTry+1;
  		  continue;
  		}
  		if(checkThis>find){
  		  //alert("array["+aTry+"]["+arrayCheckThisIndex+"] checkThis = "+checkThis+"\nfind = "+find+"\nlow = "+low+"\nchange high = "+(aTry-1));
  		  high=aTry-1;
  		  continue;
  		}

  		//if(checkThis<find){low=aTry+1;continue;};
  		//if(checkThis>find){high=aTry-1;continue;};

  		checkThis=(typeof(arrayCheckThisIndex)=="undefined")?array[aTry-1]:array[aTry-1][arrayCheckThisIndex];
  	  checkThis=(!caseInsensitive)?checkThis:checkThis.toLowerCase();
      checkThis=(!getSubstring)?checkThis:checkThis.substring(0, find.length);
      //alert("checkThis = "+checkThis+"\naTry =  "+aTry+"\nlow = "+low+"\nhigh = "+high);
  	  if(checkThis==find){high=aTry;continue;};

  	}
  	else{
  		if(checkThis>find){low=aTry+1;continue;};
  		if(checkThis<find){high=aTry-1;continue;};
  	};
  	//alert("array["+aTry+"]["+arrayCheckThisIndex+"] =  "+array[aTry][arrayCheckThisIndex]+" found return = "+aTry);
    window.status = "Binary Search found: "+find+" - "+aTry;
    return aTry;//success: returns index: Number



  }
  //alert("No match");
  window.status = "Binary Search for: "+find+" not found";
  return null; /*no match: returns null*/
}

function clearTable(tbl)
{
  var the_tbl = window[tbl];
  tbl_length = the_tbl.rows.length;
  for(i=1; i<tbl_length; i++)
  {
    the_tbl.deleteRow();
  }
}

var the_selectValue = "";
var item_selected_value;
function auto_complete_list(keyCode, list)
{

  if(keyCode == 9){return;}
  /* This function will find the next posible match for the text keyed into the select box */
  if(keyCode > 36 && keyCode < 41){return;}
  //number key pad...
  if(keyCode > 95 && keyCode < 106){keyCode -= 48;}
  //96 48  = 0
  //97 49  == 1
  //99 51  == 3
  //105 57 == 9
  char = String.fromCharCode(keyCode);
  //alert(char);
  //alert(list.options.length);
  the_selectValue = the_selectValue + char;

  var itemSelected = -1;
 var stillLooking = true;
 while (stillLooking) {
  for (i = 0; i < list.options.length; i++) {

   a = list.options[i].value.substr(0, the_selectValue.length).toUpperCase();

   //alert(a+"\n"+the_selectValue.toUpperCase());
   if (a == the_selectValue.toUpperCase()){
    itemSelected = i;
    stillLooking = false;
    break;
   }
  }

  if(stillLooking){
    the_selectValue = the_selectValue.substr(1 , the_selectValue.length -1);
    //reset_list(list, a_commodity_list, list.value);
    //alert("stillLooking selval= "+the_selectValue);
    if (the_selectValue == ""){stillLooking = false;}
  }

 }

 //alert(itemSelected);
 list.selectedIndex = itemSelected;
 //alert("itemSelected = "+itemSelected);
 //alert("end the_selectValue = "+the_selectValue);
 //alert("end");
 if(itemSelected == -1){
  item_selected_value = "";
 }else{
  item_selected_value = list.options[itemSelected].value;
  //filter_list(list, a_commodity_list, '^'+the_selectValue)
  //myfilter.set('^'+the_selectValue);
 }
}

function validate_input(field, mask)
{
  if(event.keyCode == 8){return;}

  if(field.value.length == mask.length){event.keyCode = '';return;}

  var  mask_char = mask.substr(field.value.length,1);
  switch (mask_char) {
    case '-': event.keyCode = '-'.charCodeAt(); break;
    case '*': lettersOnly();break;
    case '#': numbersOnly();break;
    case '?': alphanumericOnly();break;
    //default: event.keyCode = '';break;
    default: break;
  }
  return;
}