var MAX_CURRENCY = 1000000000.00;
var MIN_CURRENCY = -1000000000.00;
var MAX_CURR_STRING = "1000000000.00";
var MIN_CURR_STRING = "0.00";

var MAX_INTEGER = 1000000000.00;
var MIN_INTEGER = -1000000000.00;


// Function to limit the characters to be input into a text area
var nav4 = window.Event ? true : false;

function CombineEventHandlersAND()
{
    var argumentsTop = CombineEventHandlersAND.arguments;

    return function()
    {
        var arguments = argumentsTop; // We need to do this so that the anonymous function copies the VALUE of argumentsTop as it's being created (instead of just adding a reference to the globally available CombineEventHandlersAND.arguments)

        var result = true;
        for (var i = 0; i < arguments.length; i++)
        {

            // Call the function with the correct 'this' keyword
            this.Func4b93e166a0784b4aafb07ac4867eeb1a = arguments[i];
            result = result & this.Func4b93e166a0784b4aafb07ac4867eeb1a();
        }

        this.Func4b93e166a0784b4aafb07ac4867eeb1a = undefined;
        return result;
    }
}

function LimitTextArea() {
	var objects = document.page.objects;

/*
	if (nav4)
	{
		var whichCode = e.which;
	} else {
		if (e.type == "keypress")
		{
			var whichCode = e.keycode;
		} else {
			var whichCode = e.button;
		}
	}

	
	if ((objects.value.length > MaxChars) && (whichCode != 8) && (whichCode != 127))
	{
		alert("You have reached the maximum allowed character limit of "+MaxChars+" letters, numbers and spaces.");
		return false;
	}
*/

	var answer = objects.value.replace(/^\s*(.*)\s*$/, '$1');
	if (answer.length < 1)
	{
		alert("UKcorporator detects that you have not inputted any wording for the objects clause(s). Please input appropriate wording.");
		return false;
	}

	// BW 20/3/03 - Mod to force checking of number of "lines" not number of characters.
	var charsperline = 115;
	var maxlines = 42;
	var currentline = 1;
	var currentchar = 0;

	for (charcounter=0; charcounter < objects.value.length; charcounter++)
	{
		if (objects.value.charCodeAt(charcounter)==13)
		{
			currentline++;
			currentchar = 0;
		} else {
			currentchar++;
			if (currentchar==charsperline)
			{
				currentline++;
				currentchar = 0;
			}
		}
	}

	// if ((currentline > maxlines) && (whichCode != 8) && (whichCode != 127))
	if (currentline > maxlines)
	{
		alert("Sorry, but you have exceeded the limit of text which UKcorporator, as presently configured, allows in the text field. Please reduce the amount of text in your proposed objects clause. (You will be less likely to exceed the limit if you eliminate some paragraph returns.)");
		return false;
	}

	// End BW 20/3/03

	return true;
}

// Function to ensure that text is entered in a tarea
function validateTarea()
{
	var answer = this.value.replace(/^\s*(.*)\s*$/, '$1');
	if (answer.length < 1)
	{
		alert("UKcorporator detects that you have not inputted any wording for the objects clause(s). Please input appropriate wording.");
		return false;
	}
	return true;
}


/* Function to catch enter from causing form submission */
function catchEnter(e) {
  var nav4 = window.Event ? true : false;

  if (nav4) // Navigator 4.0x
    var whichCode = e.which
  else // Internet Explorer 4.0x
    if (e.type == "keypress") // the user entered a character
      var whichCode = e.keyCode
    else
      var whichCode = e.button;

  if (whichCode == 13)
	return false;
}

function validateAlert(message, field) {
  var fieldText = ((field.text) ? "the \"" + field.text + "\"" : "this") + " field";
  message = message.replace(/%f/, fieldText);
  alert(message);
}

function validateSelection() {
  if (!this.mandatory && (this.selectedIndex <= 0 || this.options[this.selectedIndex].value == null))
    return true;

	if (this.selectedIndex <= 0 || this.options[this.selectedIndex].value == null){
		this.focus();
	  validateAlert("Please select an option in %f", this);
		return false;
	}
	return true;
}

var validateShareAmountMessageTotal = -1;
function validateShareAmount()
{
    var totalValue = validateShareAmountValuePerShare * this.value;
    //alert('validateShareAmountMessageTotal:' + validateShareAmountMessageTotal + ';validateShareAmountValuePerShare:' + validateShareAmountValuePerShare + '; this.value:' + this.value + ';total:' + totalValue);
    if (totalValue != validateShareAmountMessageTotal && totalValue >= 10000)
    {
        validateShareAmountMessageTotal = totalValue;
        var validateMessage = "UKcorporator detects that the total amount of money which this shareholder agrees to pay for the shares (and therefore the total amount of money which this shareholder will be LEGALLY BOUND to pay for the shares) is somewhat large, namely " + totalValue;
        validateMessage = validateMessage + " pounds (" + this.value + " shares x " + validateShareAmountValuePerShare + " per share). UKcorporator, therefore guesses that maybe you do not in fact intend (or may now not in fact intend) that this shareholder be legally obliged to pay such a large amount of money. If so, please adjust your entries as necessary (you will need to step back if you intend to adjust the amount per share value). Otherwise please proceed as normal (and please note that you will not be given this warning message a second time on this occasion and on your current visit to this page and in respect of the exact same entries).";
        alert(validateMessage);
        return false;
    }
    return true;
}

function validateDataEntered(formObj)
{
  formObj = (typeof formObj == 'undefined') ?
    this : formObj;
  
  var value = formObj.value.replace(/^\s*(.*)\s*$/, '$1');

  if (!formObj.mandatory && value == "")
    return true;

  if (!value || value == "")
  {
    formObj.focus();
    formObj.select();
    
    if (formObj.comment) {
      validateAlert("Please enter some information"+ comment + " %f.", formObj);
    }
    else {
      validateAlert("Please enter some information into %f.", formObj);
    }
    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, ''), 10))) {
      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. Also, if you used commas, please ensure correct comma placement.";
    }
    validateAlert(message, this);
    return false;
  }

  if (this.value.indexOf('0') == 0) {
  	message = "Please enter a number (1 or greater) in digits not words, and with no decimal point or spaces. The first digit should not be a zero.";
	validateAlert(message, this);
	return false;
  }
  
  var num = parseInt(this.value, 10);
  // var minValue = Number.MIN_VALUE;
  var minValue = 1;
  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 (in digits, not words) less than or equal to " + maxValue + " into %f.", this);
    return false;
  }
  return true;
}


function validateNeilInteger() {
  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, ''), 10))) {
      message = "Please enter a number (in digits, not words) into %f.";
       validateAlert(message, this);
    } else {
      message = "If you choose to enter anything into this field it must be a non-decimal \'continous number\' (i.e. without spaces) in digits (not words). Also, if you used commas, please ensure correct comma placement.";
        alert(message) ;
    }
   
    return false;
  }

  var num = parseInt(this.value, 10);
  var minValue = 0;
  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 is an arbitrary minimum imposed by Incorporator.)", 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 is an arbitrary maximum imposed by Incorporator.)", this);
    return false;
  }
  return true;
}


function validatePhoneNumber() {
  if (!this.mandatory && this.value =="")
    return true;

  if (this.mandatory && this.value == "") {
    alert("Please ensure your telephone number has been inserted.");
  	return false;	
  }	
  
  //var pattern = /^(([0-9]+)|([1-9][0-9]{0,2}(,[0-9]{3})+))$/;
  //var pattern = /[0-9]/;
  var pattern = /[0-9]/;

  if ((!this.value || this.value == "") || this.value.search(pattern) < 0) {
    this.select();
    this.focus();

    var message;

    if (isNaN(parseInt(this.value.replace(/,/g, ''), 10))) {
      message = "You have entered details in the telephone number field which do not include any digits.";
      alert(message) ;
    } else {
      message = "You have entered details in the telephone number field which do not include any digits.";
      alert(message) ;
    }
   
    return false;
  }

  var num = parseInt(this.value, 10);
  var minValue = 0;
  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();

    message = "You have entered details in the telephone number field which do not include any digits.";
    alert(message) ;

    return false;
  } else if (num > this.maxValue) {
    this.select();
    this.focus();

    message = "You have entered details in the telephone number field which do not include any digits.";
    alert(message) ;

    return false;
  }
  return true;
}

function validatePIN() {
  if (!this.mandatory && this.value == "")
    return true;

  var pin_size = (this.value).length;
  if (pin_size < 8) {
    alert('Please enter at least 8 characters into the \"Password\" field');
    return false;
  }

  var pattern = /^[a-z0-9]*$/i;
  if ((!this.value || this.value == "") || this.value.search(pattern) < 0) {
    this.select();
    this.focus();
    alert("This must be comprised of letters and / or numbers. It is case sensitive.");
    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 pattern = /^([+\-]?(([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, separated by a decimal place and without typing in any currency symbol and greater than \'0.00\' e.g. \'1.00\') into %f.", this);
    return false;
  }

  if (this.value.indexOf('00') == 0) {
  	message = "Please enter a number (1 or greater) in digits not words, and with no spaces. The first digit should not be a zero.";
	validateAlert(message, 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;
}

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,})$/;
  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, and be careful about spaces, either before, within or after the email address)", 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 {
    if (this.value.indexOf('0') == 0) {
  		message = "Please enter a number (1 or greater) in digits not words, and with no spaces. The first digit should not be a zero.";
		validateAlert(message, this);
		return false;
    }
    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 validateLength() {
  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;
      }
    }
  }
  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).");
      validateAlert("Please select an option or options in the second box.", this);
      return false;
    }
  } else {
    if (checkboxes.mandatory && !checkboxes.checked && !checkboxes.disabled) {
      checkboxes.focus();

      alert("Please select the relevant option.");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  }
  return true;
}

function validate0220Checked() {
  // 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 select the relevant option.");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  } else {
    if (checkboxes.mandatory && !checkboxes.checked && !checkboxes.disabled) {
      checkboxes.focus();

      alert("Please select the relevant option.");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  }
  return true;
}

function validateCheckedSelect() {
  // 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 select the relevant name(s).");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  } else {
    if (checkboxes.mandatory && !checkboxes.checked && !checkboxes.disabled) {
      checkboxes.focus();

      alert("Please select the relevant name(s).");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  }
  return true;
}

function validateOption() {
  // 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 select the relevant option.");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  } else {
    if (checkboxes.mandatory && !checkboxes.checked && !checkboxes.disabled) {
      checkboxes.focus();

      alert("Please select the relevant option.");
      //validateAlert("Please select an option in %f.", this);
      return false;
    }
  }
  return true;
}

function validateRadio() {
  // Get the array for this checkbox/radio button group
  var radio = this.form[this.name];

  // Check for single radio button... has no .length property
  if( !(radio.length) )
  {
        if( !(radio.checked) )
        {
            radio.focus();
            if (radio.alerttext)
            {
              alert(radio.alerttext);
            } else {
            alert("Please select an option.");
            }
            return false;
        } else return true;
  }
  for (var i = 0; i < radio.length && !radio[i].checked; i++);

  if (i >= radio.length) {
    radio[0].focus();
    if (radio.alerttext)
    {
      alert(radio.alerttext);
    } else {
    alert("Please select an option.");
    }
    return false;
  }

  return true;
}

function validatePattern() {
  if (!this.mandatory && this.value == "")
    return true;

  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 validateCardPattern() {
  if (!this.mandatory && this.value == "")
    return true;

  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( valueType , this);
    return false;
  }
  return true;
}

function validateAuthData()
{
  switch (this.name)
  {
    case 'auth_rep_forename':
      message = 'Please enter every forename in full for the human representative for the company.';
      pattern = /^[\w\s'.,-_`"]+$/;
      break;
    case 'auth_rep_surname':
      message = 'Please enter the surname of the human representative for the company.';
      pattern = /^[\w\s'.,-_`"]+$/;
      break;
    case 'auth_telephone':
      message = 'Please enter the last 3 digits of the person\'s telephone number.';
      pattern = /^[0-9]{3}$/;
      break;
    case 'auth_birth_town':
      message = 'Please enter the first 3 letters of the person\'s town of birth.';
      pattern = /^[A-Za-z]{3}$/;
      break;
    case 'auth_eye_colour':
      message = 'Please enter the first 3 letters of the person\'s eye colour.';
      pattern = /^[A-Za-z]{3}$/;
      break;
    default:
      message = 'Please enter authentication data.';
      pattern = /^[\w]+$/;
      break;
  }

  // return if blank an not mandatory
  if (!this.value || this.value == "")
  {
    if (this.mandatory)
    {
      validateAlert(message, this);
      this.focus();
    }
    return !this.mandatory;
  }

  // checks if the data is valid
  var matchArray = this.value.match(pattern);
  if (matchArray == null)
  {
    this.select();
    this.focus();
    validateAlert(message, this);
    return false;
  }
  return true;
}