/*******************conents*************************
1. global variables used in other areas of utilities
2. functions related to making specific direct-return related popups appear
3. overall document display management related functions
4. functions related to manipulating general text presentation of form controls
5. functions related to manipulating form controls
6. functions related to manipulating form controls in relation to specific direct return business logic
7. functions related to working with events/key codes specifically
8. functions related to verifying information
9. functions related to converting information to a string
10. functions related to convering strings to other types of data (tokenized arrays, numbers, etc)+
11. functions related to manipulating document flow (submitting forms) in relation to specific direct return
    business logic
*/


function _REFERENCE_NAVIGATION_CONTROLS()
{
//placeholder for all functions related to navigation
}

function pageBack() {
	history.go(-1);
	return false;
}
//END NAVIGATION CONTROLS

function _REFERENCE_EXECUTION_TIME_CONTROLS()
{
//placeholder for all functions related controlling timing in a page
}

    /*
    * This function will not return until (at least)
    * the specified number of milliseconds have passed.
    * It uses a modal dialog.
    */
function pause(numberMillis) {
	var dialogScript = 'window.setTimeout(' + ' function () { window.close(); }, '
	 + numberMillis + ');';
    var result = window.showModalDialog('javascript:document.writeln(' +
            '"<script>' + dialogScript + '<' + '/script>")');
}

//END EXECUTION_TIME CONTROLS

function _REFERENCE_APPLICATION_VERSION_CONTROLS()
{
//placeholder for all variables & functions to be used for figuring out what version of browser/css/etc we are dealing with
}


//1. global variables used in other areas of utilities
var global_ie45,global_ns6,global_ns4,global_dom;

//@private (scriplets that auto-sets the above variables
if (navigator.appName=="Microsoft Internet Explorer")
  global_ie45=parseInt(navigator.appVersion)>=4;
else if (navigator.appName=="Netscape"){
  global_ns6=parseInt(navigator.appVersion)>=5;
  global_ns4=parseInt(navigator.appVersion)<5;}  
global_dom=global_ie45 || global_ns6;


//END APPLICATION VERSION CONTROLS

function _REFERENCE_POPUP_CONTROLS()
{
//placeholder for all functions related to making specific direct-return related popups appear
}

//parent function for making popups appear
function openCentered(url, width, height, windowName, featureString) {
  if (!windowName)
    windowName = '';
  if (!featureString)
    featureString = '';
  else
    featureString = ',' + featureString;
  var x = Math.round((screen.availWidth - width) / 2);
  var y = Math.round((screen.availHeight - height) / 2);
  featureString = 'left=' + x + ',top=' + y + ',width=' + width + ',height=' + height + featureString;
  windowName = windowName+Math.floor(Math.random()*5)+'Pop'
  return window.open(url, windowName, featureString);
}

function calendarPop()
{
//datewin=window.open("/directreturn/jsp/calSearchDate.jsp", "DateWin", "height=300, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
datewin=openCentered("/directreturn/jsp/calendar.html", 300, 210,"DateWin", "location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
datewin.focus();
}

function pdfPop(pdfName)
{
//datewin=window.open("/directreturn/jsp/calSearchDate.jsp", "DateWin", "height=300, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
//datewin=window.open("/directreturn/jsp/helppop.html", "DateWin", "height=210, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
pdfwin=openCentered("/directreturn/pdf/"+pdfName,800,400, "Help", "resizable=yes");
pdfwin.focus();
}

function checkSettingsPop()
{
datewin=openCentered("/directreturn/jsp/checkbrowsersettings.htm", 380,70,"CheckSettings", "scrollbars=no,menubars=no,toolbars=no,resizable=no");
datewin.focus();
}

/*function helpPop(helpFile)
{
	if (helpFile == null || helpFile == 'undefined' || helpFile == '')
	{
		helpFile = '/directreturn/pdf/DirectReturnEnterpriseHelp.pdf';
	}*/
//datewin=window.open("/directreturn/jsp/calSearchDate.jsp", "DateWin", "height=300, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
//datewin=window.open("/directreturn/jsp/helppop.html", "DateWin", "height=210, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
//helpwin=openCentered(helpFile,600,600, "Help", "resizable=yes");

//helpwin=openCentered(helpFile,600,900, "Help", "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes");
//helpwin.focus();
//helpwin.moveTo(500,0);
var helpwin;
function helpPop(helpFile) {
//alert(helpFile);
	if (helpFile == null || helpFile == 'undefined' || helpFile == '')
	{
		helpFile = '/directreturn/pdf/DirectReturnEnterpriseHelp.pdf';
	}
//alert(helpFile);
	
   var w=300;
   var h=(screen.height-61);
	
	openRightTopCorner(helpFile, w, h, "HELPFILE", "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes");
 
}

//parent function for making popups appear
function openRightTopCorner(url, width, height, windowName, featureString) {
  if (!windowName)
    windowName = '';
  if (!featureString)
    featureString = '';
  else
    featureString = ',' + featureString;
	
  var x = Math.round(screen.availWidth - width)-10;
  var y = Math.round( 0 );
  featureString = 'left=' + x + ',top=' + y + ',width=' + width + ',height=' + height + featureString;
  windowName = windowName+Math.floor(Math.random()*5)+'Pop'
  return window.open(url, windowName, featureString);
}





function editCurrentUserPop()
{
//datewin=window.open("/directreturn/jsp/calSearchDate.jsp", "DateWin", "height=300, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
//datewin=window.open("/directreturn/jsp/helppop.html", "DateWin", "height=210, width=300, location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
userwin=openCentered("/directreturn/jsp/useredit.jsp?sessionuserflag=true&popmode=true",540,415, "Help", "resizable=yes");
userwin.focus();
}


//END POPUP CONTROLS

function _REFERENCE_EMAIL_CONTROLS()
{
//placeholder for all functions related to making emails
}

function sendEmail(addressee) {
  var url = 'mailto:'
  url += addressee ? addressee : '';
  location.href = url;
}

//END EMAIL CONTROLS

function _REFERENCE_POPUP_USING_DYNAMIC_DIV_CONTROLS()
{
//placeholder for all functions related to making DIV based popups appear (as opposed to regular page-based popups)
}

//@private
//the code below is not a function and is a javascript scriptlet that enables the functions below
//by defining a set of html prototype behaviours
if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
	HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
}

//@private
function createNewDivPopUp(divId, content, widthPixels, heightPixels)
{
  if (document.getElementById(divId) != null)
  {
  	document.getElementById(divId).style.visibility = 'visible'
	return;  
  }
  var x = Math.round((screen.availWidth - widthPixels) / 2);
  var y = Math.round((screen.availHeight - heightPixels) / 2);
   st = "<DIV id='"+divId+"' style='position:absolute; left:"+x+"px; top:"+y+"px; width:"+widthPixels+"px; height:"+heightPixels+"px; z-index:1; background-color: #9999CC; layer-background-color: #9999CC; border: 2px none #ffffff'>";
   st+="<TABLE width=\"100%\" height=\"100%\" border=\"1\" bordercolor=\"#000000\">";
   st+="<TR><TD align=middle>";
   st+=content;
   st+="</TD></TR>";
   st+="</TABLE></DIV>";
   document.body.insertAdjacentHTML("afterBegin",st);
}

//@private
function openCenteredAndDisplayWaitDivWhileLoading(url, width, height, windowName, featureString) {

  openPopUpWaitDiv();
  winNew = openCentered(url, width, height, windowName, featureString);
  window.focus();
  winNew.blur();
  window.focus();
}

function closeParentWaitDivAndFocusWhenLoaded() {
	resizeWindowIfRequested();
	window.opener.closePopUpWaitDiv(); 	
	window.focus();  
}

/*
Floating Menu script-  Roy Whittle (http://www.javascript-fx.com/)
Script featured on/available at http://www.dynamicdrive.com/
This notice must stay intact for use
*/
//Enter "frombottom" or "fromtop" for verticalposition
function setupFloatingMovingDiv(divId, verticalposition)
{
	var verticalpos = verticalposition;
	if (verticalpos == null || verticalpos == '')
	{
		verticalpos="fromtop"
	}
	var startX = 3,
	startY = 150;
	var ns = (navigator.appName.indexOf("Netscape") != -1);
	var d = document;
	function ml(id)
	{
		var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
		if(d.layers)el.style=el;
		el.sP=function(x,y){this.style.left=x;this.style.top=y;};
		el.x = startX;
		if (verticalpos=="fromtop")
		el.y = startY;
		else{
		el.y = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
		el.y -= startY;
		}
		return el;
	}
	window.stayTopLeft=function()
	{
		if (verticalpos=="fromtop"){
		var pY = ns ? pageYOffset : document.body.scrollTop;
		ftlObj.y += (pY + startY - ftlObj.y)/8;
		}
		else{
		var pY = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
		ftlObj.y += (pY - startY - ftlObj.y)/8;
		}
		ftlObj.sP(ftlObj.x, ftlObj.y);
		setTimeout("stayTopLeft()", 10);
	}
	ftlObj = ml(divId);
	stayTopLeft();
}
/*end*/



//@private
var waitDivOpened = false;

function openPopUpWaitDiv()
{
   waitDivOpened = true;
   createNewDivPopUp("waitDiv0123456", "<font class='jimtext'>The System is processing your request.</font><br><br><img src='/directreturn/images/standby-default.gif'>", 300, 150);
}

function closePopUpWaitDiv()
{
  if (waitDivOpened)
  {
  	try {
    document.getElementById("waitDiv0123456").style.visibility="hidden";
  	}catch(err){alert(err);}
	waitDivOpened = false;
  }
}

//END POPUP_USING_DYNAMIC_DIV CONTROLS


function _REFERENCE_PAGE_RESIZE_CONTROLS()
{
//placeholder for all functions related to dynamic page resizing
}

//@private
var global_widthToResizePageTo = -1;
var global_heightToResizePageTo = -1;

function resizeWindowIfRequested()
{
	//alert(global_widthToResizePageTo + " " + global_heightToResizePageTo);
	var trueWidth = -1;	
	var trueHeigth = -1;
	if (global_ns6 || global_ns4)
	{  
	  trueWidth = window.outerWidth+20;
	  trueHeigth = window.outerHeight+30;
	}
	else
	{	 
	  trueWidth = document.body.clientWidth+20;
	  trueHeigth = document.body.clientHeight+30;
	}
	 
	if (global_widthToResizePageTo > 0)
	{
		trueWidth = global_widthToResizePageTo;
	}
	if (global_heightToResizePageTo > 0)
	{
		trueHeigth = global_heightToResizePageTo;
	}
	if (global_widthToResizePageTo > 0 || global_heightToResizePageTo > 0)
	{
		window.resizeTo(trueWidth,trueHeigth);
	}
}

//@private
function setWindowWidthResizeIfNotSet(width)
{
	if (global_widthToResizePageTo != -1 && global_widthToResizePageTo > width)
	{
		return;
	}
	else
	{
		global_widthToResizePageTo = width;
	}
}

//END PAGE_RESIZE_CONTROLS


function _REFERENCE_DYNAMIC_ELEMENT_DISPLAY_CONTROLS()
{
//placeholder for all functions related to making page elements dynamically change (like swaping elements, hidding elements, showing elements, etc)
}

function setFocusOnElement(id)
{
  var el = document.all ? document.all[id] : global_dom ? document.getElementById(id) : document.layers[id];
     if (el)
	 {
       try {el.focus();}catch(err){}
	   try {el.select();}catch(err){}
	 }
}
function setDislayTrue(id, enable)
{
  var el = document.all ? document.all[id] : global_dom ? document.getElementById(id) : document.layers[id];
     if (el)
	 {
       el.style.display = ''
	 if (enable)
	   el.disabled = false
	   }
}

function setSize(id, width)
{
  var el = document.all ? document.all[id] : global_dom ? document.getElementById(id) : document.layers[id];
	if (el)
	{
		el.style.width = width;
	}
}


function isElementHidden(id)
{
  var el = document.all ? document.all[id] : global_dom ? document.getElementById(id) : document.layers[id];
     if (el)
	   {
	   	if ( el.style.display == 'none' )
		  return true
		else
		  return false;
		}
}

function setDislayFalse(id, disable)
{
 // var el = document.all ? document.all[id] : document.getElementById ? document.getElementById('elementID') :
 //      null;
 var el = document.all ? document.all[id] : global_dom ? document.getElementById(id) : document.layers[id];
     if (el)
	 {
       el.style.display = 'none'
	   if (disable)
	     el.disabled = false
	 }
}



function cycleImages(imageReference, millisecondIterval, imagearray)
{
   currentposition = 0
   imageRef = imageReference;
   imageArray = imagearray;
   setInterval("currentposition = imageSwap(imageRef,imageArray,currentposition)", millisecondIterval);
}

//@private
function imageSwap(image,imagearray,currentposition)
{
    if (currentposition == imagearray.length){currentposition = 0;}
    image.src = imagearray[currentposition];
	return currentposition + 1;

}

function changeElementInnerHTML(elementId, txt) {
	  document.getElementById(divFieldId).innerHTML = txt;
}

function rotateDivToClockwiseRotationPosition(targetDiv, position)
{
  if (!targetDiv.style.filter)
                   targetDiv.style.filter = 
  'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + position + ')';
                            else
   targetDiv.filters.item('DXImageTransform.Microsoft.BasicImage').Rotation = position
}
function rotateDivTo90DegreeRotation(targetDiv)
{
  rotateDivToClockwiseRotationPosition(targetDiv, 1)
}
function rotateDivToDefaultRotation(targetDiv)
{
  rotateDivToClockwiseRotationPosition(targetDiv, 0)
}

//END DYNAMIC_ELEMENT_DISPLAY CONTROLS

function _REFERENCE_DYNAMIC_TABLE_MANIPULATION_CONTROLS()
{
//placeholder for all functions related manipulating table elements
}

function deleteAllTableRows(tableID) {
  var table = document.all ? document.all[tableID] : document.getElementById(tableID);
  while (table.rows.length>0) {
      table.deleteRow(0);
   
  }
}

//END DYNAMIC_TABLE_MANIPULATION CONTROLS
 
function _REFERENCE_FORM_INPUT_TEXT_CONTROLS()
{
//placeholder for all functions related manipulating text-input controls in html forms
}
function isEmpty(object) { 
	return ((object.value == "") || (object.length == 0)) 
} 
function setTextFieldToUpperCase(field) { 
    field.value = getUpperCase(field.value)
}

function clearTextFields(form) {
  for (var e = 0; e < form.elements.length; e++) {
     if (form.elements[e].type == 'text' || form.elements[e].type == 'textarea')
     form.elements[e].value='';
  }  
}

function formatDate(field) {
    return formatDate(field, false);
}

function formatDate(field, bDisplayMsg) {
    var val=field.value;
    var digits;
 
    if (val.length==0) {
	    return true;
	}
 
	if (val.length==10) {
		field.value=val;
		if (!validateDateFormat(val, bDisplayMsg)) {
//		    field.value="";
			return false;
		}
	}
	
    var index1=String(val).indexOf('/');
    if (index1==1) {
        val="0"+val;
    }
	var index2=String(val).lastIndexOf('/');
	if (index2==4) {
		val=val.substring(0,3)+"0"+val.substring(3,10);
	}
    field.value=val;
    if (!validateDateFormat(val, bDisplayMsg)) {
//	    field.value="";
		return false;
	}
    
	return true;
}

function validateEmails(field){

//emailReg was taken from http://home.cogeco.ca/~ve3ll/jstutore.htm
	if (isEmpty(field.value))
		return true;
	else{
		var emailReg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
		var val = field.value;
		emails = val.split( /[,;\s] ?/ );
		for ( var i = 0; ( email = emails[i] ); i++ ){
			if ( ! emailReg.test( email ) ){
				alert("One or more e-mail addresses you entered are invalid");
				return false;
			}			
		}
		return true;
	}
}

//END FORM_INPUT_TEXT_CONTROLS

function _REFERENCE_FORM_INPUT_TEXT_DR_CONTROLS()
{
//placeholder for all functions related manipulating text-input controls that are specific to Direct Return logic
}

function processDEAEntry(field)
{
   
   var dea_input = field.value
   if (dea_input == '')
   {
   	  return;
   }
   dea_input = getDEAFormat(dea_input);
   
   if (dea_input == '')
   {
   	 field.select();        
   }
   return;


}

//END FORM_INPUT_TEXT_DR CONTROLS


function _REFERENCE_EVENT_KEYCODE_PROCESSING_CONTROLS()
{
//placeholder for all functions related custom processing of key code events
}


// this function to be used with zip codes 
// must be used with the onKeyPress event
function processZipEventForDigitsOnKeyPress(event) {
    var keyCode = getKeyCode(event); 

	// the non-character keys
	if (keyCode<=32) {
	    return true;
	// the dash
	} else if (keyCode==45) {
	    return true;
	// digits
	} else if (keyCode>=48 && keyCode<=57) {
	    return true;
	}
	return false;
}

function advanceField(field, event) {
    if (getKeyCode(event)==13 ) {
        var new_field=getNextElement(field);
        focusSelectField(new_field);
        return false;
    }
    return true;
}

function getKeyCode(event) {
    return event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
}

function isDigit(keyCode) {
    if ((keyCode>=96 && keyCode<=105) || (keyCode>=48 && keyCode<=57)) {
        return true;
    }
    return false;
}

function isCommand(keyCode) {
    // backspace=8, tab=9, shift=16, end=35, home=36, left=37, up=38, right=39, down=40, delete=46
	if (keyCode==8 || keyCode==9 || keyCode==16 || (keyCode>=35 && keyCode<=40) || keyCode==46) {
	    return true;
	}
	return false;
} 

//this function is currently obsolete
function toUpperCase(event) { 
    if (document.all) { 
        var c=event.keyCode; 
        var C=String.fromCharCode(c).toUpperCase().charCodeAt();
        event.keyCode=C; 
        return true; 
    } else {
        return true; 
    }
}

//END EVENT_KEYCODE_PROCESSING_CONTROLS


function _REFERENCE_FORM_INPUT_FOCUSING_CONTROLS()
{
//placeholder for all functions related to changing the focus or enabled/disabled status of form controls
}
function hiLite(field) {
    //check browser, this feature is not supported in Netscape
    if (navigator.appName == "Netscape")        {
    	return true;
    }
	//sets the background of the input field to the color value named
	else        {
	document.forms[0].elements[field].style.backgroundColor = "#ffffcc";
	return false;
	//document.body.style.cursor = "default";
	}
}
//turns off background highlight
function noLite(field) {
    if (navigator.appName == "Netscape")        {
    	return true;
	}
	//sets the background of the input field to the color value named
	else        {
	document.forms[0].elements[field].style.backgroundColor = "white";
	document.body.style.cursor = "default";
	}
	return null;
}
//@private
function getNextElement (startfield) {
  var field = startfield
  var form = field.form;
  var found = false;
  var e=0;
  for (e = 0; e < form.elements.length; e++) {
    if (field == form.elements[e] && e+1<form.elements.length) {
      if (form.elements[e+1].disabled==true || form.elements[e+1].visible==false || compareStrings(form.elements[e+1].type,'hidden')) {
 field = form.elements[e+1];
      }
      else 
      {
        field = form.elements[e+1];
        found = true; 
        break; 
      }
    }
  }
 
  if (found) { 
    return field;
  } 
  else { 
    return null;
  }
}

//disables all fields (including hidden fields)
function disableAll(form){
var i;
for (i=0; i<form.length; i++){
	form.elements[i].disabled=true;}
}
   
//enables all fields (including hidden fields)
function enableAll(form){
var i;
for (i=0; i<form.length; i++){
	form.elements[i].disabled=false;}
} 

function focusSelectField(field) {
    field.focus();
    try {
        field.select();
    } catch(err) {}
}



// enables all of the visual fields in the form that can be enabled
//(hidden fields will not be enabled)
function enableFields(form) {
  for (var e = 0; e < form.elements.length; e++) {
    if (form.elements[e].disabled==true && !compareStrings(form.elements[e].type,'hidden')) {
       form.elements[e].disabled=false;
    }
  }  
}

//END FORM_INPUT_FOCUSING CONTROLS

function _REFERENCE_FORM_INPUT_RADIO_CONTROLS()
{
//placeholder for all functions related to manipulating radio-input form controls
}


function getSelectedValueFromRadioGroup(targetRadioGroup)
{
  if (targetRadioGroup.length == 0)
  { 
  	return null;
  }
  //we need to handle the condition where the the redio group has only one element
  //and is thus not an array
  try{if (targetRadioGroup.checked) return targetRadioGroup.value }
  catch(e){}
  for (var i = 0; i < targetRadioGroup.length; i++)
  {
    
  	if (targetRadioGroup[i].checked){ return targetRadioGroup[i].value;}
  }
  return null;  
}

function findInRadioGroup(value, targetRadioGroup)
{
  if (targetRadioGroup.length == 0)
  { 
  	return -1;
  }
  for (var i = 0; i < targetRadioGroup.length; i++)
  {
  	if (targetRadioGroup[i].value == value){return i;}
  }
  return -1;  
}

//END FORM_INPUT_RADIO CONTROLS

function _REFERENCE_FORM_INPUT_SELECT_CONTROLS()
{
//placeholder for all functions related to manipulating select-input form controls
//note - many of these functions are applicable to both normal select controls and to multiselects (selects
//where more than one option can be selected)
}

//dynamically change the options in a select
function changeOptions(target_field, new_options)
{
  target_field.options.length = 0;
  for (var optionsChangeIter = 0; optionsChangeIter < new_options.length; optionsChangeIter++) {
    target_field.options[optionsChangeIter] = new_options[optionsChangeIter];
  }
}

function findInSelect(value, targetSelect)
{
  if (targetSelect.options.length == 0)
  { 
  	return -1;
  }
  for (var i = 0; i < targetSelect.options.length; i++)
  {
  	if (targetSelect.options[i].value == value){return i;}
  }
  return -1;  
}

function setSelectedIfExists(value, targetSelect)
{
	if (value == null || value == '')
	{
		return;
	}
	var i = findInSelect(value, targetSelect);
	if ( i > -1)
	{
		targetSelect.options[i].selected = true;
	}
}

function setDefaultSelectedIfExists(value, targetSelect)
{
	if (value == null || value == '')
	{
		return;
	}
	var i = findInSelect(value, targetSelect);
	if ( i > -1)
	{
		targetSelect.options[i].defaultSelected = true;
		targetSelect.options[i].selected = true;
	}
}

function getSelectedValueFromSelect(targetSelect)
{
  // alert("start");
  //alert("x"+targetSelect.selectedIndex);
  return targetSelect.options[targetSelect.selectedIndex].value;
}

function getSelectedTextFromSelect(targetSelect)
{
  // alert("start");
  //alert("x"+targetSelect.selectedIndex);
  return targetSelect.options[targetSelect.selectedIndex].text;
}

function getDefaultSelectedIndex(targetSelect)
{
	var i = 0;
	while (i < targetSelect.length)
	{
		if (targetSelect.options[i].defaultSelected == true)
		{
		  return i;
		}
		i++;
	}
	//if there is no default selected index, we will
	//default to zero since the first position is 
	//the default position under both IE & netscape
	return 0;	
}

function resetSelect(targetSelect)
{
 targeSelect.selectedIndex = getDefaultSelectedIndex(targetSelect);
}

function addtoselect(target_select,text,value,defaultSelected,currentSelected,position,allowDuplicates)
{
    value = trimSpaces(value)
	text = trimSpaces(text)
	if (value == null || value == '')
	{
		return
	}
    var opt = new Option(text, value,defaultSelected,currentSelected);
	if (!allowDuplicates)
	{
		if (findInSelect(value,target_select) > -1)
		{
			return;
		}
	}
	if (position == -1)
	{
	  target_select.options[target_select.options.length] = opt;
    }
	else
	{	
      for (var i = select.options.length; i > position; i--)
        select.options[i] = select.options[i - 1];
      select.options[position] = opt;
	}
}

function removefromselect(target_select,value)
{    
	if (value == null || target_select.options.length < 1)
	{
		return
	}
	while (findInSelect(value,target_select) > -1)
	{
		target_select.options[findInSelect(value,target_select)] = null;
	}
}

// compares the value of the first select box to the value of
// the second select box
function compareValuesOfSelect(select_one, select_two) {
    if (select_one == null || select_one == 'undefined') {
	    return -2;
	}
	if (select_two == null || select_two == 'undefined') {
	    return -3;
	}
	
	var selectOneVal, selectTwoVal;
	try {
	    selectOneVal = select_one.options[select_one.selectedIndex].value;
		selectTwoVal = select_two.options[select_two.selectedIndex].value;
		
		if (selectOneVal == '' || isNaN(selectOneVal) 
		    || selectTwoVal == '' || isNaN(selectTwoVal)) {
		    return -4;
		}
		if (Number(selectOneVal) < Number(selectTwoVal)) {
		    return -1;
		} else if (Number(selectOneVal) == Number(selectTwoVal)) {
		    return 0;
		} else {
		    return 1;
		}
	} catch(e) {
		return -5;
	}
}

function sortSelect(select) {
    var optionsArray = new Array(select.options.length);
 
    for (var i = 0; i < optionsArray.length; i++)
        optionsArray[i] = new Option (select.options[i].text,select.options[i].value,select.options[i].defaultSelected,select.options[i].selected);
 
    optionsArray.sort(compareText);
    select.options.length = 0;
 
    for (var i = 0; i < optionsArray.length; i++)
        select.options[i] = optionsArray[i];
}

//@private
//note - the function below is more a verification function than a form field manipulation
//function. However, since it's integral for the sortSelect to work properly (above) it is listed
//together with it
function compareText(option1, option2) {
  return option1.text < option2.text ? -1 : option1.text > option2.text ? 1 : 0;
}


//END FORM_INPUT_SELECT CONTROLS


function _REFERENCE_FORM_INPUT_SELECT_MULTIPLE_CONTROLS()
{
//placeholder for all functions related to manipulating select-input form controls that specifically allow
//mulitple options to be selected.
//- note - many of the functions related to dealing with regular selects can also be used with multi-option selects,
//however all the functions in this sections are intended to ONLY be used with multi option selects
}


function getSelectedOptionValuesInMultipleSelect(select_target)
{
	var i = 0, iElement = 0;
	var aIndices = new Array(0);
	while (i < select_target.length)
	{
		if (select_target.options[i].selected) {
			aIndices[iElement] = select_target.options[i].value;
			iElement = iElement + 1;
		}
		i++;
	}
	return aIndices;
}

function setSelectedOptionValuesInMultipleSelect(select_target, vals)
{
	var sValue = '';
	for (var j=0; j<vals.length; j++) {
		sValue = vals[j];
			for (var i=0; i<select_target.length; i++) {
			if (select_target.options[i].value == sValue) {
				select_target.options[i].selected = true;
				break;
			}
		}
	}
}





//note that this function will not work properly if the select
//is disabled
function selectAllOptionsInMultipleSelect(select_target)
{
	var i = 0;
	select_target.multiple = true;
	while (i < select_target.length)
	{
		select_target.options[i].selected = true
		i++;
	}
}
function unselectAllOptionsInMultipleSelect(select_target)
{
	var i = 0;
	select_target.multiple = true;
	while (i < select_target.length)
	{
		select_target.options[i].selected = false
		i++;
	}
}

function isAnyOptionSelectedInMultipleSelect(select_target)
{
	var i = 0;	
	while (i < select_target.length)
	{
		if (select_target.options[i].selected)
		{
			return true
		}
		i++;
	}
	return false
}


function numberOfOptionsSelectedInMultipleSelect(select_target)
{
	var i = 0;
	var count = 0;	
	while (i < select_target.length)
	{
		if (select_target.options[i].selected)
		{
			count++;
		}
		i++;
	}
	return count;
}



//this is for use with multiple selects
//the purpose is to have the select allow multiple selections (b/c
//we need have retrieve multiple values from it after a submit)
//and at the same time give us access to whatever value was clicked
//last (a multiple select does not coorectly support the selectedIndex
//property)
function retrieveFirstSelectedOptionPositionAndUnselectIt(select_target)
{

 for(i=0;i<select_target.length;i++)
 {
  if (select_target.options[i].selected )
  {
    var val = i;
	select_target.options[i].selected = false;
	return val;
  }
 }
 return 0
}

// Dual list move function
// @depricated
/*
function moveDualList( srcList, destList, moveAll ) 

{

  // Do nothing if nothing is selected

  if (  ( srcList.selectedIndex == -1 ) && ( moveAll == false )   )

  {

    return;

  }



  newDestList = new Array( destList.options.length );



  var len = 0;



  for( len = 0; len < destList.options.length; len++ ) 

  {

    if ( destList.options[ len ] != null )

    {

      newDestList[ len ] = new Option( destList.options[ len ].text, destList.options[ len ].value, destList.options[ len ].defaultSelected, destList.options[ len ].selected );

    }

  }



  for( var i = 0; i < srcList.options.length; i++ ) 

  { 

    if ( srcList.options[i] != null && ( srcList.options[i].selected == true || moveAll ) )

    {

       // Statements to perform if option is selected



       // Incorporate into new list

       newDestList[ len ] = new Option( srcList.options[i].text, srcList.options[i].value, srcList.options[i].defaultSelected, srcList.options[i].selected );

       len++;

    }

  }



  // Sort out the new destination list

  newDestList.sort( compareOptionValues );   // BY VALUES

  //newDestList.sort( compareOptionText );   // BY TEXT



  // Populate the destination with the items from the new array

  for ( var j = 0; j < newDestList.length; j++ ) 

  {

    if ( newDestList[ j ] != null )

    {

      destList.options[ j ] = newDestList[ j ];

    }

  }



  // Erase source list selected elements

  for( var i = srcList.options.length - 1; i >= 0; i-- ) 

  { 

    if ( srcList.options[i] != null && ( srcList.options[i].selected == true || moveAll ) )

    {

       // Erase Source

       //srcList.options[i].value = "";

       //srcList.options[i].text  = "";

       srcList.options[i]       = null;

    }

  }



} // End of moveDualList()

function compareOptionValues(a, b) 

{ 

  // Radix 10: for numeric values

  // Radix 36: for alphanumeric values

  var sA = parseInt( a.value, 36 );  

  var sB = parseInt( b.value, 36 );  

  return sA - sB;

}



// Compare two options within a list by TEXT

function compareOptionText(a, b) 

{ 

  // Radix 10: for numeric values

  // Radix 36: for alphanumeric values

  var sA = parseInt( a.text, 36 );  

  var sB = parseInt( b.text, 36 );  

  return sA - sB;

}
*/

//END FORM_INPUT_SELECT_MULTIPLE CONTROLS


function _REFERENCE_FORM_INPUT_SELECT_DR_CONTROLS()
{
//placeholder for all functions related to manipulating input-select controls related to DirectReturn specific logic
}



// when the user clicks the add button next to the qty the qty field should
// change from blank to 10% to 25% to 50% to 75% but only if a partial package
// is selected in the full_partial drop-down
// field1 - full_partial field
// field2 - quantity field
function add(field1, field2) {
    var fullpartial=field1;
    // if the item the user is entering is a partial...
    if (compareStrings(fullpartial.options[fullpartial.selectedIndex].value, "p")) {
        // then check to see which percentage to increase the qty by
        // Note: once the user enters something else into the quantity field
        // do not allow them to proceed using percentages.
        var qty=field2;
        var qtylength=qty.value.length;
        var pctvalue=-1;
 
        if (qtylength==0) {
            pctvalue=0;
        } else if (qty.value.substr(qtylength-1,1)=='%') { 
            pctvalue=Number(qty.value.substr(0,qtylength-1));
        } else {
            pctvalue=Number(qty.value);
        }
         
        if (pctvalue>=0 && pctvalue<10) {
            qty.value="10%";
        } else if (pctvalue>=10 && pctvalue<25) {
            qty.value="25%";
        } else if (pctvalue>=25 && pctvalue<50) {
            qty.value="50%";
        } else if (pctvalue>=50 && pctvalue<75) {
            qty.value="75%";
        } else {
            qty.value="10%";
        }
    }
    field2.focus();
    field2.select();
}
 
// when the user clicks the subtract button next to the qty the qty field should
// change from 75% to 50% to 25% to 10% to blank but only if a partial package
// is selected in the full_partial drop-down
// field1 - full_partial field
// field2 - quantity field
function subtract(field1, field2) {
    var fullpartial=field1;
    // if the item the user is entering is a partial...
    if (compareStrings(fullpartial.options[fullpartial.selectedIndex].value, "p")) {
        // then check to see which percentage to decrease the qty by
        // Note: once the user enters something else into the quantity field
        // do not allow them to proceed using percentages.
        var qty=field2;
        var qtylength=qty.value.length;
        var pctvalue=-1;
 
        if (qtylength==0) {
            pctvalue=0;
        } else if (qty.value.substr(qtylength-1,1)=='%') { 
            pctvalue=Number(qty.value.substr(0,qtylength-1));
        } else {
            pctvalue=Number(qty.value);
        }
         
        if (pctvalue>75) {
            qty.value="75%";
        } else if (pctvalue>50 && pctvalue<=75) {
            qty.value="50%";
        } else if (pctvalue>25 && pctvalue<=50) {
            qty.value="25%";
        } else if (pctvalue>10 && pctvalue<=25) {
            qty.value="10%";
        } else if (pctvalue>=0 && pctvalue<=10) {
            qty.value="75%";
        }
 
    }
    field2.focus();
    field2.select();
}

//END FORM_INPUT_SELECT_DR CONTROLS


function _REFERENCE_FORM_INPUT_CHECKBOX_CONTROLS()
{
//placeholder for all functions related to manipulating select-checkbox form controls 
}

//TODO make this a bit more elegant
var numRptSelected = 0;
function checkall(form,check,onoff){
   var count = 0;
   var letsgo = eval("document.forms."+form+"."+check);
   if (letsgo==null) {
       return;
   } 
   else if (letsgo.length>1) {
     
      while( count<letsgo.length) {
         if (!letsgo[count].disabled) {
             letsgo[count].checked=onoff;
         
         }
         count++;
      }
   } else {
         if (!letsgo.disabled) {
             letsgo.checked=onoff;
             count = 1;
      }
 
   }

 if (true == onoff)
 {
   numRptSelected = count;
 }
 else
 {
   numRptSelected = 0;
 }
}

//in this case, the actual form gets passed in, together with
//a pattern for the beginning of the checkbox's name and the onoff flag
function checkAllMatchingNamePattern(form,checkStartNameString,onoff){
   var count = 0;
   for (j=0; j<form.length; j++) {
         if (form.elements[j].type == "checkbox" && form.elements[j].name.indexOf(checkStartNameString) == 0)
		 {
		   form.elements[j].checked = onoff;
           count++;	 
		 }
       
   } 
  if (true == onoff)
  {
   numRptSelected = count;
  }
  else
  { 
    numRptSelected = 0;
  }
}

function isAnythingCheckedInCheckboxesMatchingNamePattern(form,checkStartNameString){
   for (j=0; j<form.length; j++) {
         if (form.elements[j].type == "checkbox" && form.elements[j].name.indexOf(checkStartNameString) == 0)
		 {
		   if (form.elements[j].checked)
		   {
		   		return true
			}		 
		 }
       
   } 
   return false
}

function numberCheckedInCheckboxesMatchingNamePattern(form,checkStartNameString){
	var count = 0;
	for (j=0; j<form.length; j++) {
		if (form.elements[j].type == "checkbox" && form.elements[j].name.indexOf(checkStartNameString) == 0)
		 {
		   if (form.elements[j].checked)
		   {
		   		count++;
			}		 
		 }
   } 
   return count;
}
//END FORM_INPUT_CHECKBOX CONTROLS



function _REFERENCE_UTIL_STRING_FUNCTIONS()
{
//placeholder for all functions related to working with string PARAMETERS
//(meaning some of these functions returns things other than strings - like dates, booleans, etc) 
}

function isNumeric(s){
if (s=="")
return true; //if it's blank, we don't check
var Chars = "0123456789";
    for (var chariter = 0; chariter < s.length; chariter++) {
       if (Chars.indexOf(s.charAt(chariter)) == -1)
          return false;
        }// end for
return true;
}// end method

function validateRequiredEmail(string)
{
 if (string == '' || string == null)
 {
   return false
 }
 return validateEmail(string)
}


function validateEmail(string)
{
if (string == '' || string == null)
	return true
//string = trimSpaces(string)
var valid  = true
var AtSym    = string.indexOf('@')
var Period   = string.lastIndexOf('.')
var Space    = string.indexOf(' ')
var Length   = string.length - 1   // Array is from 0 to length-1

if ((AtSym < 1) ||                     // '@' cannot be in first position
    (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
    (Period == Length ) ||             // Must be atleast one valid char after '.'
    (Space  != -1))                    // No empty spaces permitted
   {  
      valid = false
   }
return valid
}

function compareStrings(str1, str2) {
    // if the two strings aren't the same length then they must not be equal
    // so return false
    if (String(str1).length!=String(str2).length) {
        return false;
    }
 
    // compare each character of each string with the same character of the
    // other string, if even one character doesn't match the two strings 
    // aren't equal so return false
    for (var i=0; i<String(str1).length; i++) {
        if (String(str1).charAt(i)!=String(str2).charAt(i)) {
            return false;
        }
    }
    
    // if you made it this far return true because the strings are equal
    return true;
}

function getUpperCase(string) { 
    if (string != null && string != '')
	  return string.toUpperCase()
	else
	  return ''
} 

//this will strip out only the digits from the string
function getDigitsOnly(string)
{
	if (string == '' || string == null)
		return ''

	var tempstring = ''
	var tempcharcode
	var digitsiter = 0

	while (digitsiter < string.length)
	{
		tempcharcode = string.charCodeAt(digitsiter)
		if (tempcharcode > 47 && tempcharcode < 58)
		{
			tempstring = tempstring + string.charAt(digitsiter)
		}
		digitsiter++
	}
	return tempstring
}

function trimSpaces(string) {
  var str = string
  if (str == null) {return ''}
  while (str.charAt(0) == ' ')
    str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
    str = str.substring(0, str.length - 1);
  return str;
}


function getPhoneFormat(string)
{
	if (string == '' || string == null)
		return '' 
	string = getDigitsOnly(string)
	var area_code
	var part_1
	var part_2
	if (string.length >= 3) {
		area_code = string.substring(0, 3)
	}
	else
	{
		area_code = '000'
	}	
	if (string.length >= 6) {
		part_1 = string.substring(3, 6)
	}
	else
	{
		part_1 = '000'
	}
	if (string.length >= 10) {
		part_2 = string.substring(6, 10)
	}
	else
	{
		part_2 = '0000'
	}
	return '(' + area_code + ')' + part_1 + '-' + part_2
}

function getZipFormat(string)
{	
	if (string == '' || string == null)
		return '' 
	string = getDigitsOnly(string)
	var zip
	var part_1
	var part_2
	if (string.length > 9) {
		string = string.substring(0, 9)
	}
	
	if (string.length >= 5) {
		part_1 = string.substring(0, 5)
	}
	else
	{
		part_1 = '00000000'
	}	
	if (string.length >= 9) {
		part_2 = string.substring(5, 9)
	}
	else
	{
		part_2 = ''
	}

	zip = part_1
	if (part_2 != '')
	{
		zip = zip + '-' + part_2
	}
	return zip
}



function formatDollarValue(val) {
    var digits=getDigitsOnly(val);
    var numOfDigits=val.length;
    var indexOfDollarSign=val.indexOf('$');
 
    if (val.indexOf('$')!=-1) { val=val.substr(1, 100); }
 
    var indexOfDecimal=val.indexOf('.');
 
    if (digits.length==0) { digits="0"; }
 
    if (indexOfDecimal==-1) { return "$"+digits+".00"; }
 
    var value=digits.substr(0, indexOfDecimal);
    
    return "$"+value+"."+getDecimalValue(val);
 
}

function getFloatValue(string)
{
   var indexOfDecimal = string.indexOf('.')
   if (indexOfDecimal == -1)
   {
     return getDigitsOnly(string)+".00"
   }
   else
   {
     return getDigitsOnly(string.substring(0,indexOfDecimal))+"."+getDigitsOnly(string.substr(indexOfDecimal))
   }
}


 
function getDecimalValue(val) {
    var digits=getDigitsOnly(val);
    var numOfDigits=val.length;
    var indexOfDecimal=val.indexOf('.');
    var decimalValue="00";
 
    // no decimal was found
    if (indexOfDecimal==-1) {
        return decimalValue;
    }
 
    decimalValue=digits.substr(indexOfDecimal, 3);
 
    switch (decimalValue.length) {
    // the decimal was the first character
    case 0:
        decimalValue="00";
        break;
 
    case 1:
        decimalValue=decimalValue+"0";
        break;
 
    case 2:
        decimalValue=decimalValue;
        break;
 
    case 3:
//        decimalValue=String(Number(decimalValue)+5);
        decimalValue=decimalValue.substr(0, 2);
        break;
    default:
        decimalValue="00";
    }
 
    return decimalValue;
}




function formatPercent( val)
{
  if (val == '' || val == null) {
    return '';
  }
  val = getDigitsOnly( val)
  val += '%';
  
  return val;
}



function stripLeadingCharacter(string,character)
{

  while (string.indexOf(character) == 0 )
  {
    if (string.length > 1)
	{
	  string = string.substring(1,string.length)
	}
	else
	{
	  return ''
	}
  }
  return string
}

function tokenizeString(strValue, parseChar) {
    var iValueLength=strValue.length;
 var str=strValue, c=parseChar;
 var iIndex1=0, iIndex2=0, iElements=0;
 var rtnArray = new Array();
 
 while (iIndex2!=-1 && iIndex2<iValueLength) {
        iIndex2=str.indexOf(c, iIndex1);
  if (iIndex2!=-1) {
        rtnArray[iElements++]=str.substring(iIndex1, iIndex2);
  } else {
   rtnArray[iElements++]=str.substring(iIndex1, iValueLength);
  }
  iIndex1=iIndex2+1;
    }
 return rtnArray;
}

function computePercentage(pct) {
    var pctlength=pct.length;
 
    if (pctlength==0) {
        return -1;
    } else if (pct.substr(pctlength-1,1)=='%') {
        return (Number(pct.substr(0,pctlength-1))/100);
    }
    return -1;
}

function padNumberWithBeginningCharactersAndReturnString(inputNumberString, padcharacter, totalDesiredDigits, appendSign)
{
   number = inputNumberString;
   if (Number(number) > -1) {
     while (number.length < totalDesiredDigits){
      number = padcharacter + number;
     } 
     if (appendSign){
      number = "+" + number;
     }
   }
   else{
     tempString = ""+Number(number)*-1;
     while (tempString.length < totalDesiredDigits){
      tempString  = padcharacter + tempString;
     }
     number = tempString ; 
     if (appendSign){
      number = "-" + number;
     }
   }
   return number;
}


/*
function stripInvalidCharacters(string)
{
	if (string == '' || string == null)
		return ''

	var tempstring = ''
	var tempcharcode
	var i = 0

	while (i < string.length)
	{
		tempcharcode = string.charCodeAt(i)
		if (tempcharcode > 47 && tempcharcode < 58)
		{
			tempstring = tempstring + string.charAt(i)
		}
		i++
	}
	return tempstring
}
*/

//END UTIL_STRING FUNCTIONS


function _REFERENCE_UTIL_STRING_DATE_RELATED_FUNCTIONS()
{
//placeholder for all functions related to working with string PARAMETERS that deal with date-related logic
//-these are in a seperate area because there they are very interelated and represent a distinct category of
//string related functions
}


function validateDateFormat(dateVal, bDisplayMsg) {

	var iMonth=Number(dateVal.substr(0,2));
	var iDay=Number(dateVal.substr(3,2));
	var iYear=Number(dateVal.substr(6,4));
	
	if (iYear>0 && iYear<=79) {
	    iYear = iYear + 2000;
	}
	else if (iYear>79 && iYear<100) {
	    iYear = iYear + 1900;
	}

    var msg='Invalid date.';
    if (iMonth<1 || iMonth>12) {
	    if (bDisplayMsg) { alert(msg); }
		return false;
	}
	
	switch (iMonth) {
	case 1:
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	case 12:
	    if (iDay<1 || iDay>31) {
		   	if (bDisplayMsg) { alert(msg); }
			return false;
		}
	    break;
	case 4:
	case 6:
	case 9:
	case 11:
	    if (iDay<1 || iDay>30) {
		    if (bDisplayMsg) { alert(msg); }
			return false;
		}
	    break;
	case 2:
	    if ((iYear%400==0) || (iYear%100!=0 && iYear%4==0)) {
		    if (iDay<1 || iDay>29) {
			    if (bDisplayMsg) { alert(msg); }
			    return false;
			}
		}
		else {
		    if (iDay<1 || iDay>28) {
			    if (bDisplayMsg) { alert(msg); }
			    return false;
			}
		}
	    break;
	default:
	}

	if (iYear<1900 || iYear>2099) {
		if (bDisplayMsg) { alert(msg); }
		return false;
	}
	
    return true;

}

function addToDateString(startDateString, numDays, numMonths, numYears)
{
    var startDate = getDate(startDateString)
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	
	return parseDate(returnDate);

}

function getDate(val) {
    var iIndexOfSlash=String(val).indexOf('/');
    var iLastIndexOfSlash=String(val).lastIndexOf('/');
	if (iIndexOfSlash<=0 && iLastIndexOfSlash<=0) {
	    return null;
	}

	var iMonth=Number(String(val).substring(0,iIndexOfSlash));
	var iDay=Number(String(val).substring(iIndexOfSlash+1,iLastIndexOfSlash));
	var iYear=Number(String(val).substring(iLastIndexOfSlash+1));
	
	var dDate=new Date();
	dDate.setMonth(iMonth-1);
	dDate.setDate(iDay);
	dDate.setYear(iYear);
	dDate.setHours(0);
	dDate.setMinutes(0);
	dDate.setSeconds(0);
	
	return dDate;
}

function getDateFromString(val) {
/*
    var iIndexOfSlash=String(val).indexOf('/');
    var iLastIndexOfSlash=String(val).lastIndexOf('/');
	if (iIndexOfSlash<=0 && iLastIndexOfSlash<=0) {
	    return null;
	}

	var iMonth=Number(String(val).substring(0,iIndexOfSlash));
	var iDay=Number(String(val).substring(iIndexOfSlash+1,iLastIndexOfSlash));
	var iYear=Number(String(val).substring(iLastIndexOfSlash+1));
	
	var dDate=new Date();
	dDate.setMonth(iMonth-1);
	dDate.setDate(iDay);
	dDate.setYear(iYear);
	dDate.setHours(0);
	dDate.setMinutes(0);
	dDate.setSeconds(0);
	*/	
	return getDate(val)
}

function formatMonth(month) {
    if (Number(month)>=1 && Number(month)<=9) {
        return ('0'+Number(month));
    } else if (Number(month)>=10 && Number(month)<=12) {
        return month;
    } 
    return "";
}
 
function formatYear(year) {
    if (year=="") {
        return "";
    } else if (Number(year)>=0 && Number(year)<10) {
        return ("200"+Number(year));
    } else if (Number(year)>=10 && Number(year)<70) {
        return ("20"+Number(year));
    } else if (Number(year)>=70 && Number(year)<=99) {
        return ("19"+Number(year));
    } else if (Number(year)>=1970 && Number(year)<2069) {
        return year;
    }
    return "";
}

//The following function takes in a date in a string format, converts it to Date type
//and then compares it to today's date and displays confirm boxes if the date is today's
//date or is before today's date. If is confirmed, true, if not returns false.
function dateComparedConfirmed(date) {
  var tempDate = getDateFromString(date), todayDate = new Date();
  if (compareMonthDayYear(tempDate, todayDate)< 0){
  	if (confirm("The date you selected is expired. Proceed anyway?"))
		return true;
	else return false;
  }
  else if (compareMonthDayYear(tempDate, todayDate)== 0){
	if (confirm("The date you selected expires today. Proceed anyway?"))
		return true;
	else return false;
  }
  else 
     return true;
}
//END STRING DATE RELATED FUNCTIONS



function _REFERENCE_UTIL_STRING_DR_FUNCTIONS()
{
//placeholder for all functions related to working with string PARAMETERS
//that are specific to Direct Return logic 
}

function getDEAFormat(dea)
{
   var string = dea
   string = trimSpaces(dea)
   if(string == null || string.length != 9)
   {
     alert("Please enter a DEA number that is 9 characters long \nand begins follows the XY0000000 format (X = characters, Y = characters or digits, 0 = digits ).");
	 return ''
   }
   string = string.toUpperCase()
 
   var i = 0;
   var assocDea = String(string);
   var charCount = 0;
   var charval;
   
   charval = string.charCodeAt(0)
   if (!(charval >= 65 && charval <= 90)) {
     alert("Please enter a DEA number that is 9 characters long \nand begins follows the XY0000000 format (X = characters, Y = characters or digits, 0 = digits ).");
	 return ''
   }
   
   charval = string.charCodeAt(1)
   if (!(charval >= 65 && charval <= 90) && !(charval >= 48 && charval <= 57)) {
     alert("Please enter a DEA number that is 9 characters long \nand begins follows the XY0000000 format (X = characters, Y = characters or digits, 0 = digits ).");
	 return ''
   }
   
   var iPos1 = assocDea.substr(2,1);
   var iPos2 = assocDea.substr(3,1);
   var iPos3 = assocDea.substr(4,1);
   var iPos4 = assocDea.substr(5,1);
   var iPos5 = assocDea.substr(6,1);
   var iPos6 = assocDea.substr(7,1);
   var iPos7 = assocDea.substr(8,1);

   var iGroup1 = Number(iPos1) + Number(iPos3) + Number(iPos5);
   var iGroup2 = Number(iPos2) + Number(iPos4) + Number(iPos6);

   var iTotal = Number(iGroup1) + (2 * Number(iGroup2));

   var sTotal = String(iTotal);

   if (sTotal.length == 1) {
    if (sTotal.charCodeAt(0) != String(iPos7).charCodeAt(0)) {
 	   alert("Please enter a valid\nAssociated Registrant Number");
       return ''
    }
   }
   else if (sTotal.length == 2) {
	if (sTotal.charCodeAt(1) != String(iPos7).charCodeAt(0)) {
        alert("Please enter a valid\nAssociated Registrant Number");
        return ''
	}
   }
   else if (sTotal.length == 3) {
	if (sTotal.charCodeAt(2) != String(iPos7).charCodeAt(0)) {
    	alert("Please enter a valid\nAssociated Registrant Number");
        return ''
	}
   } 
   else {
	alert("Please enter a valid\nAssociated Registrant Number");
    return ''
   }
   return assocDea
}

function formatNdcUpcForSearch(string){
	if (string == '' || string == null)
		return ''
	var tempstring = ''
	var tempcharcode
	var digitsiter = 0
	while (digitsiter < string.length)
	{
		tempcharcode = string.charCodeAt(digitsiter)
		if ((tempcharcode > 47 && tempcharcode < 58) || tempcharcode == 45)
		{
			tempstring = tempstring + string.charAt(digitsiter)
		}
		digitsiter++
	}
	return tempstring
}

function formatNdc(ndc_num)
{
  if (ndc_num == null || ndc_num == '')
  {
    return '';
  }
  
  ndc_num = getDigitsOnly(ndc_num)
  if (ndc_num.length < 6)
  {
    return ndc_num
  }
  ndc1 = ndc_num.substring(0,ndc_num.length-6)
  ndc2 = ndc_num.substring(ndc_num.length-6,ndc_num.length-2)
  ndc3 = ndc_num.substring(ndc_num.length-2,ndc_num.length)
  while (ndc1.length < 5)
  {
    ndc1 = "0" + ndc1;
  }
  return ndc1 + "-" + ndc2 + "-" + ndc3;
}

function formatUpc(ndc_num)
{
  if (ndc_num == null || ndc_num == '')
  {
    return '';
  }
  
  ndc_num = getDigitsOnly(ndc_num)
  if (ndc_num.length < 6)
  {
    return ndc_num
  }
  ndc1 = ndc_num.substring(0,ndc_num.length-6)
  ndc2 = ndc_num.substring(ndc_num.length-6)
  while (ndc1.length < 5)
  {
    ndc1 = "0" + ndc1;
  }
  return ndc1 + "-" + ndc2 
}

//END UTIL_STRING DR FUNCTIONS

function _REFERENCE_UTIL_DATE_FUNCTIONS()
{
//placeholder for all functions related to working with Date PARAMETERS
//(meaning some of these functions returns things other than dates - like strings, booleans, etc) 
}


function parseDate(date) {
    var month="";
	var day="";

	month=String(date.getMonth()+1);
	if (date.getMonth()<10) {
	    month="0"+month;
	}
	day=String(date.getDate());
	if (date.getDate()<10) {
	    day="0"+day;
	}

    return month + "/" + day + "/" + String(date.getFullYear());

}

// Compares the two Gregorian Calendar dates based on the month, day and year
// of each. 
// return -1 if date1<date2, 0 if date1==date2, 1 if date1>date2
function compareMonthDayYear(date1, date2) {

	if (date1==null || date2==null) {
		return -2;
	}
	var month1 = date1.getMonth();
	var day1 = date1.getDate();
	var year1 = date1.getYear();

	var month2 = date2.getMonth();
	var day2 = date2.getDate();
	var year2 = date2.getYear();

	// if year1 < year2 than date1 has to be earlier than date2 so return -1
	if (year1 < year2) {
		return -1;
	// otherwise if year1 > year2 than date1 has to be later than date2 so return 1
	} else if (year1 > year2) {
		return 1;
	// otherwise the years are the same
	} else {
		// so check the months of each date
		// if month1 < month2 then date1 is earlier than date2 so return -1
		if (month1 < month2) {
			return -1;
		// otherwise if month1 > month2 then date1 is later than date2 so return 1
		} else if (month1 > month2) {
			return 1;
		// otherwise the months are equal so return 0
		} else {
			// so check the days of each date
			// if day1 < day2 then date1 is earlier than date2 so return -1
			if (day1 < day2) {
				return -1;
			// otherwise if day1 > day2 then date1 is later than date2 so return 1
			} else if (day1 > day2) {
				return 1;
			// otherwise the days are equal so return 0
			} else {
				return 0;
			}
		}
	}
}

//END UTIL_DATE FUNCTIONS

function _REFERENCE_UTIL_ARRAY_FUNCTIONS()
{
//placeholder for all functions related to working with Array PARAMETERS
//(meaning some of these functions returns things other than Arrays - like strings, booleans, etc) 
}

function addElementToArray(aArray, element, unique_elements_only) {
    if (aArray == null) {
	    aArray = new Array();
	}
	
	var element_in_array = false;
	if (unique_elements_only) {
	    // first verify that the item isn't already in the array
	    for (var i=0; i<aArray.length; i++) {
			if (compareStrings(String(element), String(aArray[i]))) {
				element_in_array = true;
				break;
			}
		}
	}
	
	if (!element_in_array) {
		aArray[aArray.length] = String(element);
	}
	
	return aArray;
}

function removeElementFromArray(aArray, element) {
    if (aArray == null) {
		return null;
	}
	
	var iArrayLength = aArray.length;
	var i = 0;
	while (i < iArrayLength) {
	    // if the element exists in the array...
		if (compareStrings(String(element), String(aArray[i]))) {
			// then remove it
			aArray[i] = null;
			
			// and then shrink the array down
			for (var j=i; j<iArrayLength-1; j++) {
				aArray[j]=aArray[j+1];
			}
			iArrayLength = iArrayLength-1;
		    aArray.length = iArrayLength;
		} else {
			i = i + 1;
		}
	}

	return aArray;
}

function getListOfArrayElementsUsingSeparator(aArray, separator) {
	return aArray.join(separator);
}
//END UTIL_ARRAY FUNCTIONS


function _REFERENCE_RESULTGRID_SORT_CONTROLS()
{
//placeholder for all functions related to dealing with result-grid manipulation
}

function orderBySpecificSubmit(form, column, direction, action) {

     /*
	  alert("old column: "+form.order_by.value);
	  alert("new column: "+column);
	  alert("sort direction: "+form.sort_direction.value);
	 */
    if (form.order_by.value == column)
    {
  
	  if (form.sort_direction.value == '2')
	  {
          form.sort_direction.value = '1';
	  }
	  else
	  {
	      form.sort_direction.value = '2';
	  }		
    }
    else
    {
	  form.order_by.value = column;
	  if (direction != null)
	  {
	     form.sort_direction.value = direction;
	  }
	  else
	  {
	     form.sort_direction.value = '2';
	  }
    }
	

    if (action != null)
    {
	form.action.value=action;
    }
	//alert('submit:sort direction ' + form.sort_direction.value+':order by:' +form.order_by.value )
    form.submit();
}

function orderByWithAction(form,column, action) {
  orderBySpecificSubmit(form, column, null, action) 
} 

function orderBySubmit(form, column)
{
	orderBySpecificSubmit(form,column,null,'sort_by');

}

//END RESULTGRID_SORT FUNCTIONS

function _ACTIVEX_UTIL_FUNCTIONS(){
//placeholder for activeX control utility functions
}

function IEDetectObject(ClassID)
{
	var agt = navigator.userAgent.toLowerCase();
	var win = ((agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1));
	var ie  = (agt.indexOf("msie") != -1);
	result = false;
	// Internet explorer on windows
	if (ie && win)
	{
		document.write('<SCRIPT LANGUAGE=VBScript\> \n');
		document.write('on error resume next \n');
		document.write('result = IsObject(CreateObject("' + ClassID + '")) \n');
		document.write('</SCRIPT\> \n');
	}
	return result;
}
