/**
 * Loads observers to automatically remove the initial descriptive value of a text field 
 *
 **/
function loadClearValue() 
{
	var elements = $$("input.clearValue");
	
	for(var i = 0 ; i < elements.length ; i++)
	{
		//getAttribute("value") gets the value set in the dom not the value entered in the form
		var value = elements[i].getAttribute("value");
		Event.observe(elements[i] , "focus" , clearValue.curry(elements[i] , value) )
		Event.observe(elements[i] , "blur" , resetValue.curry(elements[i] , value) )
	}	
}

/**
 * if the value is still the initial value, clear it so the user can type
 **/
function clearValue(element , value) 
{
	if($F(element) == value)
	{
		element.setValue("");	
	}
}
/**
 * If the control lost focus and the value did not change, reset it to the initial value
 *
 **/
function resetValue(element , value) 
{
	if($F(element) == "")
	{
		element.setValue(value);	
	}
}


Event.observe(window , 'load' , loadClearValue);


var SpockForm = Class.create({

initialize: function(formId) {
	this.formId = formId;
	this.form = $(formId);
	
	Event.observe(this.form , "submit" , this.submitForm.bindAsEventListener(this))
	var elements = this.form.select("button.submit");
	for(var i = 0 ; i < elements.length ; i++)
		Event.observe(elements[i] , "click" , this.submitForm.bindAsEventListener(this))
	
	loadClearValue();
},

submitForm: function(e) 
{
	Event.stop(e)
	if (this.validate() == true)
	{
		new Ajax.Request(this.form.getAttribute("action"), {
		  method: 'post',
		  parameters: this.form.serialize(),
		  onSuccess: this.submitSuccess.bind(this),
		  onFailure: this.submitFailure.bind(this),
		  onLoading: this.submitLoading.bind(this)
		});	
	}
},
/**
 * Makes sure we get at least one form of contact information
 **/
 
validate: function() 
{
	var elements = this.form.select("input.contact");
	
	contact = (elements.length == 0) ? true : false;
	
	for(var i = 0 ; i < elements.length ; i++)
	{
		//if it's blank or has its initial value...
		//if($F(elements[i]) == "" || $F(elements[i]) == elements[i].getAttribute("value") && contact == false)
			//contact = false;
		//else
			//contact = true;
	}
	contact = true;
	if(contact == false)
		alert("You must provide at least one form of contact information");
	
	return contact;
} ,

submitLoading: function() 
{
	this.form.hide();
	this.form.insert( { 'after' : new Element('div' , {'id' : this.formId + "Loading" , 'class' : 'sending'} ).update("<h2>sending...</h2>") } );	
},


submitSuccess: function(r) 
{
	$(this.formId + "Loading").hide();
	this.form.insert( { after : new Element('div' , {'id' : this.formId + "Success" , 'class' : 'success'} ).update(r.responseText) } );
} ,

submitFailure: function(r)
{
	this.form.insert( { after : new Element('div' , {'id' : this.formId + "Failure" , 'class' : 'success'} ).update(r.responseText) } );
}
});
