/*
 * Really easy field validation with Prototype
 * http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype
 * Andrew Tetlaw
 * Version 1.5.3 (2006-07-15)
 * 
 * Copyright (c) 2006 Andrew Tetlaw
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Updated by Greg Scott for Online Insight (2006-09-02)  
 * This update allows for the message to be placed in a summary area with the id of
 * validation_messages 
 * or in a message area for each field defined by using the id of the field with
 * the suffix "_mesg". For example if the field id is first_name then the message area
 * for the error message is called first_name_mesg 
 */
Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		this.options = Object.extend({}, options || {});
		this._test = test ? test : function(v,elm){ return true };
		this.error = error ? error : 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return this._test(v,elm);
	}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			useCustomMesgArea : false,
			useSummaryArea : false,
			specialMessage : "",
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var useCustomMesgArea = this.options.useCustomMesgArea;
			var useSummaryArea = this.options.useSummaryArea;
			var specialMessage = this.options.specialMessage;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, useCustomMesg : useCustomMesgArea, useSummary : useSummaryArea, aSpecialMessage : specialMessage, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var useCustomMesgArea = this.options.useCustomMesgArea;
		var useSummaryArea = this.options.useSummaryArea;
		var specialMessage = this.options.specialMessage;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, useCustomMesg : useCustomMesgArea, useSummary : useSummaryArea, aSpecialMessage: specialMessage, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, useCustomMesg : useCustomMesgArea, useSummary : useSummaryArea, aSpecialMessage: specialMessage, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		temp = this.options.onFormValidate(result, this.form);
		//make sure something that form validate brings something back
		if(temp != null)
		{
      result = temp;
    }
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			useCustomMesg : false,
			useSummary: false,
			aSpecialMessage: "",
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle,options.useCustomMesg,options.useSummary,options.aSpecialMessage);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	displayError : function(elm, mesg, options){
		options = Object.extend({
			useTitle : false,
			useCustomMesg : false,
			useSummary: false,
			aSpecialMessage:""
		}, options || {});
		
    var displayElm = elm;
		if(options.useCustomMesg)
		{
		  displayElm = $(Validation.getElmID(elm) + "_mesg");
    }
    else if(options.useSummary)
    {
      displayElm = $("validation_messages");
    }		
    
		var advice = $("advice-"+ Validation.getElmID(elm));
		if(typeof advice == 'undefined') {
			var errorMsg = options.useTitle ? ((elm && elm.title) ? elm.title : mesg) :mesg;
			advice = '<div class="validation-advice" id="advice-'+ Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
			switch (elm.type.toLowerCase()) {
				case 'checkbox':
				case 'radio':
					var p = elm.parentNode;

					if(p && !options.useCustomMesg && !options.useSummary) {
						new Insertion.Bottom(p, advice);
					} else {
						new Insertion.After(displayElm, advice);
					}
					break;
				default:
					new Insertion.After(displayElm, advice);
		    }
			advice = $('advice-'+ Validation.getElmID(elm));
		}else
		{
		  advice.innerHTML = mesg;
    }
		if(typeof Effect == 'undefined') {
			advice.style.display = 'block';
		} else {
			new Effect.Appear(advice, {duration : 1 });
		}
	},	
	test : function(name, elm, useTitle,useCustomMesg,useSummary,specialMessage) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		var displayElm = elm;
		if(useCustomMesg)
		{
		  displayElm = $(Validation.getElmID(elm) + "_mesg");
    }
    else if(useSummary)
    {
      displayElm = $("validation_messages");
    }
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(typeof advice == 'undefined') {
					var errorMsg = useTitle ? ((elm && elm.errormsg) ? elm.errormsg : v.error) : v.error;
					if(specialMessage != "")
					{
					   errorMsg=$(elm.name +"_errormsg").innerHTML;
          }
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;

							if(p && !useCustomMesg && !useSummary) {
								new Insertion.Bottom(p, advice);
							} else if (useSummary)
							{
							   displayElm.innerHTML = advice;
              }else
              {
								new Insertion.After(displayElm, advice);
							}
							break;
						default:
						if(useSummary)
						{
						  displayElm.innerHTML = advice;
            }else
							new Insertion.After(displayElm, advice);
				    }
					advice = $('advice-' + name + '-' + Validation.getElmID(elm));
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1});
				}
			}
			elm[prop] = true;
			if((elm.type.toLowerCase()=='radio') || (elm.type.toLowerCase() == "checkbox"))
			{
			   var theField = elm.form[elm.name];
			   for(var j=0;j < theField.length; j++)
			   {
			     	Element.removeClassName(theField[j],'validation-passed');
			      Element.addClassName(theField[j],'validation-failed');
         }
      }
      else
      {
        elm.removeClassName('validation-passed');
			  elm.addClassName('validation-failed');
      }		
      
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(typeof advice != 'undefined') advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			if(elm.type.toLowerCase()!='button')
			{
			 elm.addClassName('validation-passed');
      }			
			return true;
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return Try.these(
			function(){ return $('advice-' + name + '-' + Validation.getElmID(elm)) },
			function(){ return $('advice-' + Validation.getElmID(elm)) }
		);
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			Element.removeClassName(elm,'validation-failed');
			Element.removeClassName(elm,'validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : new Validator();
	},
	methods : {}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-zipcode', 'Please enter a valid zip code.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(v);
			}],			
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-one-required', 'Please select one of the options.', function (v,elm) {
				//find all the elements with this class name then prune it down to the 
				//ones with the same name of the current element being processed
	      var success = false;
				var options = document.getElementsByClassName("validate-one-required");
        var currentOptions = options.select(function(item) {          
         return (item.name == elm.name);
        })

				for(var i=0; i < currentOptions.length;i++)
				{			
				 if(currentOptions[i].checked)
				  {
				    success = true;
				    break;
          }
        }				
				return success;
			}],
	['validate-threepart-date', 'Please enter a valid date.', function (v,elm) {
				//find the three fields that make up this combination if joining them together does not 
        //make a valid date then validate fails;
        if(Validation.get('IsEmpty').test(v))
        {
          return false;
        }        				 
    		var regex = /^(\d{4})$/;
				if(!regex.test(v)) return false;
				
				var fieldPrefix = "field_"+elm.name.substring(0,elm.name.lastIndexOf("_"));
				var aMonth =$F(fieldPrefix+ '_month');
        var aDay =$F(fieldPrefix+ '_day');
        var aYear =$F(fieldPrefix+ '_year');
                
        if(isNaN(aMonth)||(aMonth=="") || isNaN(aDay) ||(aDay=="") || isNaN(aYear) ||(aYear=="") ||
          (parseInt(aMonth,10) < 1) || (parseInt(aMonth,10) > 12) || (parseInt(aDay,10) < 1) || (parseInt(aDay,10) > 31) ||
          (parseInt(aYear,10) < 1900) || (parseInt(aYear,10) > 2008))
        {
            return false;
        }
        
        if ( (parseInt(aMonth,10) == 4) || (parseInt(aMonth,10) == 6) || (parseInt(aMonth,10) == 9) || (parseInt(aMonth,10) == 11) )
        {
        	if ( parseInt(aDay,10) > 30 )
        	{
        		return false;
        	}
        }
              
        if (parseInt(aMonth,10) == 2)
        {
        	if (parseInt(aDay,10) > 29) 
        	{
        		return false;
        	}
        	if ( (parseInt(aDay,10) > 28) && !(isLeapYear(parseInt(aYear,10))) )
        	{
        		return false;
        	}
        }
        
				v = $F(fieldPrefix+'_month') + "/" + $F(fieldPrefix+'_day') + "/" + $F(fieldPrefix+'_year');				
        return Validation.get('validate-date').test(v);

			}],			
	['validate-threepart-month', 'Please enter a valid date.', function (v,elm) {
				//find the three fields that make up this combination if joining them together does not 
        //make a valid date then validate fails;
        if(Validation.get('IsEmpty').test(v))
        {
          return false;
        }        				 
               
        if(isNaN(v) || (parseInt(v,10) < 1) || (parseInt(v,10) > 12))
        {
            return false;
        }
        return true;

			}],			
	['validate-threepart-day', 'Please enter a valid date.', function (v,elm) {
				//find the three fields that make up this combination if joining them together does not 
        //make a valid date then validate fails;
        if(Validation.get('IsEmpty').test(v))
        {
          return false;
        }        				 
               
        if(isNaN(v) || (parseInt(v,10) < 1) || (parseInt(v,10) > 31))
        {
            return false;
        }
        return true;

			}],						
	['validate-select-required', 'Please select one of the options from the drop down box.', function (v,elm) {
	      //the assumption is that the first option in the select list is not valid
	      //so if selectedIndex > 0 then the field passed validation
	      return (elm.selectedIndex > 0);
			}],			
	['validate-phone', 'Please enter a valid phone number.', function (v,elm) {
	      //validate a phone number allow (404)555-6255 or 444-444-5554
	      var success = true;
	      var stripped = v.replace(/[\(\)\.\-\ ]/g, '');
	      if ((isNaN(parseInt(stripped))) || (!(stripped.length == 10)))
	      {
	         success =false;
        }
	      return  success;
			}],		      		
	['validate-email-confirm', 'Email addresses must match.', function(v,elm) {
			  var success = true;
			  var elementList = document.getElementsByClassName("validate-email");
			  for(i=0; i < elementList.length; i++)
			  {
			     if((v != "") && (elementList[i].id != elm.id) && (elementList[i].value != elm.value))
			     {
			       success = false;
			       break;
           }
        }
				return  success;
			}]
]);

function isLeapYear(yr) {
  return new Date(yr,2-1,29).getDate()==29;
}
