/******************************************
Name:			forms.js
Description:	Provides functions used for validation
				and other form widget trickery
Date:			21/06/2006
Author:			James Condliffe
******************************************/

addLoadEvent(setupFormFields);
addLoadEvent(setupContactForm);
addLoadEvent(function(){setTimeout(initOverLabels, 50);});




/****
Contact form has a dropdown to switch between the various forms. Set up here.
****/
function setupContactForm()
{
	elem = document.getElementById("enquiry");
	
	if (elem)
	{
		elem.onchange=
			function()
			{
				this.form.action = this.value;
				this.form.submit();
			};
	}
}

/****
Each field is given a red border on focus
Optionally, fields may also have 'grey text' which is cleared on focus
****/
function setupFormFields()
{
	// Retrieve an array of all text fields and areas
	var textfields = getElementsByClassName(document, "input", "textfield");
	var textareas = getElementsByClassName(document, "textarea", "txtarea");
	var theFields = textfields.concat(textareas);

	// Examine each field
	for ( var i=0; i<theFields.length; i++)
	{
		var field = theFields[i];
		
		// Add border and remove grey text if required on focus
		field.onfocus = function()
			{
				this.style.border="1px solid #EE3338";

				if (this.className.indexOf("greytext")>-1 && this.value==this.defaultValue)
				{
					this.value="";
					this.style.textAlign="left";
					this.style.color="#000000";
				}
			};

		// Remove border and add grey text if required on blur
		field.onblur = function()
			{
				this.style.border="1px solid #7F9DB9";

				if (this.className.indexOf("greytext")>-1 && this.value=="")
				{	
					this.style.textAlign="center";
					this.style.color="#CCCCCC";
					this.value=this.defaultValue;
				}
			};

		// Apply initial grey text effects to fields if necessary
		if (field.className.indexOf("greytext")>-1)
		{
			if (field.value!=field.defaultValue && field.value!="")
			{
				field.style.textAlign="left";
				field.style.color="#000000";
			}
			else
			{
				field.style.textAlign="center";
				field.style.color="#CCCCCC";
				field.value=field.defaultValue;
			}
		}
	}
}


/****
Sets up the popup comment functionality
****/
function setupFormComments()
{
	var theform;
	var thelabels;

	theform = getElementsByClassName(document,"form","standard");

	for (var i=0 ; i<theform.length ; i++)
	{
		thelabels = getElementsByClassName(theform[0],"label","");
		
		for (var i=0 ; i<thelabels.length ; i++)
		{
			thelabels[i].onmouseover = function()
			{
				if (this.previousSibling.className == "comment")
					toggleFieldComment(this,this.previousSibling,"on");
			};

			thelabels[i].onmouseout = function()
			{
				if (this.previousSibling.className == "comment")
					toggleFieldComment(this,this.previousSibling,"off");
			};		
		}

	}
}

/*****
Display or hide the comment
*****/
function toggleFieldComment(obj, desc, toggle)
{
	if (toggle=='on') // display the tooltip thingy
	{    
		if ((desc.style.top == '' || desc.style.top == 0) && (desc.style.left == '' || desc.style.left == 0))
		{			
			x = findPosX(obj)-35;
			y = findPosY(obj)+20;
			
			desc.style.top = y + 'px';
			desc.style.left = x + 'px';
		}
		desc.style.visibility = "visible";
	}
	else
	{
		desc.style.visibility = "hidden";
	}
}

/****
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';
}

/****
Returns true if the email matches the regex
*****/
function isEmail(str) 
{
	//var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var emailReg = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";
	var regex = new RegExp(emailReg , "i");
	return regex.test(str);
}

/****
Returns true if value only contains spaces
*****/
function isBlank(val)
{
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
		}
	return true;
}



/***
Overlabels for login form
Original code and concept: http://www.alistapart.com/articles/makingcompactformsmoreaccessible
***/
function initOverLabels () 
{
    var form, labels, id, field;

    form = document.getElementById("login");
    
    // Exit if no login form
    if(!form)
        return;
    
    labels = form.getElementsByTagName("label");

    for (var i = 0; i < labels.length; i++) 
    {

        // Skip labels that do not have a named association with another field
        id = labels[i].htmlFor || labels[i].getAttribute('for');
        if (!id || !(field = document.getElementById(id))) {
        continue;
        }

        // Hide any fields having an initial value.
        if (field.value !== "") 
        {
            hideLabel(field.getAttribute("id"), true);
        }

        // Set handlers to show and hide labels.
        field.onfocus = function () 
            {
                hideLabel(this.getAttribute("id"), true);
            };
        
        // Hide label on field keydown as well, as this means that the cursor is in the box
        // This is intended to reduce the problem of people putting the cursor in the box before JS is loaded
        field.onkeydown = function()
            {
                hideLabel(this.getAttribute("id"), true);
            }

        field.onblur = function () 
            {
                if (this.value === "") 
                {
                    hideLabel(this.getAttribute("id"), false);
                }
            };
            

        // Handle clicks to LABEL elements (for Safari).
        labels[i].onclick = function () 
            {
                var id, field;
                id = this.getAttribute('for');
                if (id && (field = document.getElementById(id))) 
                {
                    field.focus();
                }
            };
    }
}

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}