//scr - 15804 disable the back button
//<![CDATA[
function browserDetect() {
  if(navigator.userAgent.indexOf("Gecko") != -1)
    return "FF";
  else return "IE";
}

function browserDetectIE6() {
	if (navigator.userAgent.indexOf("MSIE 6") != -1)
	  return true;
  else
		return false;
}

if (browserDetect() == "FF") {
  HTMLElement.prototype.__defineGetter__("innerText",
              function () { return(this.textContent); });
  HTMLElement.prototype.__defineSetter__("innerText",
              function (txt) { this.textContent = txt; });
}

// Trap Backspace(8) and Enter(13) -
// Except bksp on text/textareas, enter on textarea/submit

if (typeof window.event != 'undefined') // IE
  document.onkeydown = function() // IE
  {
    if(event.keyCode == 8)
      event.keyCode = 0;
  }
else
  document.onkeypress = function(event)  // FireFox/Others
  {
    var t=event.target.type;
    var kc=event.which;
    if ((kc != 8) || (t == 'text') || (t == 'textarea'))
      return true;
    else
      return false;
  }

function createCheckbox(field_name, field_checked, field_value)
{
  var newFieldCheckbox = document.createElement('INPUT');
  newFieldCheckbox.setAttribute('type',  'checkbox');
  newFieldCheckbox.setAttribute('name',  field_name);
  newFieldCheckbox.setAttribute('id',    field_name);
  newFieldCheckbox.setAttribute('value', field_value);
  if(field_checked){
  	newFieldCheckbox.setAttribute('defaultChecked', 'defaultChecked');
	}
  return newFieldCheckbox;
}

function createHidden(field_name, field_value)
{
  var newFieldHidden = document.createElement('INPUT');
  newFieldHidden.setAttribute('type', 'hidden');
  //newFieldHidden.setAttribute('type', 'text');
  newFieldHidden.setAttribute('name', field_name);
  newFieldHidden.setAttribute('id', field_name);
  newFieldHidden.setAttribute('value', field_value);
  return newFieldHidden;
}

function createImage(imgSrc, imgAlt, imgW, imgH, imgA)
{
	var newImg          = new Image();
	newImg.src 					= imgSrc;
	newImg.border       = '0';
	newImg.hspace       = '1';
	newImg.alt          = imgAlt;
	newImg.width        = imgW;
	newImg.height       = imgH;
	newImg.align        = imgA;
	return newImg;
}

function createInput(field_name, field_value, field_size, field_length, numOnly)
{
  var newFieldInput = document.createElement('INPUT');
  newFieldInput.setAttribute('name',  field_name);
  newFieldInput.setAttribute('id',    field_name);
  newFieldInput.setAttribute('value', field_value);
  newFieldInput.setAttribute('size',  field_size);

  if(field_length) newFieldInput.maxLength = field_length;

  if(numOnly)
  {
		newFieldInput.style.textAlign = 'right';
		newFieldInput.onkeypress = function() { return numbersOnly(event) };
  }
  return newFieldInput;
}

function createSelect(field_name, fieldList, selected_value, field_size)
{
  newFieldSelect = document.createElement('SELECT');
  newFieldSelect.setAttribute('name', field_name);
  newFieldSelect.setAttribute('id', field_name);
  newFieldSelect.style.width = field_size+'px';

  for(i=0; i < fieldList.length; i++)
  {
    var fieldOption = fieldList[i];
    newFieldOption = document.createElement("OPTION");
    newFieldOption.text = fieldOption;
    newFieldOption.value = fieldOption;
    newFieldSelect.options.add(newFieldOption);
    if(selected_value == fieldOption){ newFieldOption.selected = true; }
  }
  return newFieldSelect;
}

function createTextArea(field_name, field_value)
{
  var newFieldTextArea = document.createElement('textarea');
  newFieldTextArea.setAttribute('name',  field_name);
  newFieldTextArea.setAttribute('id',    field_name);
  newFieldTextArea.setAttribute('value', field_value);
  newFieldTextArea.setAttribute('cols', '20');
  newFieldTextArea.setAttribute('rows', '3');
  return newFieldTextArea;
}

function open_window(wPage, wName, wToolbar, wMenubar, wLocation, wDirectories, wResizable, wScrollbars, wHeight, wWidth, wTop, wLeft)
{
	/*
	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':trim(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 x_win = window.self;
	var i = 1;


	try {
  	while(x_win && typeof(x_win)!="undefined")
  	{
      if(typeof(x_win.opener)=="undefined"){ break; }
  		if(!x_win.opener){ break; }
  	  x_win = x_win.opener;
  	  if(!x_win){ break; }
  	  if(typeof(x_win)=="undefined"){ break; }
  	  i = i + 2;
  	}

	}catch (e) {
		//alert("error:"+e);
	}

	i = i * 5;
	wTop      	= typeof wTop=='undefined'      		? i:wTop;
  wLeft       = typeof wLeft=='undefined'       	? i:wLeft;

  var wfeatures = "status=1"+
                  ",toolbar="+wToolbar+
                  ",menubar="+wMenubar+
                  ",location="+wLocation+
                  ",directories="+wDirectories+
                  ",resizable="+wResizable+
                  ",scrollbars="+wScrollbars+
                  ",height="+wHeight+
                  ",width="+wWidth+
                  ",dependent=yes"+
                  ",left="+wTop+
                  ",top="+wLeft;

  OpenWin = window.open(wPage, wName, wfeatures);
  try {
  	// No popup blocker
  	OpenWin.opener = window;
		OpenWin.focus();
		document.body.onunload = function() { OpenWin.close() };
	}catch (e) {
		alert(err_popup_blocker);
	}
	return OpenWin;
}

function open_window_bill_status_update(url, movement_type) {
  url += "&movement_type=" + movement_type;
  open_window(url,'bill_update_appointments', 'no', 'no', 'no', 'no');
}

function OpenDialog(page)
{
  if(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')
      {
      	try {
      		var v = document.getElementById(a[1]).value;
      		v = escape(v);
      	} catch(err) {
      		var v = "";
      	}
        page += "target="+a[1]+"&search_val="+v;
      }else{
        var element = document.getElementById(a[1]);
        if(element != null) {
          var v = element.value;
          v = escape(v);
          page += a[0]+"="+v;
          if(a[0].indexOf("zone_desc")!=-1){
            page += "&target_zone_desc="+a[1];
          }
        }
      }
    }
  }
  open_window(page, "LookUp", 'no', 'no', 'no', 'no');
}

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 == "" || from.value == undefined || to.value == undefined) {
      return 1; //alert("Both dates must be entered.");
    } else {
      //alert(Date.parse(from.value) + "\n is less than\n" + Date.parse(to.value));
      return 2; //alert("To date must occur after the from date.");
    }
  }
}

function doDateCheckValues(from, to, valToday) {
  if (Date.parse(from) <= Date.parse(to)) {
    return 0; //alert("The dates are valid.");
  } else {
    if (from == "" || to == "" || from == undefined || to == undefined) {
      return 1; //alert("Both dates must be entered.");
    } else {
      //alert(Date.parse(from) + "\n is less than\n" + Date.parse(to));
      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(event){
  var keynum = getKey(event);
  var keychar;
  var numcheck;
  keychar = String.fromCharCode(keynum);
  numcheck = /[a-zA-Z`~!@#$%^&*()\-=_+\[\]\{\}\\|;':",\/<>\?]/; //'
  return !numcheck.test(keychar);
}

function phoneOnly(event){
  var keynum = getKey(event);
  if ((keynum <  48 &&
       keynum != 46 &&
       keynum != 40 &&
       keynum != 41 &&
       keynum != 45) || keynum > 57) event.returnValue = false;
}

function allowInteger(number, event){
  if(number.substring(0,1) == "0"){
    number = number.substring(1,number.length);
  }
  number = number+String.fromCharCode(getKey(event));
  if(number != parseInt(number)) {
    event.returnValue = false;
   }
}

function validateInteger(numField){
	var number = numField.value;
	if(number == '' || number == 0){ numField.value = 0; return true; }
  if(number.substring(0,1) == "0"){
    number = number.substring(1,number.length);
  }
  if(number != parseInt(number))
  {
    select_all_text(numField);
    return false;
  }
  return true;
}

function allowFloat(number, event){
  number = number+String.fromCharCode(getKey(event));
  if(number != parseFloat(number)) {
   event.returnValue = false;
 }
}

function validateFloat(numField){
	var number = numField.value;
	if(number == ''){ numField.value = 0; return true; }
  if(number != parseFloat(number))
  {
   	select_all_text(numField);
    return false;
 	}
 	return true;
}

function allowCurrency(obj, event)
{
  ch = String.fromCharCode(getKey(event));
  if(!/\d|,|\$|\./.test(ch))
  {
    event.returnValue = false;
    return;
  }
  event.returnValue = true;
}

function lettersOnly(event)
{
  var allowedLetters = /^[a-zA-z]+$/;
  var letter = String.fromCharCode(getKey(event));
  if(!allowedLetters.test(letter)) event.returnValue = false;
}

function alphanumericOnly(event)
{
  var allowedValues = /\w/;
  var the_value = String.fromCharCode(getKey(event));
  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){
  var allowedLetters = /^[a-z]+$/;
  for(var i=0; i < str.length; i++){
    var letter = str.substring(i,i+1);
    if(allowedLetters.test(letter)) return true;
  }
  return false;
}

function contains_upperCase(str){
  var allowedLetters = /^[A-Z]+$/;
  for(var i=0; i < str.length; i++){
    var letter = str.substring(i,i+1);
    if(allowedLetters.test(letter)) return true;
  }
  return false;
}

function contains_number(str){
  var nums = /[0-9]/;
  if(nums.test(str)) {
    return true;
  } else return false;
}

function first_char_num(str){
  var nums = /^[0-9]+$/;
  var letter = str.substring(0,1);
  //alert(letter);
  if(nums.test(letter)) return false;
  return true;
}

function no_repeats(str){
  var cnt = 0;
  var letter_1 = str.substring(0,1);
  for(var i=1; i < str.length; i++){
    var 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 selectThis(selectList, optionVal){
  for(i=0; i<selectList.length; i++){
    if(trim(selectList.options[i].value) == trim(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 (trim(selectList.options[i].value) == trim(findMe)){
      return i;
    }
  }
  return false;
}

function fillThis(selectList, the_array)
{
  //alert(selectList);
  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 removeThis(selectList, findMe)
{
  selectList.options[findThis(selectList, findMe)] = null;
}

function getValue(objID)
{
  var obj = document.getElementById(objID);

  if(obj.nodeName=='SELECT'){
    return trim(obj.options[obj.selectedIndex].value);
  }

  if(obj.nodeName=='INPUT'&&obj.type=='text')
  {
    return trim(obj.value);
  }

  if(obj.nodeName=='INPUT'&&obj.type=='hidden')
  {
    return trim(obj.value);
  }

  if(obj.nodeName=='INPUT'&&obj.type=='checkbox')
  {
    return obj.checked;
  }

  alert("return error");
  return "";
}

function findField(fieldName, fieldIndex)
{
  var the_field = undefined;
	frm = document.forms[0];
	if(frm.elements[fieldName] != undefined)
	{
	  the_field = frm.elements[fieldName];
	  if(frm.elements[fieldName][fieldIndex] != undefined){
			the_field = frm.elements[fieldName][fieldIndex];
		}
	}
	return the_field;
}

function trim(s){
  var temp = "" + s;
  temp = rtrim(temp);
  temp = ltrim(temp);
  return temp;
}

function ltrim(s){
  var temp = "" + s;
  temp = temp.replace(/^\s*/gi, "");//ltrim
  temp = temp.replace(/^\u00A0*/gi, "");
  return temp;
}

function rtrim(s){
  var temp = "" + s;
  temp = temp.replace(/\s+$/gi, "");//rtrim
  temp = temp.replace(/\u00A0+$/gi, "");
  return temp;
}

/* Sort select list functions ********************************************************************/
/*
<a href="#" onclick="sortMenu(document.getElementById('sel'),sortNum)">Sort by date entered the Union</a>(rank)<br />
<a href="#" onclick="sortMenu(document.getElementById('sel'),sortByText)"> Sort alphabetically </a><br />
<a href="#" onclick="sortMenu(document.getElementById('sel'),false,true)">Random sort </a><br />
<a href="#" onclick="sortMenu(document.getElementById('sel'),false,false,true)"> Reverse sort </a><br /><br />
*/
function removeOptionSelected(menu){
  if(menu.selectedIndex< 0 ){
    alert("Nothing selected");
    return;
  }
  menu.remove(menu.selectedIndex);
}

function sortMenu(menu,sortMethod,random,reverse){
  m=menu.length,mm=menu.length,values=[];
  while(m--){
    values[values.length]=[menu.options[m].value ||" ",menu.options[m].text ||" "];
  }
  if(!reverse)values.reverse();
  if(sortMethod)values.sort(sortMethod);
  if(random)values.shuffle(100);
  menu.length=0;
  for(var i=0;i<mm;i++){
    menu.options[i]=new Option(values[i][1] || "***",values[i][0] || "***");
  }
}

//The last three are variations of the function above:
function sortByValue(a,b){
  return a[0]<b[0]?-1:a[0]>b[0]? 1:0;
}
function sortByText(a,b){
  return a[1]<b[1]?-1:a[1]>b[1]? 1:0;
}
function sortNum(a,b){return a[0]-b[0]}
  // to sort by value or text:
  //sortMenu(document.forms[0].menuName,sortByValue)
  //sortMenu(document.forms[0].menuName,sortByText)

  //random
  Array.prototype.shuffle= function(times){
  var i,j,t,l=this.length;
  while(times--){
    with(Math){i=floor(random()*l);j=floor(random()*l);}
    t=this[i];this[i]=this[j];this[j]=t;
  }
  return this;
}
/*************************************************************************************************/

/* 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;
   var tr_class = "";
   for(var c = 0;c < this.rowAr.length;c++){
      temp = srtAr[c].cloneNode(true);
      this.setNode(this.rowAr[c], temp);
      this.rowAr[c] = temp;

      tr_class = (tr_class == "trace_tr") ? "trace_tr2" : "trace_tr" ;
      this.rowAr[c].className = tr_class;

      //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();
   }
}

var sort_direction = 'up';
function SortColumn(index, cell, tableOb)
{
  //alert("SortColumn("+index+", "+cell+", "+tableOb+")");
  //this.direction = 'down';

  this.direction = (sort_direction == 'up')?'down':'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;
  open_window(theURL, reportName, 'no', 'no', 'no', 'no');
  return;
}

function valid_email(str)
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)

	// test for the @ and the .
	if(str.indexOf(at)==-1 || str.indexOf(dot)==-1){ return false; }

	// test that the @ is not the first or last character
  if(str.indexOf(at)==0 || str.indexOf(at)==lstr){ return false; }

	// test that the . is not the first or last character
  if(str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ return false; }

	// commented out to allow for multiple @
	//if( str.indexOf(at,(lat+1)) != -1){ return false; }

	// test that the . is not right after or before the @
	if(str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ return false; }

	// test that the . is not right after or before the @
	if(str.indexOf(dot,(lat+2))==-1){ return false;}

	// test for spaces
	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)
{

  window.status = "Update Email";

  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);
  }

  window.status = " TM4Web";
}

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.getElementById('caller_email_address').value != ""){
    if(valid_email(trim(document.getElementById('caller_email_address').value))){  //SCR 31334 applied trim() function
      cnt = cnt + 1;
      list.options.length = cnt + 1;
      list.options[cnt].text = "Caller";
      list.options[cnt].value = document.getElementById('caller_email_address').value;
      all = document.getElementById('caller_email_address').value+",";
    }
  }

  //shipper ...
  if(document.getElementById('shipper_email_address').value != ""){
    if(valid_email(trim(document.getElementById('shipper_email_address').value))){  //SCR 31334 applied trim() function
      cnt = cnt + 1;
      list.options.length = cnt + 1;
      list.options[cnt].text = "Shipper";
      list.options[cnt].value = document.getElementById('shipper_email_address').value;
      all += document.getElementById('shipper_email_address').value+",";
    }
  }

  //consignee ...
  if(document.getElementById('consignee_email_address').value != ""){
    if(valid_email(trim(document.getElementById('consignee_email_address').value))){  //SCR 31334 applied trim() function
      cnt = cnt + 1;
      list.options.length = cnt + 1;
      list.options[cnt].text = "Consignee";
      list.options[cnt].value = document.getElementById('consignee_email_address').value;
      all += document.getElementById('consignee_email_address').value+",";
    }
  }

  //carrier ...
  //only add to the shipment options
  if(list.name == 'pdf_email_ship' || list.name == 'order_email_ship')
  {
    if(document.getElementById('vendor_email')){
      if(document.getElementById('vendor_email').value != ""){
        if(valid_email(trim(document.getElementById('vendor_email').value))){  //SCR 31334 applied trim() function
          cnt = cnt + 1;
          list.options.length = cnt + 1;
          list.options[cnt].text = "Carrier";
          list.options[cnt].value = document.getElementById('vendor_email').value;
          all += document.getElementById('vendor_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 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";
    if(img) img.src = imgExpand.src;
    if(txt) txt.style.textDecoration = "";
  }else
  {
    obj.style.display="";
    if(img) img.src = imgCollapse.src;
    if(txt) 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;
      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_id)
{
  var table = document.getElementById(tbl_id);
  var rows = table.rows;
  while(rows.length)
  	table.deleteRow(rows.length-1);
}

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 getKey(event) {
  if(window.event) return event.keyCode;
  else if(event.which) return event.which;
}
function setKey(event, keynum) {
  if(window.event) event.keyCode = keynum;
  else if(event.which) event.which = keynum;
}

function validate_input(field, mask, event)
{
  var keynum = getKey(event);

  if(keynum == 8){return;}

  if(field.value.length == mask.length){
    setKey(event, '');
    return;
  }

  var  mask_char = mask.substr(field.value.length,1);
  switch (mask_char) {
    case '-': setKey(event, '-'.charCodeAt()); break;
    case '*': lettersOnly(event);break;
    case '#': numbersOnly(event);break;
    case '?': alphanumericOnly(event);break;
    //default: event.keyCode = '';break;
    default: break;
  }
  return;
}

function select_all_text(the_field,the_end)
{
  if(the_field.nodeName=='INPUT'&&the_field.type=='text')
  {

    the_end = typeof the_end == 'undefined' ? the_field.value.length : the_end;
    if(browserDetect() == "IE") {
      var range = the_field.createTextRange();
      range.collapse(true);
      range.moveStart('character', 0);
      range.moveEnd('character', the_end);
      range.select();
    } else if(browserDetect() == "FF") {
      var range = document.createRange();
      range.selectNodeContents(the_field);
    }
  }
}

function countdown(mins, ofield)
{
  var H = (mins > 59) ? Math.floor(mins / 60) : 0;
  var M = parseInt(mins%60);
  var S = 0;
  var F = ofield.id;
  var _self = this;
  countdown.prototype.display_countdown = function()
  {
    document.getElementById(F).innerHTML = "Trace Page will reaload in "+((H < 10)?"0":"")+H+":"+((M < 10)?"0":"")+M+":"+((S < 10)?"0":"")+S;
    S--;
    if(S < 0){
      S = 59;
      M -= 1;
    }
    if(M < 0){
      M = 59;
      H -= 1;
    }
    if (H < 0) { H = 0; }
    setTimeout(_self.display_countdown,1000);
  }
}

function appendFunction(from_fnc, to_fnc)
{
  function parseFunctionName(fnc)
  {
    pat = /function[ ]+([^\(]+)[\(]([^\)]*)\)/;
    temp = String(fnc);
    return String(fnc).match(pat)[1];
  }
  fnc = new Function(
                     "function F_A() {\n" +
                          to_fnc + "\n" +
                          parseFunctionName(to_fnc)+ "();\n" +
                        "}\n" +
                     "function F_B() {\n" +
                          from_fnc + "\n" +
                          parseFunctionName(from_fnc)+ "();\n" +
                        "}\n" +
                     "F_A(); F_B();"
                    );
  return fnc;
}

function addToWindowOnload(addOnLoad)
{
  if (window.onload){
    x = appendFunction(addOnLoad, window.onload);
    window.onload = x;
  }else{
    window.onload = addOnLoad;
  }
}

/**
 * function: validate_Container_Digit
 * In: ContainerNum
 *     - string should consist of 11 characters
 *     - 4 letters + 6 numbers + the last character which is 'check digit'
 */
function validate_Container_Digit(cn_field, enforce_cd)
{
  ContainerNum = cn_field.value;
  //possible values: 'Never', 'Warning' or 'Error'
  if(enforce_cd == '' || enforce_cd == 'Never') { return true; }

  var len = ContainerNum.length;
  if(len != 11)
  {
    if(enforce_cd == 'Error'){
      alert(cde_error_length);
      return false;
    }

    // Warn
    if(confirm(cde_warn_length)){
      return true;
    }else{
      return false;
    }
  }

  var containerNumber = ContainerNum.substr(0, (len -1));
  var containerCheckDigit = ContainerNum.substr((len -1), len);
  var CheckDigit = GetCheckDigit(containerNumber);

  if(CheckDigit != containerCheckDigit)
  {

    var range = cn_field.createTextRange();
    range.collapse(true);
    range.moveStart('character', len -1);
    range.moveEnd('character', cn_field.value.length);
    range.select();

    if(enforce_cd == 'Error'){
      alert(cde_error_digit);
      return false;
    }

    // Warn
    if(confirm(cde_warn_digit)){
      return true;
    }else{
      return false;
    }
  }


  return true;

  function GetCheckDigit(ContainerNum)
  {


    var CheckDigit = -1;

    if(ContainerNum.length != 10){ return CheckDigit; }

    var TotNum = 0;
    var powernum = 1;
    var letter;
    var val;

    for(var i=0; i < 11; i++){
      letter = ContainerNum.substring(i,i+1);
      val = GetNum(letter);
      TotNum = TotNum + (powernum * val);
      powernum = powernum * 2;
    }

    //CheckDigit = TotNum mod 11; //modulus //x - (x div y) * y //a % b
    CheckDigit = TotNum % 11;

    if(CheckDigit == 10){ CheckDigit = 0; }

    return CheckDigit;

    function GetNum(TheLetter)
    {
      switch (TheLetter.toUpperCase())
      {
        case '0' : return 0;
        case '1' : return 1;
        case '2' : return 2;
        case '3' : return 3;
        case '4' : return 4;
        case '5' : return 5;
        case '6' : return 6;
        case '7' : return 7;
        case '8' : return 8;
        case '9' : return 9;
        case 'A' : return 10;
        case 'B' : return 12;
        case 'C' : return 13;
        case 'D' : return 14;
        case 'E' : return 15;
        case 'F' : return 16;
        case 'G' : return 17;
        case 'H' : return 18;
        case 'I' : return 19;
        case 'J' : return 20;
        case 'K' : return 21;
        case 'L' : return 23;
        case 'M' : return 24;
        case 'N' : return 25;
        case 'O' : return 26;
        case 'P' : return 27;
        case 'Q' : return 28;
        case 'R' : return 29;
        case 'S' : return 30;
        case 'T' : return 31;
        case 'U' : return 32;
        case 'V' : return 34;
        case 'W' : return 35;
        case 'X' : return 36;
        case 'Y' : return 37;
        case 'Z' : return 38;
      }
      return 0;
    }
  }
}

Array.prototype.in_array = function(obj){
  return new RegExp('(^|\,)'+obj+'(\,|$)','gi').test(this);
}

Array.prototype.count = function(){
  var count = 0;
  var i;
  for(i in this)
  {
   if(this.hasOwnProperty(i))
   {
    //alert(i+": "+this[i]);
    count++;
   }
  }
  return count;
}


function language_chg(language, formToRepost)
{
	var frm, oNode;

	oNode = document.createElement('input');
	oNode.name = 'language';
	oNode.type = 'hidden';
	oNode.value = language;
	frm = document.getElementsByName(formToRepost)[0];
	frm.appendChild(oNode);
	frm.submit();
}

// function from http://forums.devshed.com/t39065/s84ded709f924610aa44fff827511aba3.html
// author appears to be Robert Pollard
function sprintf()
{
   if (!arguments || arguments.length < 1 || !RegExp)
   {
      return;
   }
   var str = arguments[0];
   var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/; //'
   var a = b = [], numSubstitutions = 0, numMatches = 0;
   while (a = re.exec(str))
   {
      var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
      var pPrecision = a[5], pType = a[6], rightPart = a[7];

      numMatches++;
      if (pType == '%')
      {
         subst = '%';
      }
      else
      {
         numSubstitutions++;
         if (numSubstitutions >= arguments.length)
         {
            alert('Error! Not enough function arguments (' + (arguments.length - 1)
               + ', excluding the string)\n'
               + 'for the number of substitution parameters in string ('
               + numSubstitutions + ' so far).');
         }
         var param = arguments[numSubstitutions];
         var pad = '';
                if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
           else if (pPad) pad = pPad;
         var justifyRight = true;
                if (pJustify && pJustify === "-") justifyRight = false;
         var minLength = -1;
                if (pMinLength) minLength = parseInt(pMinLength);
         var precision = -1;
                if (pPrecision && pType == 'f')
                   precision = parseInt(pPrecision.substring(1));
         var subst = param;
         switch (pType)
         {
         case 'b':
            subst = parseInt(param).toString(2);
            break;
         case 'c':
            subst = String.fromCharCode(parseInt(param));
            break;
         case 'd':
            subst = parseInt(param) ? parseInt(param) : 0;
            break;
         case 'u':
            subst = Math.abs(param);
            break;
         case 'f':
            subst = (precision > -1)
             ? Math.round(parseFloat(param) * Math.pow(10, precision))
              / Math.pow(10, precision)
             : parseFloat(param);
            break;
         case 'o':
            subst = parseInt(param).toString(8);
            break;
         case 's':
            subst = param;
            break;
         case 'x':
            subst = ('' + parseInt(param).toString(16)).toLowerCase();
            break;
         case 'X':
            subst = ('' + parseInt(param).toString(16)).toUpperCase();
            break;
         }
         var padLeft = minLength - subst.toString().length;
         if (padLeft > 0)
         {
            var arrTmp = new Array(padLeft+1);
            var padding = arrTmp.join(pad?pad:" ");
         }
         else
         {
            var padding = "";
         }
      }
      str = leftpart + padding + subst + rightPart;
   }
   return str;
}

function removeElement(el)
{
  var i, n;
  if(!el) { return false; }
  if(!el.nodeName)
  {
    if(el.length){
      for (n=el.length; n--;){ removeElement(el[n]); }
    }
  }else{ el.parentNode.removeChild(el); }
}

function tm4web_js_error()
{
  //alert("do nothing");
}
function TM4WebErrorHandler(errMsg, errScript, errLine)
{
  try{
    //var msg = sprintf("<?=$lang['js_error']?>", errMsg, errScript, errLine);
    var msg ="An error has occurred in the script on this page.\n\n"+
                      "\tError Description: "+errMsg+"\n"+
                      "\tScript: "+errScript+"\n"+
                      "\tLine: "+errLine+"\n\n"+
                      "Click OK to continue.";
    alert(msg);
    if(typeof x_catch_js_error != 'undefined'){
      x_catch_js_error(errMsg, errScript, errLine, tm4web_js_error);
    }
    return true;
  }catch(e){
    return true;
  }
}
//window.onerror = TM4WebErrorHandler;


/**
 * Processing Functions
 */
function getWindowSize()
{
  var b=document.body, e=document.documentElement;
  var esw=0, eow=0, bsw=0, bow=0, esh=0, eoh=0, bsh=0, boh=0;
  if(e){
    esw = e.scrollWidth;
    eow = e.offsetWidth;
    esh = e.scrollHeight;
    eoh = e.offsetHeight;
  }
  if(b){
    bsw = b.scrollWidth;
    bow = b.offsetWidth;
    bsh = b.scrollHeight;
    boh = b.offsetHeight;
  }
  return {w:Math.max(esw,eow,bsw,bow),h:Math.max(esh,eoh,bsh,boh)};
}

function getCenter(el)
{
  sl=window.document.documentElement.scrollLeft;
  cw=document.documentElement.clientWidth;
  ow=el.offsetWidth;

  st=window.document.documentElement.scrollTop;
  ch=document.documentElement.clientHeight;
  oh=el.offsetHeight;

  return {l:(sl+(cw-ow)/2), t:(st+(ch-oh)/2)};
}

function ProcessingDisplay(sMsg)
{
  var pd = document.createElement('div');
  pd.setAttribute('name', 'processing_div');
  pd.setAttribute('id', 'processing_div');
  pd.style.left="0px";
  pd.style.top="0px";
  pd.className = 'ProcessingDiv';

  pm = document.createElement('p');
  pm.setAttribute('name', 'processing_msg');
  pm.setAttribute('id', 'processing_msg');
  pm.className = 'ProcessingMsg';
  pm.appendChild(document.createTextNode(sMsg));

  document.body.appendChild(pm);
  document.body.appendChild(pd);
}

function showProcessing()
{
  //Resize the div
  var pd = document.getElementById("processing_div");
  if (typeof pd == 'undefined' || pd==null){ return; }
  var windowSize = getWindowSize();
  pd.style.width=windowSize.w+"px";
  pd.style.height=windowSize.h+"px";

  //Center the msgbox
  var pm = document.getElementById("processing_msg");
  var windowCenter = getCenter(pm);
  pm.style.left=windowCenter.l+"px";
  pm.style.top=windowCenter.t+"px";
  pm.style.display="";
}

function stopProcessing()
{
  //Hide the div
  var pd = document.getElementById("processing_div");
  if(pd != null){
  pd.style.width="0px";
  pd.style.height="0px";
  }

  //Hide the msgbox
  var pm = document.getElementById("processing_msg");
  if(pm != null){
    pm.style.left="0px";
    pm.style.top="0px";
    pm.style.display="none";
  }
  window.status = ' TM4Web';
}

function addProcessingDiv(msg)
{
  //51721 msg = typeof msg == 'undefined' ? 'Please wait...' : trim(msg);
  msg = typeof msg != 'string' ? 'Please wait...' : trim(msg);
  ProcessingDisplay(msg);
}
addToWindowOnload(addProcessingDiv);


function focusFirst(frm)
{
  //set focus to first form field
  frm = typeof frm == 'undefined' ? document.forms[0] : frm;
  if( frm.elements[0]!=null)
  {
  	for(var i = 0; i < frm.length; i++ )
  	{
  		if( frm.elements[ i ].type != "hidden" &&
  			!frm.elements[ i ].disabled &&
  			!frm.elements[ i ].readOnly )
  			{
  				frm.elements[ i ].focus();
  				break;
  		}
  	}
  }
}

function get_row_index(el)
{
  //get the row index
  rowIndex = el.rowIndex;
  while(el.tagName!="TR")
	{
    el = el.parentNode;
  }
  return el.rowIndex;
}

function uploadStartBrowse(){
  document.getElementById('upload_success').style.visibility = 'hidden';
  document.getElementById('upload_warning').style.visibility = 'hidden';
  return true;
}

function uploadStart(){
  document.getElementById('upload_process').style.visibility = 'visible';
  document.getElementById('upload_fields').style.visibility = 'hidden';
  return true;
}

function uploadStop(msg, shortName, img_dir)
{
  //var fullName = document.getElementById('uploadedfile').value;
  //var shortName = fullName.match(/[^\/\\]+$/);

  if(msg.indexOf("[success]")==0)
  {
    document.getElementById('upload_success').style.backgroundImage = "url('"+img_dir+"/document_ok.png')";
    document.getElementById('upload_success').style.backgroundRepeat = "no-repeat";
    document.getElementById('upload_success').style.backgroundPosition = "center left";
    document.getElementById('upload_success').style.paddingLeft = "20px";
    document.getElementById('upload_success').style.visibility = 'visible';
    document.getElementById('upload_success').innerHTML = shortName+"<br>"+msg.substr( (msg.indexOf("]")+1), msg.length);
    uploadAttach(shortName);
  }else {
    document.getElementById('upload_warning').style.backgroundImage = "url('"+img_dir+"/document_error.png')";
    document.getElementById('upload_warning').style.backgroundRepeat = "no-repeat";
    document.getElementById('upload_warning').style.backgroundPosition = "center left";
    document.getElementById('upload_warning').style.paddingLeft = "20px";
    document.getElementById('upload_warning').style.visibility = 'visible';
    document.getElementById('upload_warning').innerHTML = shortName+"<br>"+msg;
  }

  document.getElementById('frm_upload').reset();
  document.getElementById('upload_process').style.visibility = 'hidden';
  document.getElementById('uploadedfile').value = '';
  document.getElementById('upload_fields').style.visibility = 'visible';

  return true;
}

function uploadOpen()
{
  //Display processing_div
  var pd = document.getElementById("processing_div");
  if (typeof pd == 'undefined' || pd==null){ return; }
  var windowSize = getWindowSize();
  pd.style.width = windowSize.w+"px";
  pd.style.height = windowSize.h+"px";
  pd.style.visibility = "visible";

  //Center new form
  var frm = document.getElementById("div_upload");
  var windowCenter = getCenter(frm);
  frm.style.left = (windowCenter.l-20)+"px";
  frm.style.top = (windowCenter.t-20)+"px";
  frm.style.visibility = "visible";
  document.getElementById('upload_fields').style.visibility = 'visible';
}

function uploadClose()
{
  //Hide processing_div
  var pd = document.getElementById("processing_div");
  if(pd != null){
    pd.style.width="0px";
    pd.style.height="0px";
  }

  //Hide the form
  var frm = document.getElementById("div_upload");
  if(frm != null){
    frm.style.visibility = "hidden";
    document.getElementById('upload_fields').style.visibility = 'hidden';
    document.getElementById('upload_success').style.visibility = 'hidden';
    document.getElementById('upload_warning').style.visibility = 'hidden';
  }
  window.status = ' TM4Web';
}

function uploadAttach(theFile)
{
  var tbl = document.getElementById('upload_attachTable');
  if(tbl){

    if(document.getElementById('upload_none') != null){
      document.getElementById('upload_none').style.display = 'none';
      document.getElementById('upload_attach').style.display = '';
    }

    var lastRow = tbl.rows.length;
    var newRow = tbl.insertRow(lastRow);
    if(lastRow%2 == 0){ newRow.className = "trace_tr2"; }else{ newRow.className = "trace_tr"; }
    var newCell = newRow.insertCell(-1);
    newCell.colSpan = '2';

    if(document.getElementById('dld').value != "'NA'"){
      var newLink = document.createElement('a');
        newLink.style.cursor = "hand";
        newLink.onclick = function() { open_attached_file(theFile) };
        newLink.innerHTML = theFile;
        newCell.appendChild(newLink);
    }else{
      newCell.innerHTML = theFile;
    }

    var cnt = 0;
    while(document.getElementById('attachFile'+cnt)!=null && cnt<100){ cnt++;}

    var newHiddenFileField = document.createElement('INPUT');
      newHiddenFileField.setAttribute('type', 'hidden');
      newHiddenFileField.setAttribute('id', 'attachFile'+cnt);
      newHiddenFileField.setAttribute('name', 'attachFile['+cnt+']');
      newHiddenFileField.setAttribute('value', theFile);

    newCell.appendChild(newHiddenFileField);

  }
}

/*
* id - string
* ID of element containing controls to disable/enable
*
* disabled - boolean
* true will disable, false will enable
*/
function setDisabled(id, disabled)
{
  if ( !document.getElementById
  || !document.getElementsByTagName) return;

  var nodesToDisable = {form :'', button :'', input :'', optgroup :'', option :'', select :'', textarea :'', img:'', a:''};

  var node, nodes;
  var div = document.getElementById(id);
  if (!div) return;


  div.className = 'greyed';
  //div.disabled = disabled;

  nodes = div.getElementsByTagName('*');
  if (!nodes) return;

  var i = nodes.length;
  while (i--){
    node = nodes[i];
    if ( node.nodeName
      && node.nodeName.toLowerCase() in nodesToDisable ){
      node.disabled = disabled;
      if(disabled){
        node.onclick = '';
        node.style.cursor = '';
        node.removeAttribute('href');
      }
    }
  }
}

//]]>
