/**
 * Validates the format of a given string.
 * 
 * @param string value
 * @return string
 */
function awepop_validateStringFormat(value)
{
	var actual = value[0];
	var i = 0;
	var ok = true; //todos son blancos
	var newBeginning;
	var newValue;
	var fin = value.length;
	
	while((i < fin) && (ok))
	{
		if (actual == " ")
		{
			i++;
			actual = value[i];
		}
		else 
		{
			ok = false;
			newBeginning = i;
		}		
	}
	
	if (ok)
		return "";
	else
		return value.substr(newBeginning, value.length);
}

/**
 * Validates an email.
 * 
 * @param string emailValue
 * @return boolean
 */
function awepop_validateEmail(emailValue)
{
  	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailValue))
   		return true;
   	else
   		return false;
}

/**
 * Validates the fields of a form.
 * 
 * @param string The ID of the field for email.
 * @param string The ID of the field for name.
 * @param string The ID of the field for surname. (Optional)
 * @return boolean
 */
function awepop_validateForm()
{
	var _email = document.getElementById(arguments[0]);
	var _name = document.getElementById(arguments[1]);
	
	if (arguments[2])
		var _surname = document.getElementById(arguments[2]);
	
	
	_name.value = awepop_validateStringFormat(_name.value);
	if (_name.value.length == 0)
	{
		alert("El nombre es obligatorio.");
		return false;
	}	
	else
	{
		if ((_name.value.length < 3) || (_name.value.length > 50))
		{
			alert("El nombre debe tener entre 3 y 50 caracteres.");
			return false;
		}
		else
		{
			_email.value = awepop_validateStringFormat(_email.value);
			if (_email.value.length == 0)
			{
				alert("El email es obligatorio.");
				return false;
			}
			else
			{
				if (awepop_validateEmail(_email.value))
				{
					if (_surname)
					{
						_surname.value = awepop_validateStringFormat(_surname.value);
						if ((_surname.value.length < 3) || (_surname.value.length > 50))
						{
							alert("El apellido debe tener entre 3 y 50 caracteres.");
							return false;
						}
						else
							return true;
					}
					else
						return true;
				}
				else
				{
					alert("El email ingresado es incorrecto");
					return false;
				}
			}
		}
	}
}
