/******************************************
Name:			smartforms.js
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
Date:			23/08/2006
Author:			James Condliffe
******************************************/
Event.observe(document,"dom:loaded",validateForms);

function validateForms() 
{
	var valForms = document.forms;

	for (var i=0; i<valForms.length; i++ ) 
	{		
		// check to see if we have any validation fields
		//exclude the top form
		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 message = $F("ValidateMessage") + ":\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 (!checkFieldRegex(els[i])) // regular expression validation
			{
				markInvalid(els[i]);
				var label = document.getElementById(els[i].id + "_label");
				fielderrors += "\n- " + label.firstChild.nodeValue;
			}
			else
			{
				markValid(els[i]);
			}
		}
	}
	
	// Additional check for > 0 interests checked
	var interests = $$("fieldset.radioset input[name='Interest']");
	if(interests.length > 0)
	{
	    var interestsLabel = interests[0].up("fieldset").down("legend").innerHTML;
	    var interestsValid = interests.any(function(o){return o.checked;})
	    if(!interestsValid)
	    {
	        fielderrors += "\n- " + interestsLabel;
	    }
	}

	if (fielderrors != "")
	{
		alert(message+fielderrors);
		return false;
	}
	else
		return true;
}

function checkFieldRegex(field)
{
	// Branch for field types
	if (field.getAttribute("type") == "checkbox")
	{
		//alert("checkbox: " + field.getAttribute("name"));
	    if(field.checked == true)
	        return true;
	    else
	        return false;
	}
	else if (field.type=="select-one")
	{	
		//alert("not checkbox: " + field.getAttribute("name"));
	      	
	    // Check against regular expression
	    var regex = new RegExp(field.getAttribute("validation") , "i");
	    return regex.test(field.options[field.selectedIndex].value);
	}
	else
	{	
		//alert("not checkbox: " + field.getAttribute("name"));
	   
	    // 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';
}

/*	Temporary hide referral option select boxes and texfields	*/
Event.observe(document,"dom:loaded",hideFormElements);
Event.observe(document,"dom:loaded",prepareReferralField);

function hideFormElements()
{
    //build a list of all fields that we want to hide
    var elmsToHide = new Array ("waveitemother");

    //using them we can then find the parent  so we cna hide the label as well
    for (var i = 0; i < elmsToHide.length; i++)
    {
        //check if the element exists
        if(!document.getElementById) return false;
	    if(!document.getElementById("lead_waveitemid")) return false;
		if(!document.getElementById(elmsToHide[i])) return false;
		
		//alert(elmsToHide[i]);
	    document.getElementById(elmsToHide[i]).parentNode.style.display = "none";
    }
    
	if(!document.getElementById("lead_waveitemid")) return false;
    var referral = document.getElementById("lead_waveitemid").options[document.getElementById("lead_waveitemid").selectedIndex].text;
    switch(referral)
    {
        case "Other (Please specify)":
	        document.getElementById("waveitemother").parentNode.style.display = "block";
            break;
    }

}


function prepareReferralField()
{
    if(!document.getElementById) return false;
	if(!document.getElementById("lead_waveitemid")) return false;
	
	//alert("Referral field exist");
	document.getElementById("lead_waveitemid").onchange = function()
	{
	    var referralIndex = document.getElementById("lead_waveitemid").value;
	    displayHTMLElement(referralIndex);
	}
}

function displayHTMLElement(pValue)
{
    hideFormElements();     //call this to reset the form in case the user changes their answer to tthe referral question
    
    //alert(pValue);
    switch(pValue)
    {
        case "104":
            //104 is the id taken from table that build the select box.
            //if the script stops working check that the number matches the ID in the database
            if(!document.getElementById) return false;
	        if(!document.getElementById("waveitemother")) return false;
	        document.getElementById("waveitemother").parentNode.style.display = "block";
            break;
    }
}
