/*
  Trims left side spaces from the given value and returns trimed string
 */
function ltrim(value) {
	if (value == null) return value;
	if (value.length < 1) return value;
	var result = new String(value);
	while (result.charAt(0) == ' ')
	{
		result = result.substr(1);
	}
	return result;
}

/*
  Trims right side spaces in the given value and returns trimed string
 */
function rtrim(value) {
	if (value == null) return value;
	if (value.length < 1) return value;
	var result = new String(value);
	while (result.charAt(result.length - 1) == ' ')
	{
		result = result.substring(0, result.length - 1);
	}
	return result;
}

/*
  Trims spaces from both ends in the given value and returns trimed string
 */
function trim(value) {
	return rtrim(ltrim(value));
}

function isChar(text) {
	var charCode = text.charCodeAt(0);
	return charCode > -1 && charCode < 128;
}

function isAlpha(text) {
	var charCode = text.charCodeAt(0);
	return (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123);
}

function isDigit(text) {
	var charCode = text.charCodeAt(0);
	return charCode > 47 && charCode < 58;
}

function isCtrlChar(text) {
	var charCode = text.charCodeAt(0);
	return (charCode > -1 && charCode < 32) || charCode == 127;
}

function isSpecialChar(text) {
	var specialCharSet = "()<>@,;:\\\".[]";
	return specialCharSet.indexOf(text.charAt(0)) >= 0;
}

function isSpace(text) {
	var charCode = text.charCodeAt(0);
	return charCode == 32;
}

function isAtom(text) {
	return isChar(text) && !isSpecialChar(text) && !isSpace(text) && !isCtrlChar(text);
}

/**
 * Returns true if passed text is valid e-mail address, othervise it 
 * returns false.
 */
function checkEmail(value) {
	// first check does given value is not empty
	if (value == null || trim(value).length < 1) return false;
	// trim value
	value = trim(value);
	// get first index of '@' in value string
	var atCharIndex = value.indexOf('@');
	// if '@' does not exist in value string or first character in the string
	// or last character in the string
	// or value string contains another '@' character
	// then this email address is invalid
	if (atCharIndex < 1 || atCharIndex == (value.length - 1) ||  value.indexOf('@', atCharIndex + 1) >= 0) return false;
	var localAddressPart = value.substring(0, atCharIndex);
	for (var charIndex = 0; charIndex < localAddressPart.length; charIndex++) {
		if (localAddressPart.charAt(charIndex) != ".") {
			if (!isAtom(localAddressPart.substr(charIndex, 1))) return false;
		} else {
			if (charIndex == 0 || charIndex == localAddressPart.length -1) return false;
		}
	}
	var domainPart = value.substring(atCharIndex + 1);
	if (domainPart.indexOf(".") < 0) return false;
	for (var charIndex = 0; charIndex < domainPart.length; charIndex++) {
		if (domainPart.charAt(charIndex) != ".") {
			if (! isAtom(domainPart.substr(charIndex, 1))) return false;
		} else {
			if (charIndex == 0 || charIndex == domainPart.length -1) return false;
		}
	}
	return true;
}
