// Common JScript routines

// Little hack for IE4 since it is not W3C DOM Level 1 compliant
function document_getElementById(id)
{
  return document.all[id]
}

if (document.all && !document.getElementById)
{
  document.getElementById = document_getElementById
}

// Use this function to find all objects, this hides any browser version differences
function getElementById(idName)
{
    return document.getElementById(idName);
}

// DK, 24/05/02 - IE4 javascript doesn't support full array functionality
function Array_push(item) {
  this[this.length] = item;
}
//
if (!Array.prototype.push) {
  Array.prototype.push = Array_push
}

// see if a button is enabled
function isEnabled(butId)
{
    return !(getButtonById(butId).disabled);
}

function showStaticPage(pageUrl)
{
    var url = "Dispatcher.asp?Web.Command=Static/StaticView.asp&page=" + pageUrl;
    window.location.assign( url );
}

function doNothing()
{
}

// The following cryptically named functions are used for select-all
ie = document.all?1:0;

function CA()
{
	var lAllboxChecked = document.frm.allbox.checked;
	var lElements;

	if (ie && !document.bMac)
	{
		lElements = document.frm.tags('INPUT');
	}
	else
	{
		lElements = document.frm.elements;
	}

    for (var i=0;i<lElements.length;i++)
    {
        var e = lElements[i];
        if (e.type == 'checkbox')
        {
        	if (!(e.name == 'allbox' || e.id == 'allbox'))
        	{
	            e.checked = lAllboxChecked;
	            if (lAllboxChecked)
	                hL(e);
	            else
	                dL(e);
	        }
        }
    }

}

function CCA(CB)
{
    if (CB.checked)
        hL(CB);
    else
        dL(CB);

    var TB=TO=0;
	var lElements;
	if (ie && !document.bMac)
	{
		lElements = document.frm.tags('INPUT');
	}
	else
	{
		lElements = document.frm.elements;
	}

    for (var i=0;i<lElements.length;i++)
    {
        var e = lElements[i];
        if (e.type == 'checkbox')
        {
        	if (!(e.name == 'allbox' || e.id == 'allbox'))
        	{
	            TB++;
	            if (e.checked)
	                TO++;
			}
        }
    }
    if (document.frm.allbox)
    {
	    document.frm.allbox.checked = (TO==TB);
	}
}

function hL(E)
{
    if (ie)
    {
        while (E.tagName!="TR")
            {E=E.parentElement;}
    }
    else
    {
        while (E.tagName!="TR")
            {E=E.parentNode;}
    }
    E.className = "H";
}

function dL(E)
{
    if (ie)
    {
        while (E.tagName!="TR")
            {E=E.parentElement;}
    }
    else
    {
        while (E.tagName!="TR")
            {E=E.parentNode;}
    }
    E.className = "";
}

// Set page title after the fact
function setPageTitle( newTitle, htmlTitle )
{
  document.title = newTitle;
  if( htmlTitle )
  {
    document.getElementById("pageTitle").innerHTML = htmlTitle;
  }
  else
  {
    document.getElementById("pageTitle").innerHTML = newTitle;
  }
}

//*****************************************************************************
//* Assert next 'Web Command' and associated 'Action Type'.
//*****************************************************************************
function SetWebCommand(pForm, pWebCommand, pAction, pDoNotSubmit)
{
	//*************************************************************************
	//* Assert the 'Web Command' and 'ActionType' details, prior to form
	//* submission.
	//*************************************************************************
	pForm['Web.Command'].value = pWebCommand;
	if (pAction != null)
	{
		pForm['ActionType'].value = pAction;
	}
	if (!pDoNotSubmit)
	{
	    pForm.submit();
	}
}

//*****************************************************************************
//* Display/hide exclamation mark on mandatory fields dependent upon
//* absence/presence of data, respectively.
//*****************************************************************************
function MandatoryField(pField)
{
	var lMandatoryFlag = getElementById(pField.name + 'MandatoryFlag');
	if (pField.value == '')
	{
		lMandatoryFlag.style.visibility = 'visible';
	}
	else
	{
	    var lVisibilty = 'hidden';
	    //Validate the data based on the DataType tag
        for (var lIndex = 0; lIndex < document.forms.length; lIndex++)
        {
    	    if (document.forms[lIndex][pField.name + 'DataType'])
    	    {
    	        //There is a data type, so validate the value against it
    	        var lDataType = document.forms[lIndex][pField.name + 'DataType'].value;
    	        var lFieldVal = pField.value;
    	        var re = /\'/;
    	        lFieldVal = lFieldVal.replace(re, "\\\'");
       	        var lEval = 'var lIsValid = is' + lDataType + '(\'' + lFieldVal + '\');'
    	        eval(lEval);
    	        if (!lIsValid)
    	        {
    	            lVisibilty = 'visible';
    	        }
    	    }
    	    break;
    	}
	    
		lMandatoryFlag.style.visibility = lVisibilty;
	}
}

// Name:  isCardinal
// Description:  Uses regular expressions to match a
//               positive integer >= 0
function isCardinal( value )
{
	var isCardinalRE = /^[0-9]*$/;
	return (isCardinalRE.test( value ));
}

// Name:  isNonZeroCardinal
// Description:  Uses regular expressions to match a
//               positive integer > 0
function isNonZeroCardinal( value )
{
	var isCardinalRE = /^[1-9][0-9]*$/;
	return (isCardinalRE.test( value ));
}

// Name:  isPositiveNumber
// Description:  Uses regular expressions to match a
//               positive number > 0
function isPositiveNumber( value )
{
	var PositiveNumberRE = /^\d\d*$|^\d\d*\.\d\d*$|^\.\d\d*$/;
	return (PositiveNumberRE.test( value ));
}

function isMoney( pVal )
{
	var re = /^\d\d*$|^\d\d*.\d{1,2}$/;

  // Test the existance of the regular expression.
	return (re.test(pVal));
}
// Name:  isDecimalNumber
// Description:  Uses regular expressions to match a
//               decimal numbers e.g. 3.0 3 3.01 etc
function isDecimalNumber( value )
{
	var DecimalNumberRE = /\d{0,10}(\.\d{1,5})?/;
	return (DecimalNumberRE.test( value ));
}

// Name:  isMail
// Description:  Uses regular expressions to match a valid email address.
//
function isMail(pVal)
{
  var lAddr = /^(\S+)\@((\w)+\.)+(\w{2,4})+$/;

  return lAddr.test(pVal)
}

//*****************************************************************************
//* Fire the default button on receipt of a carriage return.
//*****************************************************************************
function CheckForRet(event, pDefaultButton)
{
	//*************************************************************************
	//* Check for carriage returns.
	//*************************************************************************
	if (event.keyCode == 13)
	{
		//*********************************************************************
		//* Locate the default button via its Id, find the embedded
		//* 'Web Command' and run it.
		//*
		//* NOTE  Copes with "graphical" or "non-graphical" interface modes.
		//* ====  "Graphical" mode uses <a> tags, whilst "non-graphical" mode
		//*       uses <input> tags.
		//*********************************************************************
		var lButton = getButtonById(pDefaultButton);
		if (typeof(lButton.href) == 'undefined')
		{
			lButton.click();
		}
		else
		{
			location.href = lButton.href;
		    event.returnValue = false;
		}
	}
}

//*****************************************************************************
//* For all mandatory fields, display/hide the mandatory flag dependent upon
//* whether data is absent/present, respectively.
//*****************************************************************************
function SetMandatoryFieldStates(pForm, pForceInspection)
{
	//*************************************************************************
	//* Locate all potential mandatory field flags.
	//*************************************************************************
	var lMandatoryFields = document.images;
	for (var lFieldIndex = 0;
			 lFieldIndex < lMandatoryFields.length;
			 lFieldIndex++)
	{
		//*********************************************************************
		//* Determine whether the signatures match.
		//*********************************************************************
		var lMandatoryField = lMandatoryFields[lFieldIndex];
		var lSignature = 'MandatoryFlag';
		var lSignatureOffset = lMandatoryField.id.length - lSignature.length;
		if (lSignatureOffset > 0 &&
			lMandatoryField.id.substr(lSignatureOffset) == lSignature)
		{
			//*****************************************************************
			//* Only attempt to inspect associated data, if the field is
			//* actually visible.
			//*****************************************************************
			if (lMandatoryField.style.visibility == 'visible' ||
			    lMandatoryField.style.visibility == '' ||
			    pForceInspection)
			{
				//*************************************************************
				//* Display/hide the mandatory flag dependent upon whether
				//* data is absent/present, respectively.
				//*************************************************************
				var lDataFieldName  = lMandatoryField.id.substr(0, lSignatureOffset);
				var lDataFieldValue = pForm[lDataFieldName].value;
				if (lDataFieldValue == '')
				{
					lVisibilty = 'visible';
				}
				else
				{
				    lVisibilty = 'hidden';
            	    //Validate the data based on the DataType tag
            	    for (var lIndex = 0; lIndex < document.forms.length; lIndex++)
            	    {
                	    if (document.forms[lIndex][lDataFieldName + 'DataType'])
                	    {
                	        //There is a data type, so validate the value against it
                	        var lDataType = document.forms[lIndex][lDataFieldName + 'DataType'].value;
                	        var lFieldVal = lDataFieldValue;
                	        var re = /\'/;
                	        lFieldVal = lFieldVal.replace(re, "\\\'");
                   	        var lEval = 'var lIsValid = is' + lDataType + '(\'' + lFieldVal + '\');'
                	        eval(lEval);
                	        if (!lIsValid)
                	        {
                	            lVisibilty = 'visible';
                	        }
                	    }
                	    break;
                	}
				}
				// Only change DOM if different to avoid flicker
				if (lMandatoryField.style.visibility != lVisibilty)
				    lMandatoryField.style.visibility = lVisibilty;
			}
		}
	}
}

//*****************************************************************************
//* Disable the specified button if any mandatory fields are still outstanding.
//*****************************************************************************
function CheckAllMandatoryFieldsCompleted(pForm, pButtonName)
{
	//*************************************************************************
	//* Locate all potential mandatory field flags.
	//*************************************************************************
	var lDisableButton = false;
	var lMandatoryFields = document.images;
	for (var lFieldIndex = 0;
			 lFieldIndex < lMandatoryFields.length;
			 lFieldIndex++)
	{
		//*********************************************************************
		//* Determine whether the signatures match.
		//*********************************************************************
		var lMandatoryField = lMandatoryFields[lFieldIndex];
		var lSignature = 'MandatoryFlag';
		var lSignatureOffset = lMandatoryField.id.length - lSignature.length;
		if (lSignatureOffset > 0 &&
			lMandatoryField.id.substr(lSignatureOffset) == lSignature)
		{
			//*****************************************************************
			//* If any mandatory flag is visible, then disable the specified
			//* button.
			//*****************************************************************
			if (lMandatoryField.style.visibility == 'visible')
			{
				lDisableButton = true;
				break;
			}
		}
	}

	//*************************************************************************
	//* Disable the button if any mandatory fields are still outstanding.
	//*************************************************************************
	setButtonState(pButtonName, lDisableButton);

	//*************************************************************************
	//* Indicate whether any mandatory fields are still outstanding.
	//*************************************************************************
	return(lDisableButton);
}

//*****************************************************************************
//* Enable or Disable the specified button
//*****************************************************************************
function setButtonState(pButtonName, pDisableFlag)
{
	var lButton = getButtonById(pButtonName);
    if (lButton)
    {
    	var newClass = pDisableFlag ? "buttonVoid" : "button";

        // Only change DOM if different to avoid flicker
    	if(lButton.disabled != pDisableFlag) lButton.disabled  = pDisableFlag;
    	if (lButton.className != newClass)   lButton.className = newClass
    }
    else
    {
        // flag warning, probably a development oversight
        alert("Tried to disable button '" + pButtonName + "', but button of that name not found.\n Are you sure you pass an Id pararmeter to the GenericButton sub?")
    }
}


//*****************************************************************************
//* Disable the specified button if any fields still contain invalid data.
//*****************************************************************************
function CheckNoInvalidFieldsOutstanding(pForm, pButtonName)
{
	//*************************************************************************
	//* Determine whether any mandatory fields are still outstanding - if there
	//* are, then don't bother checking invalid fields as the button should
	//* remain greyed.
	//*************************************************************************
	if (!CheckAllMandatoryFieldsCompleted(pForm, pButtonName))
	{
		//*********************************************************************
		//* Locate all potential invalid field flags.
		//*********************************************************************
		var lDisableButton = false;
		var lInvalidFields = document.images;
		for (var lFieldIndex = 0;
				 lFieldIndex < lInvalidFields.length;
				 lFieldIndex++)
		{
			//*****************************************************************
			//* Determine whether the signatures match.
			//*****************************************************************
			var lInvalidField = lInvalidFields[lFieldIndex];
			var lSignature = 'Invalid';
			var lSignatureOffset = lInvalidField.id.length - lSignature.length;
			if (lSignatureOffset > 0 &&
				lInvalidField.id.substr(lSignatureOffset) == lSignature)
			{
				//*************************************************************
				//* If any invalid flag is visible, then disable the specified
				//* button.
				//*************************************************************
				if (lInvalidField.style.visibility == 'visible')
				{
					lDisableButton = true;
					break;
				}
			}
		}

		//*********************************************************************
		//* Disable the button if any invalid fields are still outstanding.
		//*********************************************************************
	    setButtonState(pButtonName, lDisableButton);
	}
}

//*****************************************************************************
//* submit a form from an href
//*****************************************************************************
function formSubmit( pForm )
{
    //use the form's submit handler to submit the form
    pForm.onsubmit();
}
//*****************************************************************************
//* SELECT element option wrappers
//*****************************************************************************
function AppendOption(pTarget, pNewOption)
{
	//*************************************************************************
	//*
	//*************************************************************************
	if (ie)
	{
		pTarget.add(pNewOption);
	}
	else
	{
		var lLastElement = pTarget.length;
		pTarget.options[lLastElement] = pNewOption;
	}
}

//*****************************************************************************
//*
//*****************************************************************************
function RemoveOption(pTarget, pIndex)
{
    if (ie)
    {
		pTarget.options.remove(pIndex);
	}
	else
	{
		pTarget.options[pIndex] = null;
	}
}
//*****************************************************************************
//*
//*****************************************************************************
function RemoveAllOptions(pTarget)
{
    var optionsLength = pTarget.options.length;

    for (var i = 1; i <= optionsLength; i++)
    {
        RemoveOption(pTarget, 0);
    }
}
//*****************************************************************************
//*
//*****************************************************************************
function outputDebugString(debugText)
{
    var outputDiv = document.getElementById("DebugDiv");
    if (outputDiv)
    {
        outputDiv.innerText = outputDiv.innerText + "\n" + debugText;
    }
}

//*****************************************************************************
//* Simulate MAXLENGTH attribute on <TEXTAREA> elements.
//*****************************************************************************
function TruncateTextAreaData(pField, pMaxLength)
{
	if (pField.value.length > pMaxLength)
	{
		pField.value = pField.value.substring(0, pMaxLength);
	}
}

//*****************************************************************************
//*
//*****************************************************************************
function AddDecimalPoint(pPrice)
{
	var lFormattedPrice = pPrice + "";
	var lDecimalPointOffset = lFormattedPrice.length - lFormattedPrice.indexOf('.');

	if (lDecimalPointOffset == (lFormattedPrice.length + 1))
	{
		lFormattedPrice += ".00";
	}
	else
	{
		switch(lDecimalPointOffset)
		{
			case 1:	lFormattedPrice += "00";
					break;
			case 2:	lFormattedPrice += "0";
					break;
			case 3:	break;
			default:	lFormattedPrice = lFormattedPrice.substring(0, lFormattedPrice.length - lDecimalPointOffset + 3) ;
					break;
		}
	}
	return lFormattedPrice;
}

//*****************************************************************************
//* Enable/disable list of buttons when an element has been
//* selected/deselected, respectively.
//*****************************************************************************
function EnableButtonsWhenElementSelected(pButtonList)
{
	//*************************************************************************
	//* Determine whether 1 or more Elements have been selected.
	//*************************************************************************
	var lAnySelected = false;
    for (var lElementIndex = 0;
    		 lElementIndex < document.frm.elements.length;
    		 lElementIndex++)
    {
		//*********************************************************************
		//* Locate all checkbox elements.
		//*********************************************************************
        var lElement = document.frm.elements[lElementIndex];
        if (lElement.type.toLowerCase() == 'checkbox' &&
            lElement.id.toLowerCase()   != 'allbox')
        {
        	if (lElement.checked)
        	{
        		lAnySelected = true;
        		break;
        	}
        }
    }

	//*************************************************************************
	//* Prepare to loop through the button list.
	//*************************************************************************
    for (var lButtonIndex = 0;
    		 lButtonIndex < pButtonList.length;
    		 lButtonIndex++)
    {
		//*********************************************************************
		//* Disable the button if no Element has been selected.
		//*********************************************************************
	    setButtonState(pButtonList[lButtonIndex], !lAnySelected);
	}
}


function IsDateValid(pCtrlName, pTarget)
{
  var lDay   = getElementById('DD_' + pCtrlName).value;
  var lMonth = getElementById('MM_' + pCtrlName).value -1;
  var lYear  = getElementById('YY_' + pCtrlName).value;
	var lErrorDetected = false;

  if (lDay > -1 && lMonth > -1 && lYear > -1)
	{
		var lKeyedDate = new Date(lYear, lMonth, lDay, 0, 0, 0, 0);
		lErrorDetected = (lKeyedDate.getDate() != lDay);
	}

	if (lErrorDetected)
	{
    getElementById(pTarget).style.visibility = 'visible';
		pCtrlName = '';
	}
	else
	{
    getElementById(pTarget).style.visibility = 'hidden';
		pCtrlName = lYear + '-' + lMonth + '-' + lDay;
	}
}

function FilterNumber(pEvent)
{
	//*************************************************************************
	//* Cope with differences between IE and NS.
	//*************************************************************************
	var lKey;
	if (ie)
	{
		lKey = pEvent.keyCode;
	}
	else
	{
		lKey = pEvent.which;
	}

	//*************************************************************************
	//* Only allow numeric characters and edit actions.
	//*************************************************************************
	var lContinue = true;
	if (lKey >= 48 && lKey <=57)
	{
	//Allow 0 to 9
	}
	else
	{
		switch(lKey)
	    {
	        //Allow BackSpace, Tab, Linefeed, Carriage Return respectively
			case 0:
			case 8:
			case 9:
			case 10:
			case 13:
	  			break;

			default:
				lContinue = false;
				pEvent.returnValue=false;
		        break;
	    }
	}

	//*************************************************************************
	//* Indicate whether to allow the key press action.
	//*************************************************************************
	return(lContinue);
}

//*****************************************************************************
//* Select the listbox entry whose raw data value matches that specified.
//*****************************************************************************
function UpdateListboxSelection(pFieldId, pCurrentRawDataValue)
{
	//*************************************************************************
	//* Loop through all raw listbox data values attempting to find a match.
	//*************************************************************************
	var lField = getElementById(pFieldId);
	if (lField.tagName == 'SELECT')
	{
		var lListboxIds = lField.options;
		for (var lEntryIndex = 0;
				 lEntryIndex < lListboxIds.length;
				 lEntryIndex++)
		{
			if (lListboxIds[lEntryIndex].value == pCurrentRawDataValue)
			{
				lField.selectedIndex = lEntryIndex;
				break;
			}
		}
	}
}

//*****************************************************************************
//* Confirm deletion of SubSheet/AI/Highlight/Group/Customer.
//*****************************************************************************
function ConfirmDelete(pIdentity)
{
    return(confirm('Please confirm ' + pIdentity + ' deletion.\n' +
                   'Click Ok to continue.\n'));
}
