// (c) 2008 mediaunit.de
/**
 * Functionality and styling of the order form..
 *
 * @author tc
 * @since 2008-06-02
 */
/*
 * Simulate namespaces.
 */
if (typeof es == "undefined") 
    es = new Object();
if (typeof es.fhecor == "undefined") 
    es.fhecor = new Object();

es.fhecor.Form = Class.create({
	
	form: null,
	observer: null,

    initialize: function(formElement) {
		this.form = formElement;
		this.toggleSubmitButton();
		this.form.select('input[type="text"].count').invoke('disable');
		this.form.observe("click", this.reactOnChanges.bindAsEventListener(this));
	},
	
	toggleSubmitButton: function() {
		var submitInput = this.form.down('input[type=submit]');
		if (submitInput) {
			var submitLink = new Element("h3", {'class': 'resource'}).update(new Element('a', {href: "#"}).update(submitInput.readAttribute('value')));
			submitInput.replace(submitLink);
			submitLink.observe("click", this.submit.bindAsEventListener(this));
		}
	},
	
	submit: function(event) {
		var doSubmit = true;
		if (typeof this.form.onsubmit == "function") 
			doSubmit = this.form.onsubmit();
		this.form.fire("form:submit");
		if (doSubmit)
			this.form.submit();
		else
			event.stop();
	},
	
	reactOnChanges: function(event) {
		
		var target = event.element();
		
		if (target.readAttribute('type') == 'checkbox') {
			var checked = !(target.getValue() == null);
			var counts = target.up('tr').select('input[type="text"]');
			if (!checked) {
				counts.invoke('clear').invoke('disable');
			} else if (counts.any()) {
				counts[0].setValue('1');
				counts.invoke('enable');
			}
		}
	}
});

Object.extend(es.fhecor.Form, {
	
	update: function() {
		var order = $('requestProposal');
		if (order)
			new es.fhecor.Form(order);
	}
});

/*
 * Apply when document is ready.
 */
Event.observe(document, 'dom:loaded', function(){
	es.fhecor.Form.update();
});
