// LyIntegerScript.js
// Copyright (c) 2000-2009, Lyria-W4.
// All rights reserved.
// @version	$Id: LyIntegerScript.js,v 1.2 2009/01/06 11:04:03 jls Exp $

// This function tests if the argument is an integer and return the result.
function IsExactInteger(str)
{
	var number = parseInt(str);
	result = isNaN(number);

	if (result)
		return false;

	// Return true only if number equals str (because parseInt('15h')=15).
	if (number.toString() == str)
		return true;
	else
		return false;
}

// This function tests if the argument is an integer and return the result
// (ignoring 0 at the beginning of the number)
function IsInteger(str)
{
	str = removeLeadingZeros(str);

	var number = parseInt(str);
	result = isNaN(number);

	if (result)
		return false;

	if (number.toString() == str)
		return true;
	else
		return false;
}

// This function remove leading '0' from the given string
// Doesn't work for negative numbers.
function removeLeadingZeros(str)
{
	// If more than 1 character try to remove the starting 0
	if (str.length > 1)
	{
		for (; str.charAt(0) == '0';)
			str = str.substring(1);

		// If the string was something like '000'
		if (str.length == 0)
			str= '0';
	}

	return str;
}

// This function tests if the field has a valid value.
function CheckIntegerField(form, fieldName, min, max, error)
{
	var value = form.elements[fieldName].value;
	// Check if the value is an integer
	var result = IsExactInteger(value);

 	// Check if the value is <= max and >= min
	if (((!result) && (value != '')) || (parseInt(value) < min) || (parseInt(value) > max))
	{
		var message = ReplaceString(error, "%1", value);
		alert(message);

		// Reset field
		form.elements[fieldName].value = form.elements[fieldName].defaultValue;
	}
}

// This function increments the value of the field.
function IncrementIntegerField(form, fieldName, min, max, pitch, check)
{
	var field = form.elements[fieldName];
	// Check if the value is an integer
	var result = IsExactInteger(field.value);

	if (field.value == "") // case of an empty value
	{
		if ((min <= 0) && (max >= 0))
			form.elements[fieldName].value = 0;
		else if (min > 0)
			form.elements[fieldName].value = min;
		else
			form.elements[fieldName].value = max;
	}
	else if ((!result) || (parseInt(field.value) < min - pitch))
		form.elements[fieldName].value = min;
	else if ((parseInt(field.value) > max - pitch))
		form.elements[fieldName].value = max;
	else
		form.elements[fieldName].value=(parseInt(field.value) + parseInt(pitch)).toString();

	if (check != "false")
		FieldChange(form, field, check);
}
