
/**************************************************************

	Script		: Validate (Electro Collect)
	Version		: 2.1
	Authors		: Samuel Birch
	Desc			: Form validation
	Licence		: Open Source MIT Licence

**************************************************************/

var Validate = new Class({
	
	getOptions: function(){
		return {
			validateOnBlur: true,
			errorClass: 'error',
			errorMsgClass: 'errorMessage',
			dateFormat: 'dd/MM/yy',
			onFail: Class.empty,
			onSuccess: false,
			showErrorsInline: true,
			label: ''
		};
	},

	initialize: function(form, options){
		this.setOptions(this.getOptions(), options);
		
		this.form = $(form);
		this.elements = this.form.getElements('.required');
		this.inputs = this.form.getElements('input');
		this.buttons = [];
		this.button = '';
		this.inputs.each(function(el){
			if(el.type == 'submit'){
				this.buttons.push(el);
				el.addEvent('click', function(e){
					this.button = el.name;
				}.bind(this));
			}
		}.bind(this));
		
		this.list = [];
		
		this.elements.each(function(el,i){
			if(this.options.validateOnBlur){
				el.addEvent('blur', this.validate.bind(this, el));
			}
		}.bind(this));
		
		this.form.addEvent('submit', function(e){
			var event = new Event(e);
			var doSubmit = true;
			//console.log(this.button);
			if(this.button == 'submit'){
			
			this.elements.each(function(el,i){
				if(! this.validate(el)){
					event.stop();
					doSubmit = false
					this.list.include(el);
				}else{
					this.list.remove(el);
				}
			}.bind(this));
			}
			if(doSubmit){
				if(this.options.onSuccess){
					event.stop();
					this.options.onSuccess(this.form);
				}else{
					this.form.getElement('input[type=submit]').setProperty('value',this.options.label);
				}
			}else{
				this.options.onFail(this.getList());
			}
			
		}.bind(this));
		
	},
	
	getList: function(){
		var list = new Element('ul');
		this.list.each(function(el,i){
			if(el.title != ''){
			var li = new Element('li').injectInside(list);
			new Element('label').setProperty('for', el.id).setText('Please enter a value for: '+el.title).injectInside(li);
			}
		});
		return list;
	},
	
	validate: function(el){
		var valid = true;
		if(el.type != 'checkbox'){
			this.showStatus(el, true);
		}
		
		this.clearMsg(el);
		
		switch(el.type){
			case 'text':
			case 'password':
			case 'textarea':
			case 'select-one':
				if(el.value != ''){
					if(el.hasClass('email')){
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(el.value.toUpperCase().match(regEmail)){
							valid = true;
							this.showStatus(el, true);
						}else{
							valid = false;
							//this.setMsg(el, 'Please enter a valid email address');
							this.showStatus(el, false, 'Please enter a valid email address');
						}
					}
					
//					if(el.name == "password")
//					{
//					    var confirmPassword = $('confirm');
//					    if(confirmPassword.value != ' ' && el.value != confirmPassword.value)
//					    {
//					        valid = false;
//					        this.showStatus(el, false, 'Your passwords must match');
//					    }
//					    else
//					    {
//					        valid = true;
//							this.showStatus(el, true);
//					    }
//					}
					
					if(el.name == "confirmpassword")
					{
					    var password = $('password');
					    if(el.value != password.value)
					    {
					        valid = false;
					        this.showStatus(el, false, 'Your passwords must match');
					    }
					    else
					    {
					        valid = true;
							this.showStatus(el, true);
					    }
					}
					
					if(el.hasClass('number')){
						
						/*var regNum = /[-+]?[0-9]*\.?[0-9]+/;*/
						var regNum = /^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
						
						if(el.name == "telephone")
						{
						    if(this.removeSpaces(el.value).length <= 11)
						    {
						        if(el.value.match(regNum)){
							        valid = true;
							        this.showStatus(el, true);
						        }else{
							        valid = false;
							        //this.setMsg(el, 'Please enter a valid number');
							        this.showStatus(el, false, 'Please enter a valid number');
						        }
						    }
						    else
						    {
						        valid = false;
						        //this.setMsg(el, 'Please enter a valid number');
						        this.showStatus(el, false, 'Please enter a valid number');
						    }
						}
						else
						{
						    if(this.removeSpaces(el.value).length <= 50)
						    {
						        if(el.value.match(regNum)){
							        valid = true;
							        this.showStatus(el, true);
						        }else{
							        valid = false;
							        //this.setMsg(el, 'Please enter a valid number');
							        this.showStatus(el, false, 'Please enter a valid number');
						        }
						    }
						    else
						    {
						        valid = false;
						        //this.setMsg(el, 'Please enter a valid number');
						        this.showStatus(el, false, 'Please enter a valid number');
						    }
						}
					}
					
					if(el.hasClass('postcode')){
						/*var regPC = /^(([A-PR-UWYZ]{1,2}[0-9]{1,2}[ABEHJMNPRVWXY]?)\s?([0-9][ABD-HJLNP-UW-Z]{2})|(GIR)\s?(0AA))$/*/
						var regPC = /(((^[BEGLMNS][1-9]\d?)|(^W[2-9])|(^(A[BL]|B[ABDHLNRST]|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]|F[KY]|G[LUY]|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]|M[EKL]|N[EGNPRW]|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKL-PRSTWY]|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)\d\d?)|(^W1[A-HJKSTUW0-9])|(((^WC[1-2])|(^EC[1-4])|(^SW1))[ABEHMNPRVWXY]))(\s*)?([0-9][ABD-HJLNP-UW-Z]{2}))$|(^GIR\s?0AA$)/;
						
						var elToUpper = el.value.toUpperCase();
						
						if(elToUpper.match(regPC)){
							valid = true;
							this.showStatus(el, true);
						}else{
							valid = false;
							//this.setMsg(el, 'Please enter a valid postcode');
							this.showStatus(el, false, 'Please enter a valid postcode');
						}
					}
					
					if(el.hasClass('date')){
						var d = Date.parseExact(el.value, this.options.dateFormat);
						if(d != null){
							valid = true;
							this.showStatus(el, true);
						}else{
							valid = false;
							//this.setMsg(el, 'Please enter a valid date in the format: '+this.options.dateFormat.toLowerCase());
							this.showStatus(el, false, 'Please enter a date in the format: '+this.options.dateFormat.toLowerCase());
						}
					}
					
				}else{
				
					valid = false;
					//this.setMsg(el);
					this.showStatus(el, false, 'Please enter a value');
				}
				break;
				
			case 'checkbox':
				if(!el.checked){
					valid = false;
					//this.setMsg(el);
					//this.showStatus(el, false, '');
				}else{
					valid = true;
					//this.showStatus(el, true);
				}
				break;
				
			case 'radio':
				var rad = $A(this.form[el.name]);
				var ok = false;
				rad.each(function(e,i){
					if(e.checked){
						ok = true;
						this.showStatus(el, true);
					}
				});
				if(!ok){
					valid = false;
					//this.setMsg(rad.getLast(), 'Please select an option');
					this.showStatus(rad.getLast(), false, 'Please select an option');
				}else{
					valid = true;
					this.showStatus(el, true);
					this.clearMsg(rad.getLast());
				}
				break;
				
		}
		return valid;
	},
	
	removeSpaces: function(myString){
	    var tstring = "";
	    myString = '' + myString;
	    splitstring = myString.split(" ");
	    for(i = 0; i < splitstring.length; i++)
	        tstring += splitstring[i];
	    return tstring;
    },
	
	setMsg: function(el, msg){
		if(msg == undefined){
			msg = el.title;
		}
		if(this.options.showErrorsInline){
			if(el.error == undefined){
				el.error = new Element('span').addClass(this.options.errorMsgClass).setText(msg).injectAfter(el);
			}else{
				el.error.setText(msg);
			}
			el.addClass(this.options.errorClass);
		}
	},
	
	clearMsg: function(el){
		el.removeClass(this.options.errorClass);
		if(el.error != undefined){
			el.error.remove();
			el.error = undefined;
		}
	},
	
	showStatus: function(el, type, msg){
		var s = el.getNext();

		if(!s){
			s = new Element('div').addClass('status').injectAfter(el);
		}else if(!s.hasClass('status') && !s.getNext()){
			s = new Element('div').addClass('status').injectAfter(el.getNext());
		}else if(!s.hasClass('status') && s.getNext().hasClass('status')){
			s = s.getNext();
		}
		if(msg == undefined){
			msg = el.title;
		}

		if(type){
			//show tick
			s.removeClass('cross');
			s.addClass('tick').setHTML('&nbsp;');
		}else{
			//show cross
			s.removeClass('tick');
			s.addClass('cross').setHTML('&nbsp;'+msg);
		}
	}
	
});

Validate.implement(new Options);
Validate.implement(new Events);


/*************************************************************/

