// everything happens inside 'domready' event
window.addEvent('domready', function(){
	
	// define a function to run when form is submitted
	$('my_form').addEvent('submit', function(e){
		e.stop();  // stop the default submission of the form
		
		/**
		 * This is where the 'magic' happens. We define a function
		 * to fire when our form submission is complete.
		 * We decode the response which will be in the format of a 
		 * JSON string and then we will call our inject_row function
		 * which will append the results to our table.
		 */
		this.set('send', {
			onComplete: function( response ){
				// decode JSON string to Javascript Array
				var data = JSON.decode(response);
				// call our inject_row function passing a reference to our
				// table body and the data array
				inject_row( $('my_table_body'), data );
			}
		});
		
		// Validate our form. Make sure no fields are blank
		var valid_form = true;
		$$('input').each(function(item){
			if( item.value == '' ) valid_form = false;
		});
		
		// If our form is valid submit to table_form.php
		// Else show an error message.
		if( valid_form ) {
			this.send();
		} else {
			alert('Fill in all fields');
		}
		
	}); // End handling of the 'submit event'
	
	/**
	 * This is a handy little function that handles adding an
	 * array of data to a table.
	 */
	var inject_row = function( table_body, data ){
		// create a table row as a string
		var row_str = '<tr>';
		data.each( function(item, index){
			row_str += '<td>'+item+'</td>';
		});
		row_str += '</tr>';
		// convert string to table wrapped in a div element
		var newRow = htmlToElements( row_str );
		// inject the new row into the table body 
		newRow.inject( table_body );
		
	}
	/**
	 *  wraps tr in a div with full table details.
	 *  this little hack is required for IE support (h8 ie)
	 */
	var htmlToElements = function(str){  
	    return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');  
	}  
	
}); // end handling of 'domready' event