/* $Header: validateForm.js,v 1.26 2002/11/09 22:38:22 salims Exp $
   $Log:	validateForm.js,v $
#  Revision 1.26  2002/11/09  22:38:22  22:38:22  salims ()
#  check for english character is commented.
#  
#  Revision 1.25  2002/10/31  14:50:02  14:50:02  hskocher ()
#  Fixed date validation bug.
#  
#  Revision 1.24  2002/10/08  21:19:13  21:19:13  hskocher ()
#  Userd Math.round function for rounding numbers in stead of parseInt (this was
#  iling in case of long no.).                                                 
#  
#  Revision 1.23  2002/10/07  21:55:50  21:55:50  hskocher ()
#  Chnaged phone validation function.
#  
#  Revision 1.22  2002/10/07  00:11:43  00:11:43  hskocher ()
#  Added check if focusField == null then set focusField in case of error.
#  
#  Revision 1.21  2002/10/06  20:40:44  20:40:44  hskocher ()
#  Added check for focusField.type not equal to null.
#  
#  Revision 1.20  2002/10/04  01:07:36  01:07:36  hskocher ()
#  Changed validateForm function, removed special handling of layers of invoice.jsp.
#  
#  Revision 1.19  2002/10/02  16:23:01  16:23:01  hskocher ()
#  Shifted common function to this file.
#  
#  Revision 1.18  2002/09/27  13:31:50  13:31:50  samirh ()
#   removed extra spaces between message words
#  
#  Revision 1.17  2002/09/25  22:33:27  22:33:27  hskocher ()
#  Fixed bug.
#  
#  Revision 1.16  2002/09/25  15:00:55  15:00:55  priyan (Priya_nupoor)
#   multilingual changes 
#  
#  Revision 1.15  2002/09/23  21:14:19  21:14:19  hskocher ()
#  No validation if country not present in postcode list.
#  
#  Revision 1.6  2002/08/21  12:19:52  12:19:52  samirh ()
#  *** empty log message ***
#  
*/

// Validate a form in a general way

var def_validateForm    ="1.0";           // For setting the array for validated Fields
var validateMethods     = new Array();// Associative array matching format types to validation methods
var elementTypes        = new Array();// Associative array matching format types for validation of "Commercial Invoice" on "submit"
var splElementType        = new Array();
var dependentFields     = new Array();// Binds dependent fields for validation.
var addCheckTypes       = new Array();// Associative array matching format types for validation on click of "ADD"
var performaElementType = new Array();// Associative array matching format types for validation of "Perforna Invoice" on "submit"
var errorList  = new Array();        // Holds the specific errors
var errorOrder = new Array();       // Holds the order of the errors
var alertMethod     = "";           // Function that takes a title, text, width and height and alerts user
var alertMIME       = "text";         // Tells us what format the alertMethod can handle (text|html)
var alertWidth      = 350;           // Width of alert box with alertMethod
var alertExtraLines = 3;        // Lines to add to number in error message
var alertLineHeight = 25;       // Height to multiply total lines by to get alert height
var alertExtraLine  = 20;        // Characters of error message that generate extra line
var mandatoryEmptyType  = "mandempty";
var inputType = "notsinglebyte";
var noStateError = comm_msg039 + accreq_msg006;
var strErrMess = "";
var focusField = null;
var EMPTY_STRING = "";
var blankmark = "---";

function makeError()
{
  return strErrMess
}

function addValidateMethod( formatType, validateMethodName, messageMethodName, formatErrorTitle )
{
  validateMethods[formatType] = new Array( validateMethodName, messageMethodName, formatErrorTitle );
}

function addElementType( elementName, mandatory, humanName, formatType )
{
  if( typeof( elementName ) == "undefined" ) return;
  if( typeof( mandatory )  == "undefined" ) mandatory  = false;
  if( typeof( humanName )  == "undefined" ) humanName  = "";
  if( typeof( formatType ) == "undefined" ) formatType = "";
  elementTypes[elementName] = new Array( mandatory, humanName, formatType );
}

function bindDependentFields(master, slave)
{
  if( typeof( master )  == "undefined" ) mandatory  = false;
  if( typeof( slave )  == "undefined" ) mandatory  = false;
  dependentFields[slave] = master;
}

/*
    Description : This creats an arry for empty field validation on click of "ADD"
*/
function addCheckElementType( elementName, mandatory, humanName, formatType )
{
    if( typeof( elementName ) == "undefined" ) return;
    if( typeof( mandatory )  == "undefined" ) mandatory  = false;
    if( typeof( humanName )  == "undefined" ) humanName  = "";
    if( typeof( formatType ) == "undefined" ) formatType = "";
    splElementType[elementName] = new Array( mandatory, humanName, formatType );
}

/*
    Description : This Validates if any mandatory field is left blank on submit of "Commercial Invoice"
*/
function validateFormDropOff( form )
{
  if( typeof( form ) == "undefined" ) form = document.forms[0];
  errorString = "";
  if( form.country.type=="select-one" && form.country.selectedIndex == 0 )
  {
    errorString = errorString + "<br />" + comm_msg027;
  }
  if( errorString != "" )
  {
    dhlAlert( comm_msg047, errorStart + "<br />" + errorString );
    return false;
  }
  var zipFlag = true;
  if( form.zip.value == "" )
  {
    zipFlag = false;
  }
  var cityFlag = true;
  if( form.city.value == "" )
  {
    cityFlag = false;
  }
  var stateFlag = true;
  if( form.state.value == "" )
  {
    stateFlag = false;
  }
  if ( zipFlag == false && cityFlag == false )
  {
     errorString = errorString + "<br />" + comm_msg039 + validForm_msg001;
    errorString = errorString + "<br />" + comm_msg039 + comm_msg028;
  }
  if( errorString != "" )
  {
    dhlAlert( comm_msg047, comm_msg030 + "\n" + "<br />" + errorString );
    return false;
  }
if( form.country.type=="select-one" )
{
  if ( !postcode_checkFormat( form.country[form.country.selectedIndex].value, form.zip.value ) )
  {
      errorString = pcode_makeError();
      dhlAlert( comm_msg047, "" + "<br />" + errorString );
      return false;
  }
}
else if (form.origCountryCode.type=="hidden" )
{
  if ( !postcode_checkFormat( form.origCountryCode.value, form.origPostcode.value ) )
  {
      errorString = pcode_makeError();
      dhlAlert( comm_msg047, "" + "<br />" + errorString );
      return false;
  } 
}
  setCookies( form )
  return true;
}

function validateForm( form, isSplList )
{
    var theForm;
    
    focusField = null;

    if (typeof(isSplList) == "undefined")
    {
        isSplList = false;
    }

    if ( typeof( form ) == 'undefined' )
    {
        theForm = document.forms[0];
    }
    else
    {
        theForm = document.forms[form];
    }

    errorList = new Array();
    errorOrder = new Array();

  el = 0;

  while( theForm.elements[el] )
  {
    element = theForm.elements[el];
    elementName = element.name;
    if( element.type == "radio" )
    {
      if( element != theForm.elements[element.name][0] )
      {
        el++;
        continue;
      }
    }
    if( (elementTypes[elementName] && !isSplList) || (splElementType[elementName] && isSplList))
    {
      if (splElementType[elementName] && isSplList)
      {
          elementType = splElementType[elementName];
      }
      else
      {
          elementType = elementTypes[elementName];
      }
      elementValue = element.value;
      if( isMandatoryEmpty( elementType[0], element ) )
      {
        if (focusField == null)
        {
            focusField = element;
        }
        addError( mandatoryEmptyType, comm_msg025, comm_msg026, elementType[1] );
      }
      else if( elementValue != "" && elementType[2] != "" && validateMethods[elementType[2]] )
      {
        valid = eval( validateMethods[elementType[2]][0] + "( elementValue, element )" );
        if( !valid )
        {
          errorMessage = eval( validateMethods[elementType[2]][1] + "()" );
          formatErrorTitle = "";
          if( validateMethods[elementType[2]][2].indexOf( " " ) == -1 )
          {
            formatErrorTitle = eval( validateMethods[elementType[2]][2] );
          }
          if( typeof( formatErrorTitle ) == "undefined" || formatErrorTitle == "undefined" || formatErrorTitle == "" )
          {
            formatErrorTitle = validateMethods[elementType[2]][2];
          }
          elementTitle = ( ( elementType[1] != "" ) ? elementType[1] : elementName );
          if (focusField == null)
          {
              focusField = element;
          }
          addError( elementType[2], formatErrorTitle, errorMessage, elementTitle );
        }
      }
    }
    else
    {
        checkMultiByteChars( element );
    }
    el++;
  }

  return showErrors();
}

function addError( formatType, formatTypeName, errorMessage, humanName )
{
  if( errorList[formatType] )
  {
    errorList[formatType][errorList[formatType].length] = humanName;
  }
  else
  {
    errorList[formatType] = new Array( formatTypeName, errorMessage, humanName );
    errorOrder[errorOrder.length] = formatType;
  }
}

function showErrors()
{
  if( errorOrder.length == 0 ) return true;
  nl   = ( ( alertMIME == "html" ) ? "<br />\n" : "\n" );
  ls = ( ( alertMIME == "html" ) ? "<ul>" : "\n" );
  le   = ( ( alertMIME == "html" ) ? "</ul>" : "\n" );
  li = ( ( alertMIME == "html" ) ? "<li>" : "  " );
  il = ( ( alertMIME == "html" ) ? "</li>" : "\n" );
  bs = ( ( alertMIME == "html" ) ? "<b>" : "" );
  be   = ( ( alertMIME == "html" ) ? "</b>" : "" );
  errorMessage = "";
  count = 0;

  for( i = 0 ; i < errorOrder.length ; i++ )
  {
    errorDetails = errorList[errorOrder[i]];
    tmp = bs + errorDetails[0] + be + nl + errorDetails[1] + nl + ls;
    if( errorDetails[1].length > alertExtraLine ) count++;
    for( j = 2 ; j < errorDetails.length ; j++ )
    {
      tmp += ( li + errorDetails[j] + il );
      count ++;
    }
    errorMessage += ( tmp + le );
    count += 3;
  }
  if ( focusField != null && focusField.type != "hidden")
  {
    focusField.focus();
    focusField = null;
  }
  if( alertMethod != "" )
  {
    alertHeight = ( count + alertExtraLines ) * alertLineHeight;
    eval( alertMethod + "( comm_msg047, errorMessage, alertWidth, alertHeight )" );
  }
  else
  {
    alert( comm_msg047 + nl + nl + errorMessage );
  }
  return false;
}

// Library Functions
function isMandatoryEmpty( mandatory, element )
{
    var emptyFlag = isEmpty( element);
    return ( mandatory && emptyFlag );
}

function checkMultiByteChars(element)
{
    isEmpty(element);
    return;
}

function getTextInputFromName( inputName, theForm )
{
  element = getInputFromName( inputName, theForm );
  if( element == null ) return null;
  if( element.type.toLowerCase() != "text" ) return null;
  return element;
}

function getInputFromName( inputName, theForm )
{
  if( typeof( theForm.elements[inputName] ) == undefined ) return null;
  return theForm.elements[inputName];
}

function charIsDigit( ch )
{
  code = ch.charCodeAt( 0 );
  if( code >= 48 && code <= 57 ) return true;
  return false;
}

function charIsLetter( ch )
{
  code = ch.charCodeAt( 0 );
  if( code >= 65 && code <= 90 ) return true;
  if( code >= 97 && code <= 122 ) return true;
  return false;
}

function charIsNonAlphanumeric( ch )
{
  if( charIsLetter( ch ) || charIsDigit( ch ) )
    return false;
  return true;
}

function isEmpty(element)
{
  var val = "";

  if( element.type.indexOf( "select" ) == 0 )
  {
      if ( element.name == "itemLines" && (document.forms['CommercialInvoice'].elements['itemLines'].length != 0) )
      {
          val = document.forms['CommercialInvoice'].elements['itemLines'].options[0].text;
      }
      else if ( element.selectedIndex >= 0 )
      {
          val = element.options[element.selectedIndex].value;
      }
  }
  else if( element.type == "radio" )
  {
      elArray = element.form.elements[element.name];
      for( rb = 0 ; rb < elArray.length ; rb ++ )
      {
          if( elArray[rb].checked )
          {
              val = elArray[rb].value;
              break;
          }
      }
  }
  else if( element.type == "checkbox" )
  {
      val = ( ( element.checked ) ? element.value : "" );
  }
  else
  {
      val = element.value;
  }
  val = trimString(val);
  if( element.type == "text" )
  {
      element.value = val;
  }
  if (typeof( val ) == "undefined" || typeof( val ) == "null" || val == "" || val == null)
  {
      return true;
  }
  else if (element.type == "text" || element.type == "textarea")
  {
    /*if (!fncmCheckEnglish(val))
    {
        if (focusField == null)
        {
            focusField = element;
        }
        addError( inputType, comm_msg006, comm_msg071, fnGetLable(element.name) );
    }*/
    return false;
  }
}

function fnGetLable(eleName)
{
    return eleName;
}

function fncmCheckEnglish (sValue)
{
	var ASCII_END = 128

	var bRetValue = true;
	var iCount = 0;
	var iCode = 0;
	var iLength = 0;

	sValue = sValue + "";
	iLength = sValue.length;
	for (iCount=0; iCount<iLength; iCount++)
	{
		iCode = sValue.charCodeAt(iCount); // get ascii code of character
		
		if (ASCII_END < iCode )
		{
			
			bRetValue = false;
			break;
		}
	}
	return bRetValue;
}

function fnValidatePhone(phonNo)
{
  var indChar = "";
  var allowedChars = " +-()";
  var index = -1;
  var gotNo = 0;
  var openBrFlag = false;

  strErrMess = ""
  for(count=0;count<phonNo.length;count++)
  {
      indChar = phonNo.charAt(count);
      if (!isNaN(indChar))
      {
          gotNo++;
          continue;
      }

      if((index = allowedChars.indexOf(indChar)) == -1)
      {
          strErrMess = comm_msg039 + comm_msg060;
          return false;
      }
      else if ((index = allowedChars.indexOf(indChar, index + 1)) != -1)
      {
          strErrMess = comm_msg039 + comm_msg060 + comm_msg061 + "'" + indChar + "'" + comm_msg062;
          return false;
      }
      else if ((indChar == ")" && count == 0) || (indChar == "(" && count > 0) || (indChar == "+" && count > 1))
      {
          strErrMess = comm_msg039 + comm_msg060;
          return false;
      }
      else if (indChar == "(")
      {
          openBrFlag = true;
      }
      else if (indChar == ")" && !openBrFlag)
      {
          strErrMess = comm_msg039 + comm_msg060;
          return false;
      }
      else if ((indChar == "-" && count == 0) || (indChar == "-" && count == phonNo.length))
      {
          strErrMess = comm_msg039 + comm_msg060;
          return false;
      }
  }
  return true;
}

function checkTime(time)
{
  var timeArr = time.split(":");
  var timeInSecs;

  if (timeArr.length != 2)
  {
      strErrMess= comm_msg063;
      return false;
  }
  if (isNaN(timeArr[0]) || isNaN(timeArr[1]) || timeArr[0] < 0 || timeArr[1] < 0)
  {
      strErrMess= comm_msg063;
      return false;
  }
  if(timeArr[1]>59 || timeArr[0]>23)
  {
      strErrMess= comm_msg063;
      return false;
  }

  timeInSecs = parseInt(timeArr[0]) * 60 + parseInt(timeArr[1]);
  if (typeof(intTime) != "undefined")
  {
      intTime = timeInSecs
  }
  if (timeInSecs == 0)
  {
      strErrMess= comm_msg064;
      return false;
  }
  return true;
}

function checkExtn(extnNo, extNoRef)
{
    var phoneVal, phoneRef;

    strErrMess = "";
    extnNo = trimString(extnNo);

    if (extnNo == "")
    {
        return true;
    }
    else if (isNaN(parseInt(extnNo)))
    {
        strErrMess = comm_msg065;
        return false;
    }
    else if (extnNo.indexOf(".") != -1)
    {
        strErrMess = comm_msg065;
        return false;
    }
    else if (typeof(dependentFields) != "undefined")
    {
        phoneRef = eval(dependentFields[extNoRef.name]);
        if (typeof(phoneRef) != "undefined")
        {
            phoneVal = trimString(phoneRef.value);
            if (phoneVal == "" && extnNo != "")
            {
                strErrMess = supplierCode_msg005
                return false;
            }
        }
    }

    return true;
}

function checkDate( dtvalue )
{
  var montharr = new Array(31,28,31,30,31,30,31,31,30,31,30,31)
  var dtarr = dtvalue.split("/");
  var temp = "", tmpidx = -2;
  var backDate = false;
  if (dtarr.length < 2 || dtarr > 3)
  {
            strErrMess = comm_msg039 + pickup_msg031 + "<BR>" + pickup_msg032 + "<P>1  dd/mm/yy<BR>2  dd/mm/yyyy<BR>3  mm/yy<BR>4  mm/yyyy";
      return false;
  }

  for (index=0; index < dtarr.length; index++)
  {
    if( dtarr[index] == "" || dtarr[index].indexOf(".") != -1 || isNaN(temp = parseInt(dtarr[index])) || temp <= 0 )
    {
        strErrMess = comm_msg039 + pickup_msg031;
        return false;
    }
    tmpidx ++
  }

  if (dtarr[tmpidx] < 1 || dtarr[tmpidx] > 12)
  {
    strErrMess = comm_msg039 + pickup_msg033 + " (1-12)"
    return false;
  }

  if (dtarr[tmpidx + 1].length != 2 && dtarr[tmpidx + 1].length != 4)
  {
    strErrMess = comm_msg039 + comm_msg066;
    return false;
  }

  if (tmpidx == 1)
  {
      if (dtarr[2] % 4 == 0)
      {
          montharr[1] = 29
      }
      if (parseInt(dtarr[0]) > parseInt(montharr[dtarr[1] - 1]))
      {
          strErrMess = comm_msg039 + pickup_msg033 + " (1-" + montharr[dtarr[1] - 1] + ")"
          return false;
      }
      if (dtarr[0] < now.getDate())
      {
          backDate = true;
      }
  }

  if (dtarr[tmpidx + 1].length < 4 && dtarr[tmpidx + 1] < 2000)
  {
      dtarr[tmpidx + 1] = parseInt(dtarr[tmpidx + 1]) + 2000
  }
  if ( dtarr[tmpidx + 1] == now.getFullYear())
  {
    if (dtarr[tmpidx] == now.getMonth() + 1)
    {
        if (backDate)
        {
           strErrMess = comm_msg067;
           return false;
        }
    }
    else if (dtarr[tmpidx] < now.getMonth() + 1)
    {
       strErrMess = comm_msg067;
       return false;
    }
  }
  else if (dtarr[tmpidx + 1] < now.getFullYear())
  {
    strErrMess = comm_msg067;
    return false;
  }

  return true;
}

function trimString (sInput, iSide)
{
    var sTemp = "";
    var cChar = "";
    var iCount = "";
    var SINGLE_BLANK = " ";
    var iInputWidth = 0;

    if (typeof(iSide) == "undefined")
    {
        iSide = 2
    }

    if (null == sInput) 
    {
        sTemp = EMPTY_STRING;
    }
    else
    {
        iInputWidth = sInput.length;

        switch (iSide)
        {
        case 0:
            //left trim
            for (iCount = 0; iCount < iInputWidth; iCount++)
            {
                cChar = sInput.charAt (iCount);
                if (SINGLE_BLANK != cChar)
                {
                    sTemp = sInput.substring (iCount, iInputWidth);
                    break;
                }
            }
            break;
        case 1:
            //right trim
            for (iCount = iInputWidth - 1; iCount >= 0 ; iCount--)
            {
                cChar = sInput.charAt (iCount);
                if (cChar != SINGLE_BLANK)
                {
                    sTemp = sInput.substring (0, iCount+1);
                    break;
                }
            }
            break;
        case 2:
            //both trim
            for (iCount = 0; iCount < iInputWidth; iCount++)
            {
                cChar = sInput.charAt (iCount);
                if (SINGLE_BLANK != cChar)
                {
                    sTemp = sInput.substring (iCount, iInputWidth);
                    break;
                }
            }
            iInputWidth = sTemp.length;
            for (iCount = iInputWidth - 1; iCount >= 0 ; iCount--)
            {
                cChar = sTemp.charAt (iCount);
                if (cChar != SINGLE_BLANK)
                {
                    sTemp = sTemp.substring (0, iCount+1);
                    break;
                }
            }
            break;
        }
    }
    return sTemp;
} // end of trimString

function validateNumber( value, paramName, defVal, toFloat, allowZero, decimalPoints, maxVal)
{
  var defMess = "<br />\n";
  var value2, lpCtr, dp = 1;

  if (typeof( defVal ) == "undefined") defVal = 0;
  if (typeof( toFloat ) == "undefined") toFloat = 1;
  if (typeof( allowZero ) == "undefined") allowZero = 1;
  if (typeof(decimalPoints) == "undefined") decimalPoints = 0;

  if( value == "" ) return defVal;

  if( value == blankmark )
  {
    return value;
  }
  if (defVal != "")
  {
    defMess = comm_msg017
  }
  if( isNaN( parseFloat( value ) ) )
  {
    strErrMess += paramName + " " + volweight_msg008 + defMess + " " + defVal + ".<br />\n";
    return defVal;
  }

  if( value < 0 || (value == 0 && allowZero == 0) )
  {
    strErrMess += paramName + " " + volweight_msg008 + defMess + " " + defVal + ".<br />\n";
    return defVal;
  }

  if( toFloat == 1 )
  {
    value2 = parseFloat( value );
  }
  else
  {
    value2 = Math.round( value );
  }

  if ( isNaN(value2) )
  {
    strErrMess += paramName + comm_msg050 + defMess + " " + defVal + ".<br />\n";
    return defVal;
  }

  if( value2 < 1 && value2 > 0 && ( value2 + "" ).charAt( 0 ) != "0" )
  {
    value2 = "0" + value2;
  }

  if (toFloat == 1 && decimalPoints > 0)
  {
      value2 = roundToDp(value2, decimalPoints)
  }

  if (typeof(maxVal) != "undefined" && value2 > maxVal)
  {
    strErrMess += paramName + comm_msg073 + defMess + " " + maxVal + ".<br />\n";
    return maxVal;
  }

  if( value!= value2)
  {
    strErrMess += paramName + " " + comm_msg050 + defMess + " " + value2 + ".<br />\n";
  }
  return value2;
}

function roundToDp( inValue, numDps )
{
  if( typeof( numDps ) == "undefined" ) numDps = 2;
  factor = Math.pow( 10, numDps );
  result = Math.round( inValue * factor ) / factor;
  return ( result );
}
// EOF