// Absolute min/max for currency values in SQL server
//var MAX_CURRENCY = 922337203685477.5807;
//var MIN_CURRENCY = -922337203685477.5808;
// Current min/max for currency values in SQL server
var MAX_CURRENCY = 1000000000.00;
var MIN_CURRENCY = -1000000000.00;
var MAX_CURR_STRING = "1000000000.00";
var MIN_CURR_STRING = "0.00";

// Absolute min/max value for ints
//var MIN_INTEGER = Math.pow(2, 32)/2 * -1;
//var MAX_INTEGER = Math.pow(2, 32)/2 - 1;
var MAX_INTEGER = 1000000000.00;
var MIN_INTEGER = -1000000000.00;


function valueOfField(objField)
{
  if (objField)
  {
    //(button, reset, submit) not checked;
    if (objField.type == "text" || objField.type == "hidden" || objField.type == "file" || objField.type == "password" || objField.type == "textarea")
    {
      return objField.value;
    }
    else if (objField.type == "select-one" || objField.type == "select-multiple")
    {
      var intIndex = objField.selectedIndex;
      if(intIndex >= 0)
      {
        var strVar = objField.options[intIndex].value;
        return strVar;
      }
      return '';
    }
    else if (objField.type == "checkbox" || objField.type == "radio")
    {
      if(objField.checked)
      {
        return objField.value;
      }
      return '';
    }
    else if (objField.length && objField[0] && (objField[0].type == "checkbox" || objField[0].type == "radio"))
    {
      for(var i = 0; i < objField.length; i++)
      {
        if(objField[i].checked)
        {
          return objField[i].value;
        }
      }
      return '';
    }
    else
    {
      return '';
    }
  }
  else
  {
    return '';
  }
}

function fieldFocus(objField)
{
  if(objField.focus) objField.focus();
  if(objField[0] && objField[0].focus) objField[0].focus();
  if(objField.select) objField.select();
}

function validateField(objField, strfieldTitle, strCustomError, blnMandatory, objValidateMethod, strPattern, varMin, varMax, intMinLen, intMaxLen)
{
  var vfield;
  if(objField.length && objField[0] && (objField[0].type == "checkbox" || objField[0].type == "radio"))
  {
    vfield = objField[0];
  }
  else
  {
    vfield = objField;
  }

  vfield.title = strfieldTitle;
  vfield.mandatory = blnMandatory;
  vfield.min = varMin;
  vfield.max = varMax;
  vfield.pattern = strPattern;
  vfield.minlength = intMinLen;
  vfield.maxlength = intMaxLen;
  

  var varFieldValue = valueOfField(objField).replace(/^\s*(.*)\s*$/, '$1');
  
  if(objValidateMethod)
  {
    vfield.validate = objValidateMethod;
    if(!vfield.validate()) return false;
  }
  else if(blnMandatory && (varFieldValue == null || varFieldValue == ''))
  {
    fieldFocus(objField);
    if(strCustomError)
    {
      alert(strCustomError);
    }
    else
    {
      if (objField.type == "text" || objField.type == "hidden" || objField.type == "file" || objField.type == "password" || objField.type == "textarea")
        alert("Please enter some information into the "+vfield.title+" field.");
      else
        alert("Please select an option in "+vfield.title+".");
    }
    return false;
  }
  if(strPattern && varFieldValue)
  {
    var intPattern = varFieldValue.search(strPattern);
    if (intPattern < 0)
    {
      fieldFocus(objField);
      if(strCustomError)
      {
        alert(strCustomError)
      }
      else
      {
        alert("Please enter a vaild value into "+vfield.title+".");
      }
      return false;
    }
  }
  
  if(varMin && varFieldValue)
  {
    if(varFieldValue < varMin)
    {
      fieldFocus(objField);
      alert(vfield.title+" field must be greater than "+varMin+".");
      return false;
    }
  }

  if(varMax && varFieldValue)
  {
    if(varFieldValue > varMax)
    {
      fieldFocus(objField);
      alert(vfield.title+" field must be less than "+varMax+".");
      return false;
    }
  }

  if(intMinLen && varFieldValue)
  {
    if(varFieldValue.length < intMinLen)
    {
      fieldFocus(objField);
      alert("There must be at least "+intMinLen+" characters in "+vfield.title+".");
      return false;
    }
  }

  if(intMaxLen && varFieldValue)
  {
    if(varFieldValue.length > intMaxLen)
    {
      fieldFocus(objField);
      alert("There must be at less than "+intMaxLen+" characters in "+vfield.title+".");
      return false;
    }
  }
  
  return true;
  
}


function validateForm(form) {
  if (!form)
  {
    alert("Please pass in the form to validate.");
    return false;
  }
  var successful = true;
  var elements = form.elements;
  for (var i = 0; successful && i < elements.length; i++)
  {
    if (elements[i].validate)
    {
      successful = elements[i].validate();
    }
  }
  return successful;
}

function validateAlert(message, field, ignoreCustom) {
  if (!ignoreCustom && field.message)
  {
    alert(field.message);
  }
  else
  {
    var fieldTitle = ((field.title) ? "the \"" + field.title + "\"" : "this") + " field";
    message = message.replace(/%f/, fieldTitle);
    alert(message);
  }
}

function validateSelect() {
  var si = this.selectedIndex;
  if (!this.mandatory && (si < 0 || this.options[si].value == null || this.options[si].value == ''))
    return true;

	if (si < 0 || this.options[si].value == null || this.options[si].value == '')
	{
		this.focus();
	  validateAlert("Please select an option in %f.", this);
	  return false;
	}
	return true;
}

function validateText() {
  var value = this.value.replace(/^\s*(.*)\s*$/, '$1');

  if (!this.mandatory && value == "")
    return true;

  if (!value || value == "")
  {
    this.focus();
    this.select();
    validateAlert("Please enter some information into %f.", this);
    return false;
  }
  
  if (this.maxlength)
  {
    if (this.value)
    {
      if (this.value.length > this.maxlength)
      {
        this.select();
        this.focus();
        validateAlert("You cannot exceed "+this.maxlength+" characters in %f.", this);
        return false;
      }
    }
  }

  if (this.minlength)
  {
    if (this.value)
    {
      if (this.value.length < this.minlength)
      {
        this.select();
        this.focus();
        validateAlert("There must be at least "+this.minlength+" characters in %f.", this);
        return false;
      }
    }
  }
  
  if (this.pattern)
  {
    var pattern = this.pattern;
    var found = this.value.search(pattern);
    if (found < 0)
    {
      var valueType = (this.valueType) ? this.valueType + " " : "value";
      this.select();
      this.focus();
      validateAlert("Please enter a valid " + valueType + " into %f.", this);
      return false;
    }
  }
  
  return true;
}

function validateInteger() 
{
  if (!this.mandatory && this.value =="")
    return true;

  var pattern = /^(([0-9]+)|([1-9][0-9]{0,2}(,[0-9]{3})+))$/;

  if ((!this.value || this.value == "") || this.value.search(pattern) < 0)
  {
    this.select();
    this.focus();

    var message;
    if (isNaN(parseInt(this.value.replace(/,/g, ''))))
    {
      message = "Please enter a number (in digits, not words) into %f.";
    }
    else
    {
      message = "Please enter a non-decimal positive number in digits (not words) without anything else into %f.";
    }
    validateAlert(message, this);
    return false;
  }

  var num = parseInt(this.value);
  var minValue = Number.MIN_VALUE;
  var maxValue = Number.MAX_VALUE;

  if (!isNaN(this.minValue))
    minValue = Math.max(this.minValue, minValue);
  if (!isNaN(this.maxValue))
    maxValue = Math.min(this.maxValue, maxValue);

  if (num < minValue)
  {
    this.select();
    this.focus();
    validateAlert("Please enter a number (in digits, not words) greater than or equal to " + minValue + " in %f.", this);
    return false;
  }
  else if (num > this.maxValue)
  {
    this.select();
    this.focus();
    validateAlert("Please enter a number less than or equal to " + maxValue + " into %f.", this);
    return false;
  }
  return true;
}

function validateCurrency() {
  if (!this.mandatory && this.value == "")
    return true;

  var pattern = /^(Nil|[+\-]?(([0-9]+)|([1-9][0-9]{0,2}(,[0-9]{3})+))([\.-]([0-9]){2}))$/i;
  var found = this.value.search(pattern);

  if (found < 0)
  {
    this.select();
    this.focus();
    validateAlert("Please enter a valid currency value (i.e. in digits, not words, showing dollars and cents separated by a decimal place and without typing in the dollar sign and greater than \'0.00\' e.g. \'1.00\') into %f.", this);
    return false;
  }

  var minValue = (!isNaN(this.minValue)) ? Math.max(this.minValue, MIN_CURRENCY) : MIN_CURRENCY;
  var maxValue = (!isNaN(this.maxValue)) ? Math.min(this.maxValue, MAX_CURRENCY) : MAX_CURRENCY;

  var value = this.value.replace(/(.)\-/g, '$1.');

  if (value < minValue)
  {
    this.select();
    this.focus();
    validateAlert("Please enter a number greater than or equal to " + MIN_CURR_STRING + " into %f.", this);
    return false;
  }
  else if (value > maxValue)
  {
    this.select();
    this.focus();
    validateAlert("Please enter a number less than or equal to " + MAX_CURR_STRING + " into %f. (This is an arbitrary maximum imposed by Incorporator.)", this);
    return false;
  }

  return true;
}


//This function needs to be checked again
function validateEmail()
{
  // return if blank an not mandatory
  if ((!this.value || this.value == "") && !this.mandatory)
    return true;

  emailStr = String(this.value);

  // checks if the e-mail address is valid
  var emailPat = /^(\".*\"|[A-Za-z0-9\_][A-Za-z0-9\.\-\_]*)@(\[\d{1,3}(\.\d{1,3}){3}]|([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,3})$/;
  var matchArray = emailStr.match(emailPat);
  if (matchArray == null)
  {
    this.select();
    this.focus();
    validateAlert("Please enter a valid email address into %f.\n(check the '@' and '.' characters)", this);
    return false;
  }
  // make sure the IP address domain is valid
  var IPArray = matchArray[2].match(/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/);
  if (IPArray != null)
  {
    for (var i=1; i<=4 ;i++)
    {
      if (IPArray[i]>255)
      {
        this.select();
        this.focus();
        validateAlert("Please enter a valid destination IP address into %f.", this)
        return false;
      }
    }
  }
  return true;
}

function validateDecimal()
{
  if (!this.mandatory && this.value == "")
    return true;

  if (isNaN(this.value))
  {
    this.select();
    this.focus();
    validateAlert("Please enter a number into %f.", this);
    return false;
  }
  else
  {
    var decimals = (this.decimals) ? this.decimals : 0;
    var regExp = '^[\-+]?[0-9]+' + ((decimals) ? '(\.[0-9]{1,' + decimals + '})?' : '') + '$'
    var matchArray = this.value.match(regExp);

    if (matchArray == null)
    {
      this.select();
      this.focus();
      validateAlert("Please enter a number with " + ((decimals) ? "up to " + decimals : "no") + " decimal places into %f.", this);
      return false;
    }

    var minValue = (isNaN(this.minValue)) ? Number.negativeInfinity : Number(this.minValue);
    var maxValue = (isNaN(this.maxValue)) ? Number.positiveInfinity : Number(this.maxValue);

    if (this.value < minValue)
    {
      this.select();
      this.focus();
      validateAlert("Please enter a number greater than or equal to " + minValue + " into %f. (This is an arbitrary minimum imposed by Incorporator.)", this);
      return false;
    }
    else if (this.value > maxValue)
    {
      this.select();
      this.focus();
      validateAlert("Please enter a number less than or equal to " + maxValue + " into %f. (This is an arbitrary maximum imposed by Incorporator.)", this);
      return false;
    }
  }
  return true;
}

function validateChecked()
{
  // Get the array for this checkbox/radio button group
  var checkboxes = this.form[this.name];
  
  if (checkboxes[0] && checkboxes[0].mandatory && !checkboxes[0].disabled)
  {
    for (var i = 0; i < checkboxes.length && !checkboxes[i].checked; i++);

    if (i >= checkboxes.length)
    {
      checkboxes[0].focus();

      //alert("Please tick the relevant name(s).");
      if (this.message)
		    alert(this.message);
		  else
        validateAlert("Please select an option in %f.", this);
      return false;
    }
  }
  else
  {
    if (checkboxes.mandatory && !checkboxes.checked && !checkboxes.disabled)
    {
      checkboxes.focus();

      //alert("Please tick the relevant name(s).");
      if (this.message)
		    alert(this.message);
		  else
        validateAlert("Please select an option in %f.", this);
      return false;
    }
  }
  return true;
}

function validateDate() 
{
  // private month conversion function
  function lpdt_monthName(intMonth)
  {
    switch(parseInt(intMonth))
    {
      case 1:
        return "January";
      case 2:
        return "February";
      case 3:
        return "March";
      case 4:
        return "April";
      case 5:
        return "May";
      case 6:
        return "June";
      case 7:
        return "July";
      case 8:
        return "August";
      case 9:
        return "September";
      case 10:
        return "October";
      case 11:
        return "November";
      case 12:
        return "December";
    }
  }

  var intDay, intMonth, intYear;
  var blnDay, blnMonth, blnYear;

  var valid = false;

  var varForm = this.form;
  var varFirstField = null;

  var strName = this.name;
  strName = strName.substr(0, strName.lastIndexOf("_"));

  var now = new Date();

  var varYear = varForm[strName + "_year"];
  if (varYear)
  {
    varFirstField = varYear;

    var strYear = varYear.options[varYear.selectedIndex].value;
    if (strYear == "")
    {
      intYear = now.getFullYear();
    }
    else
    {
      blnYear = true;
      intYear = parseInt(strYear, 10);
    }
  }
  else
  {
    intYear = now.getFullYear();
  }

  var varMonth = varForm[strName + "_month"];
  if (varMonth)
  {
    varFirstField = varMonth;

    var strMonth = varMonth.options[varMonth.selectedIndex].value;
    if (strMonth == "")
    {
      intMonth = now.getMonth() + 1;
    }
    else
    {
      blnMonth = true;
      intMonth = parseInt(strMonth, 10);
    }
  }
  else
  {
    intMonth = now.getMonth() + 1;
  }

  var varDay = varForm[strName + "_day"];
  if (varDay)
  {
    varFirstField = varDay;

    var strDay = varDay.options[varDay.selectedIndex].value;
    if (strDay == "")
    {
      intDay = now.getDate();
    }
    else
    {
      blnDay = true;
      intDay = parseInt(strDay, 10);
    }
  }
  else
  {
    intDay = now.getDate();
  }

  if (blnDay)
  {
    switch (intMonth)
    {
      case 4:
      case 6:
      case 9:
      case 11:
        valid = intDay > 0 && intDay <= 30;
        break;
      case 2:
        var max;
        if (intYear % 100 == 0)
        {
          if (intYear % 400 == 0)
          {
            max = 29;
          }
          else
          {
            max = 28;
          }
        }
        else if (intYear % 4 == 0)
        {
          max = 29;
        }
        else
        {
          max = 28;
        }
        valid = intDay > 0 && intDay <= max;
        break;
      default:
        valid = intDay > 0 && intDay <= 31;
        break;
    }
  }
  else
  {
    valid = true;
    if (intMonth == (now.getMonth() + 1))
    {
      intDay = now.getDate();
    }
    else
    {
      intDay = 1;
    }
  }

  if (!valid)
  {
    if (varFirstField)
      varFirstField.focus();
    alert("The date selected does not exist. (e.g. 29 Feb in a non leap year). Please check the day of the month.");
    return false;
  }

  var date = new Date(intYear, intMonth-1, intDay, 0, 0, 0);
  if (this.maxValue)
  {
    if (this.maxValue < date)
    {
      this.focus();
      var strDate = '';
      strDate += (blnDay) ? this.maxValue.getDate() : '';
      strDate += (strDate != '') ? ' ' : '';
      strDate += (blnMonth) ? lpdt_monthName(this.maxValue.getMonth() + 1) : '';
      strDate += (strDate != '') ? ' ' : '';
      strDate += (blnYear) ? this.maxValue.getFullYear() : '';

      var message = 'The date selected must be earlier than (or on) ' + strDate + '.';
      alert(message);

      return false;
    }
  }
  if (this.minValue)
  {
    if (this.minValue > date)
    {
      this.focus();
      var strDate = '';
      strDate += (blnDay) ? this.minValue.getDate() : '';
      strDate += (strDate != '') ? ' ' : '';
      strDate += (blnMonth) ? lpdt_monthName(this.minValue.getMonth() + 1) : '';
      strDate += (strDate != '') ? ' ' : '';
      strDate += (blnYear) ? this.minValue.getFullYear() : '';

      var message = 'The date selected cannot precede ' + strDate + '.';
      alert(message);
      return false;
    }
  }
  return true;
}


function validateFileUpLoad()
{
  var vForm = this.form;
  var aryFieldName = this.name.split("_");
  var vFieldName = aryFieldName[0];

  if (vForm.elements(vFieldName + '_delete') && !vForm.elements(vFieldName + '_delete').checked)
    this.mandatory = false;

  this.validate1 = validateText;

  return this.validate1();
}