/******************************************
Name:			smartforms.js
Date:			23/08/2006
Author:			James Condliffe
Description:	Smart forms validation using regular expressions
				in a custom form attribute.

				Based loosely around ppk's form validation script concept:
				http://www.quirksmode.org
******************************************/
addLoadEvent(validateForms);

function validateForms() 
{
	var valForms = document.forms;

	for (var i=0; i<valForms.length; i++ ) 
	{		
		// check to see if we have any validation fields
		var valFields = valForms[i].elements;
		
		for (var j=0; j<valFields.length; j++)
		{
			if (valFields[j].getAttribute("validation")) // a field in the form requires validation
			{
				if (typeof valForms[i].onsubmit != 'function') // only apply this once to each form
				{
					valForms[i].onsubmit = smartValidate;
					break;
				}
			}
		}
	}
}

function smartValidate()
{
	var els = this.elements;
	var message = "Please complete or correct the following required fields to continue:\n";
	var fielderrors = "";

	for (var i=0; i<els.length; i++)
	{
	    var validation;
	    	    
	    if (validation = els[i].getAttribute("validation"))
		{     
            if(validation.indexOf("compare")>-1) // if we're comparing against another field
            {
                // Get the other field's id and compare the two fields values
                var compelelement;
                var arrVal = validation.split(":");
                if(compelement = document.getElementById(arrVal[1]))
                {
                    if(compelement.value != els[i].value)
                    {
                        markInvalid(els[i]);
                        var label = document.getElementById(els[i].id + "_label");
                        var complabel = document.getElementById(compelement.id + "_label");
                        fielderrors += "\n- " + complabel.firstChild.nodeValue + " and " + label.firstChild.nodeValue + " must match";
                    }
                }
            }
            
            else if(els[i].getAttribute("type") == "radio")
	        {
	            var radioGroup = els[i].getAttribute("name");
				var label = document.getElementById(radioGroup + "_label");
	            var radioGroupOptions = document.getElementsByName(radioGroup);
	                	        
    	        if (!checkFieldGroupRegex(radioGroupOptions))
    	        {
    	            fielderrors += "\n- " + label.firstChild.nodeValue;
    	        }
    	        
    	        var relatedField =	label.getAttribute("rel");
    	        var radioGroupOptionExtrainfoReq = document.getElementById(relatedField).getAttribute("rel");
    	        
    	        if(document.getElementById(radioGroupOptionExtrainfoReq).checked && document.getElementById(relatedField).value == "")
    	        {
    	            markInvalid(document.getElementById(relatedField));
				    fielderrors += "\n- Please state charity registration number";
    	        }
    	        else
    	        {
    	            markValid(document.getElementById(relatedField));
    	        }
	        }
            else if (!checkFieldRegex(els[i])) // regular expression validation
			{
			    //console.log(!checkFieldRegex(els[i]));
				markInvalid(els[i]);
				var label = document.getElementById(els[i].id + "_label");
				fielderrors += "\n- " + label.firstChild.nodeValue;
			}
			else
			{
				markValid(els[i]);
			}
		}
	}

	if (fielderrors != "")
	{
		//console.log(message+fielderrors);
		alert(message+fielderrors);
		return false;
	}
	else
	    return true;
}

function checkFieldGroupRegex(fieldgroup)
{
    var groupResponse = false;
    for (var i=0; i < fieldgroup.length; i++)
    {
        if(fieldgroup[i].checked == true)
        {
            groupResponse = true;
        }
    }
    return groupResponse;
}

function checkFieldRegex(field)
{
    // Branch for field types
	if (field.getAttribute("type") == "checkbox" || field.getAttribute("type") == "radio")
	{
	    if(field.checked == true)
	        return true;
	    else
	        return false;
	}
	else
	{	
	    // Check against default value if greytext is on
	    if (field.className.indexOf("greytext") > -1 && !isBlank(field.defaultValue) && field.value == field.defaultValue)
		    return false;
    	
	    // Check against regular expression
	    var regex = new RegExp(field.getAttribute("validation") , "i");
	    return regex.test(field.value);
	}
}

/****
Marks a form element invalid
****/
function markInvalid(elem)
{
    // Only mark invalid if it's not a greytext issue
	if (elem.className.indexOf("greytext") == -1)
	    elem.style.backgroundColor='#E7E6D6';
}

/****
Marks a form element valid
*****/
function markValid(elem)
{
	elem.style.backgroundColor='#FFFFFF';
}

