/**
 * @author jfdesgagne
 */
var Concours = new Class({
  	coopNumber:0,
	fValidator:null,
	
    initialize: function(){
		if($('coop_nombre')) {
			this.initEvents();
			this.config();
		}
    },
	
	config:function() {
		this.fValidator = new fValidator("form_concours", {
			"onValidClass": this,
			"language": lang,
			"onValidFunction": "submitForm"
		});
	},
	
	initEvents:function() {
		$('coop_nombre').addEvent('change', this.coopChangeHandler.bindWithEvent(this));
	},
	
	submitForm:function() {
		$('form_concours').submit();
	},
	
	coopChangeHandler:function(event) {
		if(this.fValidator) {
			this.fValidator.remove();
			this.fValidator = null;
		}
		
		var newNbCoop = event.target.options[event.target.selectedIndex].value;
		//alert("newNbCoop:"+newNbCoop);
		//alert("coopNumber:"+this.coopNumber);
		if(newNbCoop>this.coopNumber) {
			for(this.coopNumber; this.coopNumber<newNbCoop; this.coopNumber++) {
				var coop = $('chef').clone();
					 coop.set('id', 'coop'+(this.coopNumber+1));
					 coop.getElements('input').each(function(ol){
						  this.replaceName(ol);
						}.bind(this))
					 
					 coop.getElements('select').each(function(ol){
						   this.replaceName(ol);								
					 }.bind(this));
					 
					 coop.getElements('label').each(function(ol){
						   this.replaceFor(ol);								
					 }.bind(this));
					
					coop.getElements('legend').each(function(ol){
						  ol.set('html','Coéquipier numéro '+(this.coopNumber+1));
					 }.bind(this));
					
					coop.inject($('coop'), 'bottom');	
			}
		} else if(newNbCoop<this.coopNumber) {
			for(this.coopNumber; this.coopNumber>newNbCoop; this.coopNumber--) {
				if($('coop'+this.coopNumber)) $('coop'+this.coopNumber).destroy();
			}
			if(this.coopNumber<0) this.coopNumber = 0;
		}
		
		this.config();		
	},
	
	replaceName:function(object){
		var name  = object.get('name');
		var nname = name.toString().replace('chef', 'coop'+(this.coopNumber+1));
					
		object.set('name',nname);
		object.set('id',nname);
	},
	
	replaceFor:function(object){
		var name  = object.get('for');
		var nname = name.toString().replace('chef', 'coop'+(this.coopNumber+1));
					
		object.set('for',nname);
	},
	
	removeEvents:function() {
		
	}	
	
});
