/*
* This notice must be untouched at all times.

============= META ==================
@name : jaxWidgets_Validator.js  
@version : 0.10 
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 27/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================

============== DESCRIPTION =============
The validator widget is a part of the jaxWidgets library. It provides
dynamic in-page validation of common fields.
=========================================

============= FEATURES ==================
- Uses jaxXML markup tags to specify designer friendly tags in HTML (.NET style)
- i18n support for strings
- Customisable UI
- Use on any number of fields
- Validates most common formats
============================================

============= CHANGELOG ==================

==========================================

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

// Register object
jaxWidgets.Validator = function()
{
	// Validation settings
	var isRequired = "false";
	
	// Common regexs
	var regexEmail = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
	var regexUrl = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
	var regexDate = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
	var regexTime = /^([1-9]|1[0-2]):[0-5]\d$/;
	var regexIP = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
	var regexInteger = /(^-?\d\d*$)/;       
	
	// United states specific regexs
	var regexPostcode_US = /\d{5}(-\d{4})?/;
	var regexSSN_US = /\d{3}-\d{2}-\d{4}/;   
	var regexPhone_US = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
	var regexState_US = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;
	
	// United Kingdom specific regexs
	var regexPostcode_UK = /^([A-Za-z]{1,2})([0-9]{2,3})([A-Za-z]{2})$/;   
	
	// i18n settings
	var strLocale = "US";	
	var strType = "String";
	var strRequired = "Required";
	var strInvalid = "Invalid format";

	// Internal global vars
	var tmpString;
	
	// Create validator
	this.load = function(element)
	{
		if(!element)
		{
			_Engine.writeError('jax Error: Validator cannot load');
			return;
		}
		
		var fieldElement = document.getElementById(element.getAttribute("ControlToValidate"));
		if(!fieldElement)
		{
			_Engine.writeError('jax Error: Validator is missing a ControlToValidate attribute');
			return;
		}		
		
		// Create validator layer
		var validatorElement = document.createElement("span");
		validatorElement.setAttribute("id",fieldElement.id+"_valid");
		
		element.parentNode.insertBefore(validatorElement,element.nextSibling);
		
		// Standard function to parse the custom jax tag
		this.parseTag(element,validatorElement);		
		
		// Create style for current element using DOM compatible function from Library
		_Library.setStyle(element, validatorElement);
		
		tmpString = validatorElement.getAttribute("isRequired")
		if(tmpString.toString().toLowerCase() == "true")
		{
			_Validator.validate(fieldElement.id);
		}
		
		// Register event handlers
		// Use quirksmode idea for flexible registration by copying existing events
		// onSubmit
		var parentForm = _Library.getParentForm(fieldElement);
		var oldEventCode = (parentForm.onsubmit) ? parentForm.onsubmit : function () {};
		parentForm.onsubmit = function () {oldEventCode(); return _Validator.validate(fieldElement.id)};		
		// onBlue
		var oldEventCode = (fieldElement.onblur) ? fieldElement.onblur : function () {};
		fieldElement.onblur = function () {oldEventCode(); return _Validator.validate(fieldElement.id)};
	};
	
	this.setInvalid = function(div)
	{
		div.innerHTML = div.getAttribute("strInvalid");
	};
	
	this.validate = function(id)
	{		
	    var element;
		if(!(element = document.getElementById(id)))
		{
			return false;
		}
		var validDiv = document.getElementById(id+"_valid");
		var validString = element.value;		
		if(validString.length == 0)
		{
			tmpString = validDiv.getAttribute("isRequired");
			var isRequired = tmpString.toString().toLowerCase();
			if(isRequired == "true")
			{
				validDiv.innerHTML = validDiv.getAttribute("strRequired");
				return false;
			}
			else
			{
				validDiv.innerHTML = "";
			}			
		}
		
		// If we have reached here, we can continue with validation
		var tmpLocale = validDiv.getAttribute("strLocale");
		switch(validDiv.getAttribute("strType"))
		{
			case "String" : 
				return true;
				break;
			
			case "Email" :  
				if(!validString.match(regexEmail))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "Url" :  
				if(!validString.match(regexUrl))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "Date" :  
				if(!validString.match(regexDate))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "Time" :  
				if(!validString.match(regexTime))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "IP" :  
				if(!validString.match(regexIP))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "Integer" :  
				if(!validString.match(regexInteger))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "Postcode" :
				switch(tmpLocale)
				{
					case "US" :  
						if(!validString.match(regexPostcode_US))
							{ this.setInvalid(validDiv); return false; }
						break;
					case "Email" :  
						if(!validString.match(regexPostcode_UK))
							{ this.setInvalid(validDiv); return false; }
						break;
				}
				break;
			
			// No need to check locale for SSN as it is US specific
			case "SSN" :  
				if(!validString.match(regexSSN_US))
					{ this.setInvalid(validDiv); return false; }
				break;
			
			case "Phone" :  
				switch(tmpLocale)
				{
					case "US" :  
						if(!validString.match(regexPhone_US))
							{ this.setInvalid(validDiv); return false; }
						break;															
				}
				break;
			
			// Only US States work for now
			case "State" :  
				switch(tmpLocale)
				{
					case "Email" :  
						if(!validString.match(regexState_US))
							{ this.setInvalid(validDiv); return false; }
						break;
				}
				break;																			
				
			// Do custom validation
			case "Custom" :
				if(!validString.match(validDiv.getAttribute("Match")))
					{ this.setInvalid(validDiv); return false; }
				break;
		}
		
		// If we have reached here, everything is OK		
		validDiv.innerHTML = "";
		return true;
	};		
	
	/********* Custom tag parser **********/
	this.parseTag = function(element,validatorElement)
	{					
	    if(element.getAttribute("Required"))
			validatorElement.setAttribute("isRequired",element.getAttribute("Required"));
		else
			validatorElement.setAttribute("isRequired",isRequired);
						
		if(element.getAttribute("TextRequired"))
			validatorElement.setAttribute("strRequired",element.getAttribute("TextRequired"));
		else
			validatorElement.setAttribute("strRequired",strRequired);		
			
		if(element.getAttribute("TextInvalid"))
			validatorElement.setAttribute("strInvalid",element.getAttribute("TextInvalid"));
		else
			validatorElement.setAttribute("strInvalid",strInvalid);
			
		if(element.getAttribute("Type"))
			validatorElement.setAttribute("strType", element.getAttribute("Type"));
		else
			validatorElement.setAttribute("strType", strType);
		
		if(element.getAttribute("Locale"))
			validatorElement.setAttribute("strLocale", element.getAttribute("Locale"));
		else
			validatorElement.setAttribute("strLocale", strLocale);
		
		if(element.getAttribute("Match"))
			validatorElement.setAttribute("strCustom", element.getAttribute("Match"));1
	};			
	
	this.registerWithEngine = function(_Validator)
	{
		var tag = "Validator";
		var handler = _Validator;
		_Engine.registerWidget(tag, handler);
	};
}
	
var _Validator = new jaxWidgets.Validator();
_Validator.registerWithEngine(_Validator);


