// Copyright (c) 2010
//

var Forms = Class.create({
	
	initialize: function( form, options ) {

	    this.options = options || { };
		
		this.seats = this.options.seats || [];
		
		this.form 	= form;
		
		this.cmd 		= this.options.cmd;
		this.subject    = this.options.subject;
		this.errorColor = this.options.errorColor;
		this.submitBt   = this.options.submitBt;
		this.sendingMsg = this.options.sendingMsg;
		this.successMsg = this.options.successMsg;
		this.errorMsg   = this.options.errorMsg;
		
		//var fields = $( form ).getInputs( 'text' );
		//if( fields ) fields.concat( $( form ).getInputs( 'textarea' ) );
		//else 
		this.fields = $( form ).getElements();

		if( this.fields ) {
			
			this.fields.each( function( e ) {
				e.defaultValue = e.value;
				Event.observe( $(e), 'focus', function() {
					if( e.value == e.defaultValue ) e.value = '';
				});
				Event.observe( $(e), 'blur', function() {
					if( e.value == '' ) e.value = e.defaultValue;
				});
			});
		
			var ref = this;
			Event.observe( $( this.submitBt ), 'click', function() {
				if( ref.validate() ) {
					ref.submitForm();
				}
			});
			
		}
		

	},
	
	validate: function() {
		
		var ref   = this;
		var valid = true;
		var color = this.errorColor;
		
		$(ref.form+'-result').update( '' );
		
		if( this.fields ) {
			this.fields.each( function( e ) {
				if( e.readAttribute('mandatory') == '1' ) {
					if( e.value == e.defaultValue || e.value == '' ) {
						valid = false;
						e.highlight( { endcolor:color, restorecolor:color } );
					}
					else if( e.readAttribute('type') == 'email' ) valid = ref.validateEmail(e);
					else e.highlight( {startcolor:'#FFFFFF', endcolor:'#FFFFFF', restorecolor:'#FFFFFF' } );
				}
				else	
					if( e.readAttribute('type') == 'email' && e.value != e.defaultValue && e.value != '' ) valid = ref.validateEmail(e);
			});
		}
		
		return valid;
		
	},
	
	validateEmail: function( e ) {
		
		var color = this.errorColor;
		
		var isEmail = (/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(new String(e.value)));
		if( !isEmail ) e.highlight( { endcolor:color, restorecolor:color } );
		else e.highlight( {startcolor:'#FFFFFF', endcolor:'#FFFFFF', restorecolor:'#FFFFFF' } );
		
		return isEmail;
		
	},
	
	submitForm: function() {
		
		var ref = this;
		$(ref.form+'-result').update( ref.sendingMsg );
		
		new Ajax.Request('php/query.php', {
			parameters: { cmd: ref.cmd,
						  subject: ref.subject,
						  data: $(ref.form).serialize() },
			onSuccess: function( transport, json ) {
				if( json.success == true ) {
					$(ref.form).reset();
					$(ref.form+'-result').update( ref.successMsg );
				}
				else {
					$(ref.form+'-result').update( ref.errorMsg );
				}
			}
		});
	
	}
	
});

/*
*/