//*************************************************************************************************
//*
//*  Licensed Materials - Property of IBM
//*  (C) Copyright IBM Deutschland Informationssysteme GmbH 1999
//*  All Rights Reserved
//*
//*************************************************************************************************

//# ============================================================================================= #
//#
//# COMPONENT_NAME:    syntax.js
//#
//# FUNCTIONS:         EISA - JSP / HTML page name mapping
//#
//# ORIGINS:           3 August 2000 - O. Holzwarth
//#
//#
//# This file contains javascript functions which can be used as shared resource.
//#
//# ============================================================================================= #


// global variable
var firstFailedField = false;


// do nothing - alert an appropriate message
function doNothing()
{
   alert( "This action is currently not implemented." );
   return false;
}


// deny the requested action - alert an appropriate message
function denyAction( text )
{
   var msg;       // msg must be localized!!
   msg  = "________________________________________________________\n\n";
   msg += "  The requested action is not allowed in this context.\n";

   if ( text ) {
      msg += "\n  ";
      msg += text;
   } // endif
   msg += "\n";
   msg += "________________________________________________________\n\n";

   alert( msg );
   return false;
}


// go back to the previous page
function goBack()
{
   history.go( -1 );
}


// convert a field value to uppercase
function convertToUpperCase( field )
{
   field.value = field.value.toUpperCase();
}


// select an item in a combo box.
// @param:     combobox to set the selection for
// @param:     value of the item to select
function selectCBItem( cb, itemVal )
{
   for ( var i = 0; i < cb.length; i++ ) {
      if ( cb.options[i].value == itemVal ) {
         cb.options[i].selected=true;
         break;
      } // endif
   } // endfor

   return true;
}


// select a radioButton from the set.
// @param:     radioButtonSet to select a button from
// @param:     value of the button to select
function selectRadioButton( rbSet, rbVal )
{
   for ( var i = 0; i < rbSet.length; i++ ) {
      if ( rbSet[i].value == rbVal ) {
         rbSet[i].checked=true;
         break;
      } // endif
   } // endfor

   return true;
}


// get an array with all URL parameters from the given location
function getURLParameters( location )
{
   return location.search.split( '?' );
}


// extract and return a parameter from the given stream
// if the key is not included return an empty string
// @param:  the parameter stream
// @param:  the key to get the appropriate value from the stream
function getParameter( parmStream, key )
{
   // get the init flag
   var key       = "?" + key + "=";
   var parmValue = "";
   var startIdx  = parmStream.indexOf( key  );
   if ( startIdx >= 0 ) {
      var endIdx    = parmStream.indexOf( "?", startIdx + 1 );
      if ( endIdx < 0 )
         parmValue = parmStream.substring( startIdx + key.length );
      else
         parmValue = parmStream.substring( startIdx + key.length, endIdx );
   } // endif

   return parmValue;
}



// verifies a form. In case of any verification error alert a message.
// @param:     the form to check the fields for
// @return:    true if the verification was successful otherwise false.
function verifyForm( form )
{
   return verifyFields( form.elements );
}


// verifies an array of fields. In case of any verification error alert a message.
// @param:     the array with the fields to check
// @return:    true if the verification was successful otherwise false.
function verifyFields( fields )
{
   var msg = "";

   // reset the variable
   firstFailedField = false;

   var emptyFields = checkMandatoryFields( fields );
   var wrongContents = checkSyntax( fields );
   if ( emptyFields || wrongContents ) {
      // concatenate the messages
      msg = emptyFields;
      if ( msg && wrongContents )
         msg += "\n\n";
      msg += wrongContents + "\n\n"
      displayError( msg );
      return false;
   } // endif

   return true;
}


// checks the mandatory fields for filling.
// @param:     the array with the fields to check
// @return:    the names of those fields which are defined as mandatory
//             and do not include any value
function checkMandatoryFields( fields )
{
   var emptyFields      = "";
   var unselectedFields = "";
   var tab              = "\n        ";

   msgMandatory  = "The following field(s) have to be filled:\n";
   msgUnselected = "At least one item has to be selected for:\n";

   // loop through all fields
   for ( var i = 0; i < fields.length; i++ ) {
      var e = fields[i];
      if ( e.optional )
         continue;

      // check the field
      switch ( e.type ) {
         case "text"     :
         case "textarea" :
         case "password" :
            if ( isEmpty( e ) ) {
               if ( !emptyFields )
                  emptyFields += msgMandatory;
               emptyFields += tab + e.name;
            } // endif

            if ( !firstFailedField ) {
               firstFailedField = true;
               select(e);
            } // endif
            break;

         case "select-one"      :
         case "select-multiple" :
            if ( !isSelected( e ) ) {
               if ( !unselectedFields )
                  unselectedFields += msgUnselected;
               unselectedFields += tab + e.name;
            } // endif

            if ( !firstFailedField ) {
               firstFailedField = true;
               select(e);
            } // endif
            break;

         default :
            break;
      } // endswitch
   } // endfor

   // concatenate the result strings and return it
   strResult = emptyFields;
   if ( unselectedFields )
      strResult += "\n\n" + unselectedFields;

   return strResult;
}


// checks the syntax for dedicated fields.
// @param:     the array with the fields to check
// @return:    the names of those fields where the syntax check has failed
function checkSyntax( fields ) {
   var errortext = "";
   var tab = "\n        ";

   var msgSyntax = "The following field(s) have been filled incorrectly:\n";

   // iterate through all fields and validate them
   for ( var i = 0; i < fields.length; i++ ) {
      var e = fields[i];

      // check the field value
      var msg = checkField( e );

      // check the result
      if ( msg != true ) {
         // an error occurred - check if this is the first error
         if ( !errortext )
            errortext += msgSyntax;

         // concatenate the error message
         errortext += tab + e.name + " - " + msg;
         if ( !firstFailedField ) {
            firstFailedField = true;
            select(e);
         } // endif
      } // endif
   } // endfor

   return errortext;
}


// checks the field if it contains an allowed value.
// @param:     the field to check
// @return:    true if the value is allowed otherwise the appropriate error message.
function checkField( field ) {
   // if the field is optional: check if it is filled
   if ( field.optional && isEmpty( field ) )
      return true;

   var msgPrefix                    = "please ";
//   var msgCorrectFormatDate         = "use the format TT.MM.YYYY";
   var msgCorrectFormatDate         = "use the format YYYY-MM-DD";
   var msgCorrectFormatNumeric      = "use numeric values only";
   var msgCorrectFormatAlphaNumeric = "use alphanumeric values only";
   var msgCorrectFormatDecimal      = "use decimal values only";
   var msgCorrectLength1             = "enter a value with ";
   var msgCorrectLength2             = " characters";

   var msg = true;

   // do the defined syntax check
   if ( field.checkMethod == "date" ) {
      // check for correct date
      if ( !validateDate( field ) )
         msg = msgPrefix + msgCorrectFormatDate;
   } else if ( field.checkMethod == "numeric" ) {
      if ( !isNumeric( field ) )
         msg = msgPrefix + msgCorrectFormatNumeric;
   } else if ( field.checkMethod == "alphanumeric" ) {
      if ( !isAlphaNumeric( field ) )
         msg = msgPrefix + msgCorrectFormatAlphaNumeric;
   } else if ( field.checkMethod == "alphanumeric*" ) {
      if ( !isAlphaNumeric( field, '*' ) )
         msg = msgPrefix + msgCorrectFormatAlphaNumeric;
   } else if ( field.checkMethod == "decimal" ) {
      if ( !isDecimal( field ) )
         msg = msgPrefix + msgCorrectFormatDecimal;
   } // endif

   // check the value length
   result = validateLength( field );
   if ( result != true ) {
      if ( msg == true )
         // the field has only an incorrect length
         msg = msgPrefix + msgCorrectLength1 + result + msgCorrectLength2;
      else
         // the field also has an incorrect format
         msg += " and " + msgCorrectLength1 + result + msgCorrectLength2;
   } // endif

   return msg;
}



// displays the given error information
function displayError( text ) {
   var msg;       // msg must be localized!!
   msg  = "_______________________________________________\n\n";
   msg += "  The requested action could not be executed.\n";
   msg += "  Please check the following information.\n";
   msg += "_______________________________________________\n\n";

   // display errors
   msg += text;
   alert( msg );
   return true;
}


// sets the focus on the given field and select the contents
function select( field ) {
   field.focus();
   if (!field.options)
	field.select();
}



// *****   input validation checks   *****
// checks if the field is empty
function isEmpty( field ) {
   var value = field.value;
   if ( value == null || value.length == 0 )
      return true;

//   for ( var i = 0; i < value.length; i++ ) {
//      var aChar = value.charAt( i );
//      if ( aChar != ' ' && aChar != '\t' )
//         return false;
//   } // endfor

//   return true;
   return false;
}


// checks if a (valid) item is selected in the select object
function isSelected( selectField ) {
   if ( selectField.selectedIndex == -1 )
      return false;

   if ( selectField.options[ selectField.selectedIndex ].value == "" )
      return false;

   return true;
}


// checks a date field of the correct date syntax
// assumes german date format dd.mm.yyyy
// 26.11.99 assumes now the following format yyyy-mm-dd
function validateDate(field) {
//   var dateFields = field.value.split( "." );
   var dateFields = field.value.split( "-" );
   if ( dateFields.length != 3 )
      return false;
   if ( !validateMonth( dateFields[1] ) )
      return false;
//   if ( !validateDay( dateFields[0], dateFields[1] ) )
   if ( !validateDay( dateFields[2], dateFields[1] ) )
      return false;
//   if ( !validateYear( dateFields[2] ) )
   if ( !validateYear( dateFields[0] ) )
      return false;

   return true;
}

function validateMonth(field) {
   var input = stripZeros( field );
   if ( !validateBasics( input ) )
      return false;
   if ( !inRange( input, 1, 12 ) )
      return false;
   return true;
}

function validateYear(field) {
   var input = stripZeros( field );
   if ( !validateBasics( input ) )
      return false;
   if ( !inRange( input, 1900, 2100 ) )
      return false;
   return true;
}

function validateDay(dayField, monthField) {
   var input = stripZeros( dayField );
   if ( !validateBasics( input ) )
      return false;
   var monthVal = parseInt( monthField );
   var monthMax = new Array( 31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
   var top = monthMax[monthVal];
   if ( !inRange( input, 1, top ) )
      return false;
   return true;
}

// JavaScript sees numbers with leading zeros as octal values, so strip zeros
function stripZeros( inputStr ) {
   var result = inputStr;
   while ( result.substring( 0, 1 ) == "0" )
      result = result.substring( 1, result.length );

   return result;
}

// do the basic validation for checking the date value
function validateBasics( inputVal ) {
   if ( inputVal == "" || inputVal == null )
      return false;
   if ( !isInteger( inputVal ) )
      return false;
   return true;
}

// checks the value if it is a positive integer
function isInteger( value ) {
   for ( var i = 0; i < value.length; i++ ) {
      var aChar = value.charAt( i );
      if ( aChar < "0" || aChar > "9" )
         return false;
   } // endfor

   return true;
}

// function to determine if value is in acceptable range for this application
function inRange( inputStr, lo, hi ) {
   var num = parseInt( inputStr );
   if ( num < lo || num > hi )
      return false;

   return true;
}


// checks a numeric field for the correct value
function isNumeric( field )
{
   return isInteger( field.value );
}


// checks an alphanumeric field for the correct value
// if the parameter 'placeholder' is set the given character is accepted as placeholder
function isAlphaNumeric( field, placeholder )
{
   var value = field.value;

   // check if a placeholder is accepted and the placeholder character is appended to the value
   if ( placeholder && placeholder == value.charAt( value.length - 1 ) )
      // cut the placeholder
      value = value.substring( 0, value.length - 1 );

   for ( var i = 0; i < value.length; i++ ) {
      var aChar = value.charAt( i );
      if ( ( aChar < "a" || aChar > "z" ) && ( aChar < "A" || aChar > "Z" ) && ( aChar < "0" || aChar > "9" ) && ( aChar <= "z" ) )
         return false;
   } // endfor

   return true;
}


// checks a decimal field for the correct value
function isDecimal( field, noDecimals )
{
   var value = field.value;

   // convert the comma to a dot
   valArray = value.split( ',' );
   if ( valArray.length > 2 )
      return false;
   else if ( valArray.length == 2 )
      value = valArray[0] + '.' + valArray[1];

   // check format
   if ( value.split( '.' ).length > 2 )
      return false;

   if ( ( value.charAt(0) < "0" || value.charAt(0) > "9" ) && value.charAt(0) != "." && value.charAt() != "+" && value.charAt(0) != "-" )
      return false;

   for ( var i = 1; i < value.length; i++ ) {
      var aChar = value.charAt( i );
      if ( ( aChar < "0" || aChar > "9" ) && aChar != "." )
         return false;
   } // endfor

   return true;
}


// checks the field if the value is of the correct length (or empty).
// @param:     the field to check
// @return:    true if the value is valid otherwise the requested length.
function validateLength( field ) {
   if ( isEmpty( field ) )
      // no value is a valid one (this is checked by the 'optional' attribute)
      return true;

   var definedLength = field.valueLength;
   // do the length check
   if ( ( definedLength != null ) && ( field.value.length != definedLength ) )
      return definedLength;

   return true;
}


// *****   end checking methods   *****


