window.addEvent('domready', function() {
	
	$$('form.validate').each(function(item){ addValidation(item.get('id'), false) });
	$$('form.validateAjax').each(function(item){ addValidation(item.get('id'), true) });
	
	$$('select.customSelect').each(function(item) {
		item.store('customSelect', new CustomSelect(item.get('id'))); 
	});
	
});


function addValidation(formId, ajaxFlag, ajaxLoading) {

	var wait = 1500;

	$$('#'+formId+' input', '#'+formId+' select','#'+formId+' textarea').each(function(item) {

		var validate = item.get('validate');

		if(!validate) return;

		validate = validate.split(' ');

		var newValidation = new LiveValidation(item, {
			insertAfterWhatNode: $('label_'+item.get('id')),
			wait: wait
		});

		if(validate.indexOf('acceptance') != -1) newValidation.add(Validate.Acceptance, { failureMessage: item.get('error') });
		if(validate.indexOf('confirmation') != -1) newValidation.add(Validate.Confirmation, { match: item.get('match'), failureMessage: item.get('error') });
		if(validate.indexOf('email') != -1) newValidation.add(Validate.Email, { failureMessage: item.get('error') });
		if(validate.indexOf('presence') != -1) newValidation.add(Validate.Presence, { failureMessage: item.get('error') });
	});

	if(ajaxFlag)
	{
		var form = $(formId);
		var validateOnSubmit = form.onsubmit;

		if(!ajaxLoading) {
			var ajaxLoadingTarget = $(form.get('aLTarget')) ? form.get('aLTarget') : formId;
			var ajaxLoading = new AjaxLoading(ajaxLoadingTarget, form.get('aLAlpha'), form.get('aLClass')).setMessage(form.get('aLMessage'));
			form.store('ajaxLoading', ajaxLoading);
		}

		$(formId).onsubmit = function() {
			if(validateOnSubmit())
			{
				ajaxLoading.show();
				
				$(formId).set('send', { onSuccess: function(responseText, responseXML){
					$(formId).set('styles', {'display': 'none'});
					$(formId+'Response_'+responseText).fade('hide');
					$(formId+'Response_'+responseText).set('styles', {'display': 'block'});
					$(formId+'Response_'+responseText).fade('in');
					ajaxLoading.hide();
				}});

				$(formId).send();
			}
			return false;
		}
	}
}

var AjaxLoading = new Class({

	initialize: function(elementId, alpha, class) {

		//saving properties
		this.targetElement = $(elementId);
		this.alpha = alpha ? alpha : 0.8;
		this.class = class ? class : "ajaxLoading";

		//creating elements
		this.container = new Element('div', {
			'class': this.class + '-container',
			'styles': {
				'cursor': 'progress',
				'position': 'absolute',
				'top': 0
			}
		});

		this.image = new Element('img', {
			'class': this.class + '-image',
			'src': 'images/ajax-loader.gif',
			'styles': {
				'cursor': 'inherit'
			}
		});
		
		this.messageSpan = new Element('span', {
			'class': 'ajaxLoading-message'
		});

		this.messageContainer = new Element('div', {
			'styles': {
				'cursor': 'inherit',
				'text-align': 'center'
			}
		});

		this.container.fade('hide');
		
		this.messageSpan.inject(this.messageContainer, 'top');
		this.image.inject(this.messageContainer, 'top');
		this.messageContainer.inject(this.container);
		this.container.inject(document.body);

		this.setTarget(elementId);

		window.addEvent('resize', this.onTargetResize.bindWithEvent(this));
	},
	place: function() {
		this.container.set('styles', {
			'top': this.targetElement.getPosition().y,
			'left': this.targetElement.getPosition().x,
			'width': this.targetElement.getSize().x,
			'height': this.targetElement.getSize().y
		});
		this.messageContainer.set('styles', { 'margin-top': (this.targetElement.getSize().y - this.messageContainer.getSize().y) * .5 });
		return this;
	},
	setTarget: function(elementId) {
		this.targetElement.removeEvent('resize', this.onTargetResize.bindWithEvent(this))
		this.targetElement = $(elementId);
		this.targetElement.addEvent('resize', this.onTargetResize.bindWithEvent(this));
		this.place();
		return this;
	},
	getMessage: function(msg) {
		return this.messageText;
	},
	setMessage: function(msg) {
		this.messageText = msg;
		this.messageSpan.set('text', msg);
		return this;
	},
	onTargetResize: function() {
		if(this.targetElement) this.place();
	},
	fade: function(how) {
		this.place();
		this.container.fade(how);
		return this;
	},
	show: function() {
		this.fade(this.alpha);
		return this;
	},
	hide: function() {
		this.fade(0);
		return this;
	},
	toString: function() {
		return '[ AjaxLoadingObject: Target Element: ' + this.targetElement.get('id') + ', Message Text: ' + this.messageText + ']';
	}
});

var CustomSelect = new Class({

	initialize: function(elementId) {
		
		//saving properties
		this.selectElement = $(elementId);
		this.selectElement.setStyle('display', 'none');

		this.opened = false;
		this.optionsWidth = 0;
		this.optionsList = new Array();
		
		//creo l'handler della select
		this.customSelect = new Element('div', {
			'class': 'customSelect',
			'value': '',
			'styles': {
				'cursor': 'default',
				'float': 'left'
			}
		});
		
		this.customSelect.inject(this.selectElement, 'before');
		
		//creo il contenitore delle options
		this.optionsContainer = new Element('div', {
			'class': 'customSelectOptions',
			'styles': {
				'position': 'absolute',
				'overflow': 'auto'
			}
		});

		//inietto il contenitore delle options
		this.optionsContainer.fade('hide');
		this.optionsContainer.inject(this.selectElement, 'before');
		
		//creo le options della select
		this.selectElement.getChildren().each(this.createOption.bindWithEvent(this));
		
		var customSelectBorderLeft = Number(this.customSelect.getStyle('border-left-width').replace('px',''));
		var customSelectBorderRight = Number(this.customSelect.getStyle('border-right-width').replace('px',''));
		var customSelectPaddingLeft = Number(this.customSelect.getStyle('padding-left').replace('px',''));
		var customSelectPaddingRight = Number(this.customSelect.getStyle('padding-right').replace('px',''));
		
		var optionsContainerWidth = this.optionsList[0].getSize().x + customSelectPaddingRight;
		this.optionsContainer.setStyle('width', optionsContainerWidth);
		this.optionsContainer.setStyle('margin-left', this.customSelect.getPosition().x - this.optionsContainer.getPosition().x);
		
		var customSelectWidth = this.optionsContainer.getSize().x - customSelectPaddingLeft - customSelectPaddingRight - customSelectBorderLeft - customSelectBorderRight;
		this.customSelect.setStyle('width', customSelectWidth);
		
		//eventi
		this.customSelect.addEvent('click', this.toggle.bindWithEvent(this));
		window.addEvent('click', this.checkLostFocus.bindWithEvent(this));
		document.addEvent('blur', this.close.bindWithEvent(this));
	},
	createOption: function(item, index) {

		var newOption = new Element('div', {
			'class': 'customSelectOption',
			'text': item.get('text'),
			'value': item.get('value'),
			'styles': {
				'cursor': 'default'
			}
		});
		
		var icon = new Element('img', {
			'class': 'customSelectOptionIcon',
			'height': 16,
			'width': 16,
			'src': item.get('icon') ? item.get('icon') : 'images/blank.gif',
			'styles': {
				'vertical-align': 'middle'
			}
		}).inject(newOption, 'top');
		
		newOption.addEvent('click', this.onSelectionChange.bindWithEvent(this, index));
		newOption.inject(this.optionsContainer);

		this.optionsList.push(newOption);
	},
	open: function(e) {
		this.opened = true;
		this.optionsContainer.fade('show');
	},
	close: function(e) {
		this.opened = false;
		this.optionsContainer.fade('hide');
	},
	toggle: function(e) {
		if(this.opened) this.close();
		else this.open();
	},
	checkLostFocus: function(e) {
		if(e.target != this.customSelect && e.target != this.optionsContainer) this.close();
	},
	onSelectionChange: function(e, index) {
		this.selectedOption = this.optionsList[index];
		this.customSelect.set('text', this.selectedOption.get('text'));
		this.selectElement.set('value', this.selectedOption.get('value'));
		this.close();
	},
	toString: function() {
		return '[ CustomSelectObject: ]';
	}
});