/**************************************************************

	Script		: Validate
	Version		: 2.1
	Authors		: Muthu K
	Desc		: Form validation
	Licence		: Open Source DCI Licence

**************************************************************/

var Validatea= new Class({
	
	getOptions: function(){
		return {
			ValidateaOnBlur: true,
			errorClass: 'error',
			errorMsgClass: 'errorMessage',
			dateFormat: 'dd/MM/yy',
			onFail: Class.empty,
			onSuccess: false,
			showErrorsInline: true,
			label: 'Please wait...'
			
		};
	},

	initialize: function(form, options){
		this.setOptions(this.getOptions(), options);
		if ($(form))
		{
		this.form = $(form);
		this.elements = this.form.getElements('.required');
		//alert('this.elements');
		this.list = [];

        this.elementstext = this.form.getElements('input[type=text]');
        this.elementstext.each(function(et,i){
			et.addClass('green');
		}.bind(this));

        this.elementspass = this.form.getElements('input[type=password]');
        this.elementspass.each(function(ep,i){
			ep.addClass('green');
		}.bind(this));

        this.elements.each(function(el,i){
			if(this.options.ValidateaOnBlur){
				el.addEvent('blur', this.Validatea.bind(this, el));
			}
		}.bind(this));
		
		this.form.addEvent('submit', function(e){
			var event = new Event(e);
			var doSubmit = true;
			this.elements.each(function(el,i){
			
				if(! this.Validatea(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{
// 				alert("You have missed some required information - please check the * marked areas and complete");
				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(el.title).injectInside(li);
			}
		});
		return list;
	},
	
	Validatea: function(el){
		var valid = true;
		this.clearMsg(el);
		switch(el.type){
			case 'text':
			case 'password':
			case 'textarea':
			case 'select-one':
				if(el.hasClass('fname')){
				var alpahanumeric = el.value;
					for(var j=0; j<el.value.length; j++)
					{
						  var alphaa = alpahanumeric.charAt(j);
						  var hh = alphaa.charCodeAt(0);
						  if((hh > 64 && hh<91) || (hh > 96 && hh<123))
						  {
							valid=true;
						  }else{
							valid = false;
							this.setMsg(el, '* First name should be alphabet');
						  }
					}
				}
				if(el.hasClass('lname')){
				var alpahanumeric = el.value;
					for(var j=0; j<el.value.length; j++)
					{
					  var alphaa = alpahanumeric.charAt(j);
					  var hh = alphaa.charCodeAt(0);
					  if((hh > 64 && hh<91) || (hh > 96 && hh<123))
					  {
						valid=true;
					  }else{
						valid = false;
						this.setMsg(el, '* Last name should be alphabet');
						  }
					}
				}			

				if(el.hasClass('zip'))
				{
				var postcode = el.value;
				if(postcode!='Type ZIPCODE here')
				{
				valid=true;
				}
				else
				{
				valid = false;
				this.setMsg(el, '* Please type your postcode here');
				}
				}
				if(el.value != ''){
					el.hasClass('email');
					var actemail=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;
						}else{
							valid = false;
							this.setMsg(el, '* Please enter your valid email address');
						}
					}
					if(el.hasClass('cemail')){
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(el.value.toUpperCase().match(regEmail))
                        {
							if($('entremail').value != el.value && $('entremail').value != "")
                            {
                                valid = false;
                                this.setMsg(el, '* Your email addresses do not match');
                            }
                            else
                            {
                                valid = true;
                            }
						}
                        else
                        {
							valid = false;
							this.setMsg(el, '* Please confirm your valid email address');
						}
					}
					if(el.hasClass('temail')){
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
                        if(el.value.toUpperCase().match(regEmail))
                        {
                            valid = true;
						}
                        else
                        {
							valid = false;
							this.setMsg(el, '* Please enter their valid email address');
						}
					}
					if(el.hasClass('tcemail')){ 
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(el.value.toUpperCase().match(regEmail))
                        {
							if($('entrtemail').value != el.value && $('entrtemail').value != "")
                            {
                                valid = false;
                                this.setMsg(el, '* Their email addresses do not match');
                            }
                            else
                            {
                                valid = true;
                            }
						}
                        else
                        {
							valid = false;
							this.setMsg(el, '* Please confirm their valid email address');
						}
					}
					if(el.hasClass('number')){
						var regNum = /[-+]?[0-9]*\.?[0-9]+/;
						if(el.value.match(regNum)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, '* Please enter a valid number');
						}
					}
					
					if(el.hasClass('postcode')){
						 var regPC = /[A-Z]{1,2}[0-9]{1,2}/;
						//var regPC = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/
						if(el.value.match(regPC)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, '* Please enter your valid postcode');
						}
					}
					
					if(el.hasClass('date')){
						var d = Date.parseExact(el.value, this.options.dateFormat);
						if(d != null){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, '* Please enter a valid date in the format: '+this.options.dateFormat.toLowerCase());
						}
					}

                    if(el.id == 'entrpassword')
                    {
                        if($('confpassword').value != el.value && $('confpassword').value != "")
                        {
                            valid = false;
                            this.setMsg(el, '* Your passwords do not match');
                            this.setMsg($('confpassword'), '* Your passwords do not match');
                        }
                        else if($('confpassword').value == el.value)
                        {
                            valid = true;
                            this.clearMsg(el);
                            this.clearMsg($('confpassword'));
                        }
                    }

                    if(el.id == 'confpassword')
                    {
                        if($('entrpassword').value == "")
                        {
                            valid = false;
                            this.setMsg($('entrpassword'), '* Please enter your new password');
                        }
                        else if($('entrpassword').value != el.value)
                        {
                            valid = false;
                            this.setMsg(el, '* Your passwords do not match');
                            this.setMsg($('entrpassword'), '* Your passwords do not match');
                        }
                        else if($('entrpassword').value == el.value)
                        {
                            valid = true;
                            this.clearMsg(el);
                            this.clearMsg($('entrpassword'));
                        }
                    }
					
				}
                else
                {
					if(el.id == 'entrpassword')
                    {
                        if($('confpassword').value == "")
                        {
                            valid = true;
                            this.clearMsg(el);
                            this.clearMsg($('confpassword'));
                        }
                        else
                        {
                            valid = false;
                            this.setMsg(el, '* Please enter your new password');
                        }
                    }
                    else if(el.id == 'confpassword')
                    {
                        if($('entrpassword').value == "")
                        {
                            valid = true;
                            this.clearMsg(el);
                            this.clearMsg($('entrpassword'));
                        }
                        else
                        {
                            valid = false;
                            this.setMsg(el, '* Please confirm your new password');
                        }
                    }
                    else
                    {
                        valid = false;
                        this.setMsg(el);
                    }
				}
				break;
				
			case 'checkbox':
				if(!el.checked){
					valid = false;
					this.setMsg(el);
				}else{
					valid = true;
				}
				break;
				
			case 'radio':
				var rad = $A(this.form[el.name]);
				var ok = false;
				rad.each(function(e,i){
					if(e.checked){
						ok = true;
					}
				});
				if(!ok){
					valid = false;
					this.setMsg(rad.getLast(), '* Please select an option');
				}else{
					valid = true;
					this.clearMsg(rad.getLast());
				}
				break;
				
		}
		return valid;
	},
	
	setMsg: function(el, msg){
		if(msg == undefined){
			msg = el.title;
		}
		if(this.options.showErrorsInline)
        {
			if(el.error == undefined)
            {
				if(el.name == 'accept_tos')
                {
                    el.error = new Element('span').addClass(this.options.errorMsgClass).setText(msg).inject($('tos'));
                }else if(el.name == 'about_me')
                {
                    el.error = new Element('span').addClass(this.options.errorMsgClass).setText(msg).inject($('abt'));
                }else
                {
		 try
		  {
                    el.error = new Element('span').addClass(this.options.errorMsgClass).setText(msg).injectAfter(el);
		  }
		  catch(err)
		  {
		   //alert("Error:" + err);
		  }
                }
			}
            else
            {
				el.error.setText(msg);
			}
            el.removeClass('green');
			el.addClass(this.options.errorClass);
		}
	},
	
	clearMsg: function(el){
		el.addClass('green');
        el.removeClass(this.options.errorClass);
		if(el.error != undefined){
			el.error.remove();
			el.error = undefined;
		}
	}
	
});

Validatea.implement(new Options);
Validatea.implement(new Events);
