window.addEvent('domready', function() {
		
	new MorphList($('silgrafeMenu').getElement('ul'));
	
	var myFormValidation = new Validate('myForm',{
					errorClass: 'red'
				});
	
});

var MorphList = new Class({   
	
	Implements: [Events, Options],
	
	options: {/*             
		onClick: $empty,
		onMorph: $empty,*/
		morph: { 'link': 'cancel' }
	},
	
	initialize: function(menu, options) {
		var that = this;
		this.setOptions(options);
		this.menu = $(menu);
		this.menuitems = this.menu.getChildren();
		this.menuitems.addEvents({
			mouseenter: function(){ that.morphTo(this); },
			mouseleave: function(){ that.morphTo(that.current); },
			click: function(ev){ that.click(ev, this); }
		});       
		this.bg = new Element('li', {'class': 'background'}).adopt(new Element('div', {'class': 'left'}));
		this.bg.inject(this.menu).set('morph', this.options.morph);
		this.setCurrent(this.menu.getElement('.current'));
	},          

	click: function(ev, item) {
		this.setCurrent(item, true);
		this.fireEvent('onClick', [ev, item]);
	},
	
	setCurrent: function(el, effect){  
		if(el && ! this.current) {
			this.bg.set('styles', { left: el.offsetLeft, width: el.offsetWidth, height: el.offsetHeight, top: el.offsetTop });
			(effect) ? this.bg.fade('hide').fade('in') : this.bg.fade('show');
		}
		if(this.current) this.current.removeClass('current');
		if(el) this.current = el.addClass('current');    
	},         
         
	morphTo: function(to) {
		if(! this.current) return; 
		this.bg.morph({
			left: to.offsetLeft, top: to.offsetTop,
			width: to.offsetWidth, height: to.offsetHeight
		});
		this.fireEvent('onMorph', to);
	}

});

var Validate = new Class({
	
	getOptions: function(){
		return {
			validateOnBlur: true,
			errorClass: 'error',
			errorMsgClass: 'errorMessage',
			dateFormat: 'dd/MM/yy',
			showErrorsInline: true,
			label: 'Aguarde um momento...'
		};
	},

	initialize: function(form, options){
		this.setOptions(this.getOptions(), options);
		this.options.onFail = options.onFail || $empty;
		this.options.onSuccess = options.onSuccess || false;
		this.form = $(form);
		this.elements = this.form.getElements('.required');
		
		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;
			this.elements.each(function(el,i){
				if(! this.validate(el)){
					event.stop();
					doSubmit = false
					this.list.include(el);
				}else{
					this.list.erase(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).appendText(el.title).injectInside(li);
			}
		});
		return list;
	},
	
	validate: function(el){
		var valid = true;
		this.clearMsg(el);
		
		switch(el.type){
			case 'text':
			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;
						}else{
							valid = false;
							this.setMsg(el, 'Introduza um email válido');
						}
					}
					
					if(el.hasClass('number')){
						//var regNum = /[-+]?[0-9]*\.?[0-9]+/;
						var regNum = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
						if(el.value.match(regNum)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Introduza um nº válido');
						}
					}
					
				}else{
					valid = false;
					this.setMsg(el);
				}
				break;
				
		}
		return valid;
	},
	
	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).appendText(msg).injectAfter(el);
			}else{
				el.error.appendText(msg);
			}
			el.addClass(this.options.errorClass);
		}
	},
	
	clearMsg: function(el){
		el.removeClass(this.options.errorClass);
		if(el.error != undefined){
			el.error.destroy();
			el.error = undefined;
		}
	}
	
});

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





function open_mode( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results != null)
	{
		if(results[1] == '1')
			alert('A mensagem foi enviada com sucesso!');
		else
			alert('Foi detectado um erro durante o envio do email.\nP.F. entre em contacto através geral@silgrafe.com.');
	}
}