﻿var MATCH_EMAIL_PATTERN = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

var neoForm = {

	validate: function(_containerID, _callback)
	{
		try
		{
			var formIsValid = true;
			var textfields	= $(_containerID + " input:text");
			var textareas	= $(_containerID + " textarea");
			var radiogroups	= $(_containerID + " .radiogroup");
			var checkgroups	= $(_containerID + " .checkgroups");
			var selects		= $(_containerID + " select");
			
			$(textfields).each(function(i){
				var textfield = $(this);
				
				if(textfield.hasClass("required") && textfield.val().length <= 0)
				{ 
					textfield.addClass("withErrors");
					formIsValid = false;
				}
				else if(textfield.hasClass("email_address") && !MATCH_EMAIL_PATTERN.test(textfield.val()))
				{
					textfield.addClass("withErrors");
					formIsValid = false;
				}
				else
				{
					textfield.removeClass("withErrors");
				}
			});

			$(textareas).each(function(i){

				var textarea = $(this);
				
				if(textarea.hasClass("required") && textarea.val().length <= 0)
				{ 
					textarea.addClass("withErrors");
					formIsValid = false;
				}
				else
				{
					textarea.removeClass("withErrors");
				}
			});
			
			$(radiogroups).each(function(i){
				
				var radiogroup = $(this);
				if(radiogroup.attr("id") == "") radiogroup.attr("id", "radiogroup" + i);
				var radioList = $( "#" + radiogroup.attr("id") + " input:checked");
				
				if(radioList.length == 0)
				{
					formIsValid = false;
					radiogroup.addClass("withErrors");
				}
				else
				{
					radiogroup.removeClass("withErrors");
				}
			});
			
			$(checkgroups).each(function(i){
				
				var checkgroup = $(this);
				if(checkgroup.attr("id") == "") checkgroup.attr("id", "checkgroup" + i);
				var checkList = $( "#" + checkgroup.attr("id") + " input:checked");
				
				if(checkList.length == 0)
				{
					formIsValid = false;
					checkgroup.addClass("withErrors");
				}
				else
				{
					checkgroup.removeClass("withErrors");
				}
			});
			
			$(selects).each(function(i){
				var select = $(this);
				
				if(select.val() == "default")
				{
					formIsValid = false;
					select.addClass("withErrors");
				}
				else
				{
					select.removeClass("withErrors");
				}
			});

			_callback(formIsValid);
			return formIsValid;
		}
		catch(e)
		{
			trace(e.description);
			console.log(e.description);
			return false;
		}
	},

	send: function(containerID, callback)
	{
		return this.validate(containerID, callback);
	}
};