// Lemon (HK) Ltd

// Default messages in English
MESSAGE_MAP = {}
MESSAGE_MAP["MANDATORY"] = "Please enter [%1].\n"
MESSAGE_MAP["ISNAN"] = "[%1] should be a number.\n"
MESSAGE_MAP["OUT_OF_RANGE_MAX"] = "The maximum value of [%1] is %3!\n"
MESSAGE_MAP["OUT_OF_RANGE_MIN"] = "The minimum value of [%1] is %2!\n"
MESSAGE_MAP["MUST_BE_POSITIVE"] = "[%1] should be greater than zero!\n"
MESSAGE_MAP["SUPPRESS_ROUNDUP"] = "[%1] %2!\n"

var NONZERO = "NONZERO"

function errMsg(m, p1, p2, p3, p4, p5, p6)
{
	m = MESSAGE_MAP[m]

	if (p1)
		m = replace(m, "%1", p1)
	if (p2)
		m = replace(m, "%2", p2)
	if (p3)
		m = replace(m, "%3", p3)
	if (p4)
		m = replace(m, "%4", p4)
	if (p5)
		m = replace(m, "%5", p5)
	if (p6)
		m = replace(m, "%6", p6)

	return m
}

function setDefaultValue(obj, v)
{
	if (trim(obj.value).length == 0)
		obj.value = v
}

function checkNumber(obj, title, unit, mandatory, min, max, precision, scale, suppressRoundupMsg)
{
	var v = trim(obj.value)
	
	v = v.replace(/ /g, "");
	v = v.replace(/,/g, "");
	obj.value = v;

	if (v.length == 0)
	{
		return mandatory ? errMsg("MANDATORY", title) : ""
	}
	else
	{
		v = obj.value = replace(v, ",", "");

		if ( isNaN(v) )
		{
			return errMsg("ISNAN", title)
		}
		else
		{
			v = v * 1

			if ((precision || scale) && max == 0)
			{
				max = Math.pow(10, precision - scale) - Math.pow(10, scale * -1);
			}

			if (max == NONZERO && v >= 0)
				return errMsg("OUT_OF_RANGE_MAX", title, unit, 0)
			else if ((precision || scale || max) && v > max)
				return errMsg("OUT_OF_RANGE_MAX", title, unit, formatCurrency(max))

			if (min == NONZERO && v <= 0)
				return errMsg("MUST_BE_POSITIVE", title, 0)

			if (v < min)
				return min == 0 ? errMsg("MUST_BE_POSITIVE", title, formatCurrency(min)) : errMsg("OUT_OF_RANGE_MIN", title, formatCurrency(min));

			if (precision || scale)
			{
				var v_ = Math.round(v * Math.pow(10, scale)) / Math.pow(10, scale);
				if (v != v_)
				{
					if (suppressRoundupMsg)
						return errMsg("SUPPRESS_ROUNDUP", title, suppressRoundupMsg);
					else
						obj.value = v_
				}
			}
		}
	}
	return "";
}

function formatCurrency(value)
{
	var strValue =  "" + value;
	var i = strValue.indexOf('.');
	var strDisplay = "";
	if (i < 0)
		i=strValue.length;
	else
		strDisplay = strValue.substring(i,strValue.length);
	for(i=i-3;i>0;i-=3)
	{
		strDisplay = "," + strValue.substring(i,i+3) + strDisplay;
	}
	strDisplay = strValue.substring(0,i+3) + strDisplay;
	return strDisplay;
}

function replace(str, src, target)
{
	var t = "", j = 0;

	while (1)
	{
		var i = str.indexOf(src, j);
		if (i == -1)
		{
			return t += str.substring(j)
		}
		else
		{
			t += str.substring(j, i) + target
			j = i + src.length
		}
	}
}

function isSpace(c)
{
	return c==' ' || c=='\t' || c=='\n' || c=='\r'
}

function trim(s)
{
	var j = s.length
	for (var i=j; --i>=0&&isSpace(s.charAt(i)); --j);
	for (var i=0; i<j&&isSpace(s.charAt(i)); i++);
	return s.substring(i, j)
}
