//*****************************************************************************
// File:    jsFieldValidation.js
// Purpose: This file has the library of javascript functions that validate
//          form fields.
// Functions
// ----------------------------------------------------------------------------
// bool isEmpty(string) - returns true if a string is empty.
// ...
// bool resetForm(frmForm) - cleans all the error labels and the values.
//*****************************************************************************
// Author   Date       Comments
// -------- ---------- --------------------------------------------------------
// JGP/V    2002.05.23 Creation of the file.
// JGP/V    2002.06.06 Added the resetForm function.
// JGP/V    2003.05.28 Added the date field validation.
// JGP/V    2004.03.12 Added the multi-language.
// JGP/V    2004.07.28 Changed the getLang to accept es.*.
//*****************************************************************************

// Constants.
var WHITESPACE = " \t\n\r";

var FLD_REQUIRED = "*";
var FLD_EMAIL = "@";
var FLD_NUMERIC = "#";
var FLD_DATE = "§";

var MSG_ERR_REQUIRED = "- Por favor preencha o campo!";
var MSG_ERR_REQUIRED_CMB = " - Por favor seleccione uma opção!";
var MSG_ERR_EMAIL = "- Por favor insira um e-mail válido!";
var MSG_ERR_NUMERIC = "- Por favor insira um valor numérico!";
var MSG_ERR_DATE = "- Por favor insira uma data válida!";

var MSG_ERR_REQUIRED_ES = "- ¡Por favor, rellene este campo!";
var MSG_ERR_REQUIRED_CMB_ES = "- ¡Por favor, seleccione una opción!";
var MSG_ERR_EMAIL_ES = "- ¡Por favor, introduzca un e-mail válido!";
var MSG_ERR_NUMERIC_ES = "- ¡Por favor, introduzca un valor numérico!";
var MSG_ERR_DATE_ES = "- ¡Por favor, introduzca una fecha válida!";


function getLang(){
	var strURL = window.document.URL;var strLanguage = '1';
	if (strURL.indexOf("es.") > 0 && strURL.toUpperCase() != 'HTTPS://VORTALOFFICESUPPLIES.VORTAL.PT/DEFAULT.ASP' && strURL.toUpperCase() != 'HTTPS://VORTALOFFICESUPPLIES.VORTAL.PT/' && strURL.toUpperCase() != 'HTTPS://VORTALENERGYEUTILITIES.VORTAL.PT/DEFAULT.ASP' && strURL.toUpperCase() != 'HTTPS://VORTALENERGYEUTILITIES.VORTAL.PT/'){strLanguage= '2';}
	if (strURL.indexOf("en.") > 0){strLanguage= '3';}
	return strLanguage;
	}

function isEmpty(str){return ((str == null) || (str.length == 0));}

function getCharInString (chr, str){
  for (i = 0; i < str.length; i++){
    if (str.charAt(i) == chr){return true;}
  }
  return false
}

function LTrim(str){   
  var i = 0;
  while ((i < str.length) && getCharInString(str.charAt(i), WHITESPACE)){i++;}
  return str.substring(i, str.length);
}

function isEmail(str){
  // there must be >= 1 character before @, so we
  // start looking at character position 1 
  // (i.e. second character)
  var i = 1;
  var intLength = str.length;

  // look for @
  while ((i < intLength) && (str.charAt(i) != "@")){i++}
  if ((i >= intLength) || (str.charAt(i) != "@")){return false;}else{i += 2;}
  // look for "."
  while ((i < intLength) && (str.charAt(i) != ".")){i++}

  // there must be at least one character after the .
  if ((i >= intLength - 1) || (str.charAt(i) != ".")){return false;}else{return true;}
}

function isDate(str){
  var dte;
  dte = String2Date(str);
  if (dte == false){return false;}else{return true;}
}

function isFieldValid(objComponent){
  var strValue;
  var lblErr;
  
  if (objComponent == null) return false;
  
  strValue = objComponent.value;
  strValue = LTrim(strValue);
  
  //If internet explorer
  if(window.ActiveXObject)
  {
	lblErr = objComponent.form.all.item("lblErr_" + objComponent.name);
  }
  else
  {
	//voltar para firefox aqui
	lblErr = objComponent.parentNode.childNodes.item("lblErr_" + objComponent.getAttribute("name"));
  }  

  if (getCharInString(FLD_REQUIRED, objComponent.id)){
    if (objComponent.tagName == "SELECT"){if (objComponent.nullvalue == strValue){strValue="";}}
  
    if (isEmpty(strValue))
    {
      if (lblErr != null) 
      {
        if (objComponent.tagName == "SELECT")
        {
          lblErr.innerText = ((getLang()==2) ? MSG_ERR_REQUIRED_CMB_ES : MSG_ERR_REQUIRED_CMB);
        }
        else
        {
          lblErr.innerText = ((getLang()==2) ? MSG_ERR_REQUIRED_ES : MSG_ERR_REQUIRED);
        }
      }
      return false;
    }
  }
  
  if (getCharInString(FLD_EMAIL, objComponent.id))
  {
    if (!isEmpty(strValue) && !isEmail(strValue))
    {
      if (lblErr != null) lblErr.innerText = ((getLang()==2) ? MSG_ERR_EMAIL_ES : MSG_ERR_EMAIL);
      return false;
    }
  }
  
  if (getCharInString(FLD_NUMERIC, objComponent.id))
  {
    if (!isEmpty(strValue))
    {
      if (isNaN(strValue))
      {
        if (lblErr != null) lblErr.innerText = ((getLang()==2) ? MSG_ERR_NUMERIC_ES : MSG_ERR_NUMERIC);
        return false;
      }
    }
  }
  
  if (getCharInString(FLD_DATE, objComponent.id))
  {
    if (!isEmpty(strValue) && !isDate(strValue))
    {
      if (lblErr != null) lblErr.innerText = ((getLang()==2) ? MSG_ERR_DATE_ES : MSG_ERR_DATE);
      return false;
    }
    else
    {
      if (!isEmpty(strValue))
      {
        strValue = Date2String(String2Date(strValue));
      }
    }
  }
  
  if (lblErr != null) lblErr.innerText = "";
  objComponent.value = strValue;
  return true;    
}

function isFormValid(frmForm)
{
  var blnErrFound = false;
      
  if (frmForm == null) return false;
  for (var intElem = 0; intElem < frmForm.elements.length; intElem++)
  {
    if (!isFieldValid(frmForm.elements[intElem]))
    {
      if (!blnErrFound)
      {
        blnErrFound = true;
        frmForm.elements(intElem).focus()
      }
    }
  }
  return (!blnErrFound);
}

function resetForm(frmForm)
{
  if (frmForm == null) return;
  
  for (var intElem=1; intElem < frmForm.length; intElem++)
  {
    if (frmForm.elements(intElem).tagName == "SELECT")
    {
      frmForm.elements(intElem).selectedIndex = 0;
    }
    else if ((frmForm.elements(intElem).type != "hidden") 
      && (frmForm.elements(intElem).type != "button")
      && (frmForm.elements(intElem).type != "reset")
      && (frmForm.elements(intElem).type != "submit"))
    {
      if (frmForm.elements(intElem).type == "checkbox")
      {
        frmForm.elements(intElem).checked = false;
      }
      else
      {
        frmForm.elements(intElem).value = "";
      }
    }
  }
  
  for (var i = 0; i < frmForm.all.length; i++)
  {
    if (frmForm.all.item(i).id.indexOf("lblErr") == 0)
    {
      frmForm.all.item(i).innerText = "";
    }
  }
}

/******************************************************************************
'Function: IsLeapYear()
'Purpose:  This function returns true is a given year is a leap year.
'Inputs:   intFullYear - given year.
'Returns:  The result is True if the year if a lead year, false otherwise.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function IsLeapYear(intFullYear)
{
  // Declaration of the local variables.
  var intYear;
  
  // Validation of the parameter.
  if (intFullYear == null) return false;
  if (!isFinite(intFullYear)) return false;
  
  // Format the year has an integer.
  intYear = parseInt(parseVal(intFullYear));
  
  // Return the validation.
  return (intYear % 400 == 0 || (intYear % 4 == 0 && intYear % 100 != 0));
}

/******************************************************************************
'Function: String2Date()
'Purpose:  This function transforms a string to a date.
'Inputs:   strDate - the given date in one of the following formats: 
'             dd/mm/yyyy or yyyy/mm/dd.  Accepts '/', '-' and '.' and the 
'             separator.  Accepts days and months with only one digit.
'Returns:  The result date.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function String2Date(strDate)
{
  // Declaration of the local variables.
  var intDay, intMonth, intFullYear;
  var arexFormats = new Array(/^(\d{1,2})[\/\-\.](\d{1,2})[\/\-\.](\d{4})$/,
                              /^(\d{4})[\/\-\.](\d{1,2})[\/\-\.](\d{1,2})$/);
  var aintMonthType = new Array(1,2,1,0,1,0,1,1,0,1,0,1);
  
  // Validation of the parameter.
  if (strDate == null) return false;
  
  // Search for the format of the date.
  for (i = 0; i < arexFormats.length; i++)
  {
    if (arexFormats[i].test(strDate))
    {
      // If the format is dd/mm/yyyy, ...
      if (i == 0)
      {
        intDay = parseInt(parseVal(RegExp.$1));
        intMonth = parseInt(parseVal(RegExp.$2));
        intFullYear = parseInt(parseVal(RegExp.$3));
      }
      // Else the format is yyyy/mm/dd ...
      else
      {
        intDay = parseInt(parseVal(RegExp.$3));
        intMonth = parseInt(parseVal(RegExp.$2));
        intFullYear = parseInt(parseVal(RegExp.$1));
      }
      
      // If the day is less than 1, then is 1.
      if (intDay < 1) intDay = 1;
      
      // If the month is not between 1 and 12, return false.
      if (intMonth < 1 || intMonth > 12) return false;

      // Validate the type of month.
      switch (aintMonthType[intMonth - 1])
      {
        // If month has only 30 days...
        case 0:
          // If the day is greater that 30, then is 30.
          if (intDay > 30) intDay = 30;
          break;
        // If month has only 31 days...
        case 1:
          // If the day is greater that 31, then is 31.
          if (intDay > 31) intDay = 31;
          break;
        // If month has only 28/29 days...
        case 2:
          // If is a leap year, ...
          if (IsLeapYear(intFullYear))
          {
            // If the day is greater that 29, then is 29.
            if (intDay > 29) intDay = 29;
          }
          else
          {
            // If the day is greater that 28, then is 28.
            if (intDay > 28) intDay = 28;
          }
          break;
      }
      
      // Return the date.
      return new Date(intFullYear, intMonth - 1, intDay);
    }
  }
  return false;
}

/******************************************************************************
'Function: Date2String()
'Purpose:  This function transforms a date to a string.
'Inputs:   dteDate - given date (optional).  If not given returns today's date.
'          strSeparator - char used to separate the date items (optional). 
'                         If not given uses '/'. 
'Returns:  The result date in the dd/mm/yyyy format.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.03.24 Creation of the function.
******************************************************************************/
function Date2String()
{
  // Declaration  of the local variables.
  var rex = /^[\/\-\.]$/;
  var result;

  // If no parameter was given uses today's date and '/'.
  if (arguments.length == 0) return Date2String(new Date(), '-');
  
  // If only one parameter was given, ...
  if (arguments.length == 1)
  {
    // If the parameters is the separator, use it with today's date.
    if (arguments[0].length == 1)
    {
      return Date2String(new Date(), arguments[0]);
    }
    // Else, use the parameter has the date with the default separator.
    else
    {
      return Date2String(arguments[0], '-');
    }
  }
  
  // Validation of the parameters.
  if (arguments[0] == null || arguments[1] == null) return false;
  
  // Validation of the separator char.
  if (!rex.test(arguments[1])) return false;
  
  try
  {
    // Add the day.
    if (arguments[0].getDate() < 10) 
    {
      result = '0' + arguments[0].getDate();
    }
    else
    {
      result = '' + arguments[0].getDate();
    }
    
    result += arguments[1];
    
    // Add the month.
    if (arguments[0].getMonth() < 9) 
    {
      result += '0' + (arguments[0].getMonth() + 1);
    }
    else
    {
      result += '' + (arguments[0].getMonth() + 1);
    }
    
    // Add the full year.
    result += arguments[1] + arguments[0].getFullYear();
    
    // Return the result.
    return result;
  }
  catch(e)
  {
    // In case of any errors, return false.
    return false;
  }
}

/******************************************************************************
'Function: parseVal()
'Purpose:  This function removes the leading zeros of a string.
'Inputs:   strValue - given value in a string.
'Returns:  The result value without the leading zeros.
'******************************************************************************
' Author   Date       Comments
' -------- ---------- ---------------------------------------------------------
' JGP/V    2003.09.04 Creation of the function.
' JGP/V    2004.09.09 Validation that the value is really a string
******************************************************************************/
function parseVal(strValue)
{
  strValue = '' + strValue;

  while (strValue.charAt(0) == '0')
    strValue = strValue.substring(1, strValue.length);

  return strValue;
}
