// CMS MailForm client scripts.

var CMS_MailForm_ClickFlag = false;
var CMS_MailForm_ClickFlagTimer = null;



function CMS_MailForm_Check()
{
    if (! CMS_MailForm_ClickFlag) 
        return true;
    
	for(var i = 0; i < document.forms[0].elements.length; i ++)
	{
        var el = document.forms[0].elements[i];
		if (el.name != null && el.name.indexOf("#") != -1 && ! CMS_MailForm_IsControlValid(el))
				return false;
	}
	
	return true;
}



function CMS_MailForm_SetClickFlag()
{
    CMS_MailForm_ClickFlag = true;
    if (CMS_MailForm_ClickFlagTimer != null)
        clearTimeout(CMS_MailForm_ClickFlagTimer);
    CMS_MailForm_ClickFlagTimer = setTimeout("CMS_MailForm_ClickFlag = false;", 1000);
}



function CMS_MailForm_IsControlValid(control)
{
	if (! CMS_IsStringEmpty(control.getAttribute("validator")))
	{
		var sExpr = control.getAttribute("validator");
		var sStartText = control.getAttribute("startText");
		
		if (sExpr == "notEmpty")
		{
			if (CMS_IsStringEmpty(control.value) || 
			    (! CMS_IsStringEmpty(control.value) && sStartText == control.value))
				return CMS_MailForm_ShowErrorMessage(control, CMS_MailForm_ErrorMessage_EmptyField);
			else
				return true;
		}
			
		if (sExpr == "email")
		{
			if (! control.value.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/g))
				return CMS_MailForm_ShowErrorMessage(control, CMS_MailForm_ErrorMessage_RegExpression);
			else
				return true;
		}

		var expr = eval("/" + sExpr + "/g");
		if (! control.value.match(expr))
			return CMS_MailForm_ShowErrorMessage(control, CMS_MailForm_ErrorMessage_RegExpression);
	}
	
	return true;
}



function CMS_MailForm_ShowErrorMessage(control, errorMessageTemplate)
{
	if (CMS_IsStringEmpty(control.getAttribute("ErrorMessage")))
	{
		alert(CMS_MailForm_ReplaceTemplate(errorMessageTemplate, control));
	}
	else
	{
		alert(control.getAttribute("ErrorMessage"));
	}
	
	control.focus();
	return false;
}



function CMS_MailForm_ReplaceTemplate(message, control)
{
	return message.replace(/##ControlName##/g, control.name.replace(/#/g, ""));
}



function CMS_MailForm_InitStartText(startNode)
{	
	var nodes = startNode.childNodes;
	for (var i=0; i < nodes.length; i ++)
	{
		CMS_StartText_Initialize(nodes.item(i));
		CMS_MailForm_InitStartText(nodes.item(i))
	}
}