// Use sub errors in english?
var use_sub_errors = false;

// IsSomething validators
function IsThis(str,this_str)
{
	for(var i=0; i<str.length; i++)
	{
		for(var j=0; j<this_str.length; j++)
		{
			if(str.charAt(i)==this_str.charAt(j))
				return true;
		}
	}
	return false;
}

function IsNumber(str)
{
  return (!isNaN(str));
}

function IsSpecialChars(str)
{
	return IsThis(str,"`()(\\~!?@^&*+\"|%:=,<>");
}

function IsTelecom(str)
{
	var validDelimiters = "()- +";
	var minDigitsInNumber = 8;

	var stripped_str = "";
	for (var i = 0; i < str.length; i++)
	{
		var c = str.charAt(i);
		if (validDelimiters.indexOf(c) == -1)
			stripped_str += c;
	}
	return (IsInteger(stripped_str) && stripped_str.length >= minDigitsInNumber);
}

function IsZipcode(str)
{
	if(!IsInteger(str))
	{
		subErrors.push("zipcode_Zipcode must be numbers");
		return false;
	}
	if(str.length != 4)
	{
		subErrors.push("zipcode_Zipcode must be 4 numbers");
		return false;
	}
	return (IsInteger(str) && str.length == 4 && !IsSpecialChars(str));
}

function IsEmail(str)
{
	var regexp = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;

	if(regexp.test(str))
		return true;
	else
	{
		subErrors.push("email_Email must be of correct format");
		return false;
	}
 	return false;
}

function IsLetters(str)
{
	return (typeof str == 'string' && !IsNumber(str));
}


function IsString(str)
{
	return (typeof str == 'string');
}

function IsEmpty(str)
{
	return ((str == null) || (str.length == 0))
}

function IsDigit (c)
{
	return ((c >= "0") && (c <= "9"))
}

function IsInteger(s)
{
/*
	if (IsEmpty(s))
	if (IsInteger.arguments.length == 1)
		return 0;
	else
		return (IsInteger.arguments[1] == true);
*/
	var i;
	for (i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if (!IsDigit(c)) return false;
	}
	return true;
}

// Misc functions for handling specific errors and sorry these are hardcodet to english locale atm
var subErrors = [];
function HasSubError(str)
{
	for (var i = 0; i < subErrors.length; i++)
	{
		if(subErrors[i].search(str+"_") == 0)
			return true;
 	}
	return false;
}

function GetLastSubError(str)
{
	for (var i = 0; i < subErrors.length; i++)
	{
		if(subErrors[i].search(str+"_") == 0)
			return subErrors[i].substr(str.length+1);
 	}
	return "";
}

// Handling of ids
var registeredIds = [];
function IsSectionDone(sectionid)
{
	for (var i = 0; i < registeredIds.length; i++)
	{
		if(registeredIds[i].search(sectionid+"_") != -1)
			return false;
 	}
	return true;
}

function RegisteredIdExists(id)
{
	for (var i = 0; i < registeredIds.length; i++)
	{
		if(registeredIds[i] == id)
			return true;
 	}
 	return false;
}

function FindRegisteredId(id)
{
	for (var i = 0; i < registeredIds.length; i++)
	{
		if(registeredIds[i] == id)
			return i;
 	}
	return "damnit_Kyle!";
}

function UnregisterId(id)
{
	if(RegisteredIdExists(id))
		registeredIds.splice(FindRegisteredId(id),1);
}

function RegisterId(id)
{
 	if(!RegisteredIdExists(id))
 	{
		registeredIds.push(id);
		return true;
	}
	else
		return false;
}

// Error functionality
function FormatError(msg)
{
  	return "<font class=\"errortxt\" color=\"red\"><br />"+msg+"</font>";
}

function DisplayError(id,msg)
{
	if(RegisteredIdExists(id))
		RemoveError(id);
	$("#"+id+"_icon").attr("style","display:none;");
	$("#"+id).attr("class","error");
	$("#"+id).after("<span id=\""+id+"_error\">"+FormatError(msg)+"</span>");
	RegisterId(id);
	subErrors = [];
}

function DisplayErrorFaded(id)
{
	$("#"+id).attr("class","error_faded");
}

function RemoveError(id)
{
	$("#"+id).removeAttr("class");
	$("#"+id+"_error").remove();
	UnregisterId(id);
}

function PutIcon(id)
{
	if(document.getElementById(id+"_icon").style.display == "none")
	{
		$("#"+id+"_icon").attr("style","");
	}
}

function ForceRemoveAllErrors(sectionid)
{
	var start_length = registeredIds.length
	for (var i = 0; i < start_length; i++)
	{
		RemoveError(registeredIds[0]);
	}
}
// Functions to call when a field needs validation
// Arguments from Setup() are passed to Validate() so they're the same:
// id		:	An element id				ex. <input id="myTextInput" ... />
// method	:	Method for validating see Validate() further down for implemented methods.
// errmsg	:	Text to write when validation fails (see above for special hardcodet locale detailed errors
// optional	:	Boolean to tell the Validate() function if a field can be blank or not.
//				true = optional = can be blank
//				false = not optional = can not be blank

function Setup(id,method, errmsg, optional)
{
	if(document.getElementById(id) != null)
	{
		// Initial stuff
		RemoveError(id);

		$("#"+id).focus( function() {
			if(!RegisteredIdExists(this.id))
				RemoveError(this.id);
			else
				DisplayErrorFaded(this.id);
		});
		$("#"+id).blur(	function() {
			Validate(this.id,method, errmsg, optional);
		});
		// Put status icon
		// This is site implementation specific...
		// In this case we use some css stunt... The commented under this uses a <img> tag
		$("#"+id).wrapAll("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td></td><td class=\"validate_checkmark\"><div id=\""+id+"_icon\" class=\"validate_checkmark\" style=\"display:none;\"><div/></td></tr>");
		//$("#"+id).wrapAll("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td></td><td><img id=\""+id+"_icon\" style=\"display:none;\" src=\"img/check.png\" width=\"18\" height=\"23\" /></td></tr>");
	}
	else
	{
		// Comment out if you write broken code :)
		alert("validate_fields.js:\nYou're trying to setup validation on a non-exsisting id \""+id+"\"");
	}
}

function Validate(id, method, errmsg, optional)
{
	if(document.getElementById(id) != null)
	{
		// Initial stuff
		RemoveError(id);
		//alert("Validating: "+id+" as \n"+$("#"+id).val()+" as "+method);
		//var empty_errmsg = /*"";*/"Please specify";
		var id_value = $("#"+id).val();

		if(method == "string")
		{
			if(!optional)
			{
				if(IsEmpty(id_value))
					DisplayError(id,errmsg);
				else
				{
					if(IsString(id_value))
					{
						RemoveError(id);
						PutIcon(id);
					}
					else
						DisplayError(id, errmsg);
				}
			}
			else
			{
				if(IsString(id_value) || IsEmpty(id_value))
				{
					RemoveError(id);
					if(!IsEmpty(id_value))
						PutIcon(id);
					else
						$("#"+id+"_icon").attr("style","display:none;");
				}
				else
					DisplayError(id, errmsg);
			}
		}

		if(method == "email")
		{
			if(!optional)
			{
				if(IsEmpty(id_value))
					DisplayError(id,errmsg);
				else
				{
					if(IsEmail(id_value))
					{
						RemoveError(id);
						PutIcon(id);
					}
					else if( HasSubError(method) && use_sub_errors)
						DisplayError(id, GetLastSubError(method));
					else
						DisplayError(id, errmsg);
				}
			}
			else
			{
				if(IsEmail(id_value) || IsEmpty(id_value))
				{
					RemoveError(id);
					if(!IsEmpty(id_value))
						PutIcon(id);
					else
						$("#"+id+"_icon").attr("style","display:none;");
				}
				else if( HasSubError(method) && use_sub_errors)
					DisplayError(id, GetLastSubError(method));
				else
					DisplayError(id, errmsg);
			}
		}

		if(method == "phone")
		{
			if(!optional)
			{
				if(IsEmpty(id_value))
					DisplayError(id,errmsg);
				else
				{
					if(IsTelecom(id_value))
					{
						RemoveError(id);
						PutIcon(id);
					}
					else
						DisplayError(id, errmsg);
				}
			}
			else
			{
				if(IsTelecom(id_value) || IsEmpty(id_value))
				{
					RemoveError(id);
					if(!IsEmpty(id_value))
						PutIcon(id);
					else
						$("#"+id+"_icon").attr("style","display:none;");
				}
				else
					DisplayError(id, errmsg);
			}
		}

		if(method == "zipcode")
		{
			if(!optional)
			{
				if(IsEmpty(id_value))
					DisplayError(id,errmsg);
				else
				{
					if(IsZipcode(id_value))
					{
						RemoveError(id);
						PutIcon(id);
					}
					else if( HasSubError(method) && use_sub_errors )
						DisplayError(id, GetLastSubError(method));
					else
						DisplayError(id, errmsg);
				}
			}
			else
			{
				if(IsZipcode(id_value) || IsEmpty(id_value))
				{
					RemoveError(id);
					if(!IsEmpty(id_value))
						PutIcon(id);
					else
						$("#"+id+"_icon").attr("style","display:none;");
				}
				else if( HasSubError(method) && use_sub_errors)
					DisplayError(id, GetLastSubError(method));
				else
					DisplayError(id, errmsg);
			}
		}

	}
}

