
/*
evite les erreurs de debug sous IE (console.log ne fonctionne qu'avec firebug)
*/
if(window.console == undefined) {
	console = {
		log: function(s){return true}
	}
}

/**
 * @author giann & Fab
 */

var _maxAllowedMatching = 200;

// SearchController ///////////////////////////////////////////////////////////

/*
Controlleur de la vue "search" se charge de toutes les actions de creation de l'interface,
les actions de bouton, la gestion des recherches
*/
var SearchController = Class.create({
	
	initialize: function() {
		Event.observe(window, 'load', this.onLoad.bind(this));
	},
	
	onLoad: function() {
		this.form = $('foSearch');
		this.initForm();
		document.observe('component:change', this.onChange.bind(this));
		this.matchingCounter = $('matchingCounter');
		this.initUi();
		this.count();
	},
	
	
	/*
		intialise les actions des boutons de l'interface
	*/
	initUi: function() {
		this.form.observe('submit', this.onSubmitForm.bindAsEventListener(this));
	},
	
	
	onChange: function(evt) {
		
		/*var zSelect = evt.target.childNodes[1].childNodes[0];
		var toReset = null;
		
		if ((zSelect.value > 0) && (zSelect != aControlUsed[(aControlUsed.length-1)])) {
			aControlUsed.push(zSelect);
		}
		//aControlUsed.push(zSelect);
		
		if (aControlUsed.length > 2) {
			toReset = aControlUsed[0];
			aControlUsed.shift();
		}
		
		if(toReset != null) {
			if (toReset.name == 'exp_years') {
				toReset.selectedIndex = (toReset.length-1);
			}
			else {
				toReset.selectedIndex = 0;
			}
		}
		
		if((zSelect.value != 0) || (aControlUsed.length != 2)) {
			this.count();
		}*/
		
		var nbControlUsed = 0;
		var controlToReset = null;
		$$('#foSearch select').each(function(select){
			if (select.value > 0) {
				if(nbControlUsed == 0) {
					controlToReset = select;
				}
				nbControlUsed++;
			}
		});
		
		
		if(nbControlUsed > 2) {
			if (controlToReset.name == 'exp_years') {
				controlToReset.selectedIndex = (controlToReset.length-1);
			}
			else {
				controlToReset.selectedIndex = 0;
			}
		}
		
		this.count();
	},
	
	
	onSubmitForm: function(evt) {
		evt.stop();
	},
	
	/*
		initialise les select
		les valeurs sont recuperees dans la variable PHP_initSearch
		cette variable est "ecrite" par le PHP : voir le fichier ou est inclu ce script
	*/
	initCombo: function(combo, moreBox) {
		if (PHP_initSearch[combo.name]) {
			combo.selectValue(PHP_initSearch[combo.name]);
		}
		else {
			combo.selectValue('0');
		}
		
		if(moreBox) {
			if(PHP_initSearch[combo.name]) {
				if(PHP_initSearch[combo.name] > 0) {
					moreBox.open();
				}
			}
		}
	},
	
	
	initText: function (textBox, moreBox) {
		if (PHP_initSearch[textBox.name]) {
			textBox.setData(PHP_initSearch[textBox.name]);
		}
		
		if(moreBox) {
			if(PHP_initSearch[textBox.name]) {
				if(PHP_initSearch[textBox.name].length > 0) {
					moreBox.open();
				}
			}
		}
	},
	
	initCountrySelector: function(cs) {
		if(PHP_initSearch[cs.name + '_region']) {
			cs.selectRegion(PHP_initSearch[cs.name + '_region']);
			cs.selectCountry(PHP_initSearch[cs.name + '_country']);
		} 
	},
	
	initIndustrySelector: function(cs, moreBox) {
		if(PHP_initSearch[cs.name + '_industry']) {
			cs.selectIndustry(PHP_initSearch[cs.name + '_industry']);
			if (PHP_initSearch[cs.name + '_subindustry']) {
				cs.selectSubIndustry(PHP_initSearch[cs.name + '_subindustry']);
				if (PHP_initSearch[cs.name + '_subindustry'] > 0) {
					moreBox.open();
				}
			}
		} 
	},
	
	initGraduationSelector: function(cs, moreBox) {
		if (PHP_initSearch[cs.name + '_gradfrom']) {
			cs.selectFrom(PHP_initSearch[cs.name + '_gradfrom']);
			if (PHP_initSearch[cs.name + '_gradfrom'] != 0) {
				moreBox.open();
			}
		}
		if (PHP_initSearch[cs.name + '_gradto']) {
			cs.selectTo(PHP_initSearch[cs.name + '_gradto']);
			if (PHP_initSearch[cs.name + '_gradto'] != 0) {
				moreBox.open();
			}
		}
	},
	
	initTotYearsSelector: function(cs, moreBox) {
		if (PHP_initSearch[cs.name + '_totyearsfrom']) {
			cs.selectFrom(PHP_initSearch[cs.name + '_totyearsfrom']);
			if (PHP_initSearch[cs.name + '_totyearsfrom'] != 0) {
				moreBox.open();
			}
		}
		if (PHP_initSearch[cs.name + '_totyearsto']) {
			cs.selectTo(PHP_initSearch[cs.name + '_totyearsto']);
			if (PHP_initSearch[cs.name + '_totyearsto'] != 0) {
				moreBox.open();
			}
		}
	},
	
	/*
		reactualise la page
	*/
	reset: function() {
		location.href = Utils.link("CVSearchDemo.php", {reset: 1});
	},
	
	onResetSearch: function() {
		var aUrl = document.location.href.split("?")
		document.location.href = Utils.link(aUrl[0], {search: PHP_searchId});
	},
	
	/*
		compte les resultats d'une recherche
		utilise AJAX : voir le fonctionnement de Utils.remoteCall (plus bas dans ce fichier)
	*/
	count: function() {
		this.matchingCounter.update('<img src="http://www.mba-exchange.com/assets/CVSearch/strobber.gif" />');
		Utils.remoteCall('count', [this.serializer.serialize()], this.onCountResponse.bindAsEventListener(this));
	},
	
	/*
		reponse de count renvoyé par AJAX
	*/
	onCountResponse: function(transp) {
		this.matchingCounter.update(transp.responseJSON.data.Result + " / " + transp.responseJSON.data.LastForum);
	},
	
	/*
		création du formulaire de recherche
	*/
	initForm: function() {
		
		//intialise le serialiseur (voir plus bas)
		this.serializer = new Serializer();
		
		var combo, more;
		
		// EXPERIENCE /////////////////////////////////////////////////////////
		
		//creation du titre (h3) "Experience"
		this.form.insert(new Element('h3').addClassName('gtitle').update('Experience'));
		
		// le select avec le label "Industry"
		/*combo = new ComboBox('Industry', 'exp_industry');
		// les données sont fournies par la variable PHP_industries (var ecrite par php)
		combo.setData(PHP_industries);
		// ajout du champ dans le formulaire
		this.form.insert(combo.element);
		// initialisation de la valeur selectionnée
		this.initCombo(combo);
		// ajout au serialiseur
		this.serializer.add(combo);*/
		
		combo = new ComboBox('Industry', 'exp_industry');
		combo.setData(PHP_industries);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		// meme principe pour les autres champs ...
		
		combo = new ComboBox('Function', 'exp_functional');
		combo.setData(PHP_functions);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		combo = new CountrySelector('exp', PHP_regions, PHP_countries);
		this.form.insert(combo.element);
		this.initCountrySelector(combo);
		this.serializer.add(combo);
		
		combo = new ComboBox('Experience', 'exp_years');
		combo.setData(PHP_expYears);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		/*combo = new TotYearsSelector('exp', PHP_totExpYears);
		more.content.insert(combo.element);
		this.initTotYearsSelector(combo);
		this.serializer.add(combo);*/
		
		
		// PREFERENCE /////////////////////////////////////////////////////////
		this.form.insert(new Element('h3').addClassName('gtitle').update('Preferences'));
		
		combo = new ComboBox('Industry', 'pref_industry');
		combo.setData(PHP_industries);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		
		combo = new ComboBox('Function', 'pref_functional');
		combo.setData(PHP_functions);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		combo = new CountrySelector('pref', PHP_regions, PHP_countries);
		this.form.insert(combo.element);
		this.initCountrySelector(combo);
		this.serializer.add(combo);

		
		// PERSONAL ///////////////////////////////////////////////////////////
		this.form.insert(new Element('h3').addClassName('gtitle').update('Personal'));
		
		combo = new ComboBox('Language', 'language');
		combo.setData(PHP_languages, PHP_TopLanguages);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		combo = new ComboBox('Level', 'languagelevel');
		combo.setData(PHP_languageslevels);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		combo = new ComboBox('Nationality', 'nationality');
		combo.setData(PHP_nationalities);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		/*textBox = new TextBox('Business School', 'bschool');
		this.form.insert(textBox.element);
		this.initText(textBox);
		this.serializer.add(textBox);*/
		
		
		/*textBox = new TextBox('Last Name', 'lastname');
		this.form.insert(textBox.element);
		this.initText(textBox);
		this.serializer.add(textBox);*/
		
		combo = new ComboBox('Diploma type', 'diploma');
		combo.setData(PHP_diploma);
		this.form.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		/*var item = new CheckboxOnOff('Work permit: European Union', 'wp_eu');
		this.form.insert(item.element);
		this.serializer.add(item);
		if(PHP_initSearch.wp_eu == 1) {
			item.checkbox.checked = true;
		}
		
		var cbOtherCountry = new CheckboxOnOff('Work permit: Other Country', 'wp_other_countries');
		this.form.insert(cbOtherCountry.element);
		this.serializer.add(cbOtherCountry);
		if(PHP_initSearch.wp_other_countries == 1) {
			cbOtherCountry.checkbox.checked = true;
		}
		
		var hiddenBox = new Element('div');
		this.form.insert(hiddenBox);
		
		combo = new ComboBox('Country', 'wp_other_countries_list');
		combo.setData(PHP_countryList);
		hiddenBox.insert(combo.element);
		this.initCombo(combo);
		this.serializer.add(combo);
		
		if(!cbOtherCountry.checkbox.checked) {
			hiddenBox.hide();
		}
		
		cbOtherCountry.registerActivate(function() {
			hiddenBox.show();
		});
		
		cbOtherCountry.registerDesactivate(function() {
			hiddenBox.hide();
		});*/
	}
	
});


// UtilsClasses ///////////////////////////////////////////////////////////////
/*
classe statique utilitaire; elle contient 2 methodes:
link: sert a creer des liens le parametre "qp" est un objet contenant les variables d'url
remoteCall: sert a appeler une procedure distante (AJAX)
*/
var Utils = {
	
	link: function(url, qp) {
		qp = qp || {};
		qp.session = PHP_session;
		return url + '?' + $H(qp).toQueryString();
	},
	
	remoteCall: function(method, params, callback) {
		var sType = 'MBAX';
		var plaCode = 'MBAX';
		var cID = 0;
		if(typeof(searchType) != 'undefined') {
			sType = searchType;
		}
		if(typeof(PLA_CODE) != 'undefined') {
			plaCode = PLA_CODE;
		}
		if(typeof(C_ID) != 'undefined') {
			cID = C_ID;
		}
		new Ajax.Request(Utils.link("../Ajax/CVSearch.php"), {
			parameters: {request: $H({
				method: method,
				params: params
			}).toJSON(), searchType: sType, plaCode: plaCode, cID: cID},
			onSuccess: callback
		});
	}
}

/*
les classes ComboBox, ComboBoxCloner, CountrySelector et CheckboxOnOff
sont des composants d'interface
ce qui est important de retenir, c'est que chaque composant, s'il veut etre serialisé
doit implementer les methodes getValue() et getName()
puisque le serialiseur va prendre le nom du composant (getName()) et l'associer avec la valeur (getValue())
sous cette forme: {name: value}
Pour ces memes classes, la methode setData sert a remplir/intialiser le composant
*/

var ComboBox = Class.create({
	
	initialize: function(label, name) {
		this.label = label;
		this.name = name;
		this.init();
	},
	
	init: function() {
		this.draw();
	},
	
	draw: function() {
		this.element = new Element('div').addClassName('comboBox');
		var label = new Element('label');
		this.text = new Element('span').addClassName('text').update(this.label);
		this.select = new Element('select').writeAttribute({name: this.name})
			.observe('change', this.onChange.bind(this));
		label.insert(this.select);
		this.element.insert(this.text);
		this.element.insert(label);
	},
	
	onChange: function() {
		this.element.fire('component:change');
	},
	
	setData: function(data, topData) {
		this.data = data;
		if (topData) {
			this.topData = topData;
		}
		this.select.options.length = 0;
		if(topData) {
			$H(topData).each(function(pair, i) {
				this.select.options[this.select.options.length] = new Option(pair.value, pair.key);
			}, this);
		}
		$H(data).each(function(pair, i) {
			this.select.options[this.select.options.length] = new Option(pair.value, pair.key);
		}, this);
	},
	
	addRadioBox: function(radioBox) {
		this.radioBox = radioBox;
		//this.element.insert({top: radioBox.element});
		this.text.insert(radioBox.element);
	},
	
	selectValue: function(v, parentName, i) {
		var value = v;
		var radioValue = 'Or';
		
		if (v.indexOf('/') > 0) {
			var aValues = v.split(new RegExp("[/]+", "g"));
			radioValue = aValues[0];
			value = aValues[1];
		}
		else {
			if (parentName) {
				if (PHP_initSearch[parentName + '_AndOr_' + i]) {
					radioValue = PHP_initSearch[parentName + '_AndOr_' + i];
				}
			}
		}
		
		$A(this.select.options).each(function(opt) {
			if (opt.value == value) {
				opt.selected = true;
			}
		});
		
		if (this.radioBox != null) {
			this.radioBox.selectValue(radioValue);
		}
	},
	
	getValue: function() {
		if(this.radioBox != null) {
			return (this.radioBox.getValue() + '/' + $F(this.select)) || 0;
		}
		else {
			return $F(this.select) || 0;
		}
	},
	
	getName: function() {
		return this.name;
	}
});


/*
 * Class qui cree un groupe de radio buttons
 */
var RadioBox = Class.create({
	initialize: function(name) {
		this.name = name;
		this.radioButtons = [];
		this.init();
	},
	
	init: function() {
		this.draw();
	},
	
	draw: function() {
		this.element = new Element('span').addClassName('radioBox');
	},
	
	onChange: function() {
		this.element.fire('component:change');
	},
	
	setData: function(data, defaultIndice) {
		this.data = data;
		$H(data).each(function(pair, i) {
			var label = new Element('label');
			var text = new Element('span').addClassName('radioText').update(pair.value);
			
			/*Fucking IE, new Element DO NOT work for radio buttons*/
			var radioButton = '<input type="radio" id="' + this.name + '_' + pair.key + '" name="' + this.name + '" value="' + pair.key + '" class="radioButton" onclick="this.fire(\'component:change\')" ';
			if(defaultIndice == i) {
				radioButton += 'checked="checked" ';
			}
			radioButton += '/>';
			this.radioButtons.push(this.name + '_' + pair.key);
			label.update(radioButton).insert(text);
			this.element.insert(label);
		}, this);
	},
	
	onRadioButtonClick: function() {
		this.element.fire('component:change');
	},
	
	selectValue: function(v)
	{
		$A(this.radioButtons).each(function(zRadio) {
			$(zRadio).checked = false;
			if ($(zRadio).value == v) {
				$(zRadio).checked = true;
			}
		});
	},
	
	getValue: function() {
		var val = 'Or';
		$A(this.radioButtons).each(function(zRadio) {
			if($(zRadio).checked == true) {
				val = $(zRadio).value;
			}
		});
		return val;
	},
	
	getName: function() {
		return this.name;
	}
});



/*
 * Class qui cree un input text
 */
var TextBox = Class.create({
	initialize: function(label, name) {
		this.label = label;
		this.name = name;
		this.init();
	},
	
	init: function() {
		var date = new Date();
		this.lastTimeRefresh = date.getTime();
		this.lastTimeLength = 0;
		this.timer = null;
		this.draw();
	},
	
	draw: function() {
		this.element = new Element('div').addClassName('textBox');
		var label = new Element('label');
		this.text = new Element('span').addClassName('text').update(this.label);
		this.inputText = new Element('input').writeAttribute({type: 'text', name: this.name})
			.observe('keydown', this.onKeyDown.bindAsEventListener(this));
		label.insert(this.inputText);
		this.element.insert(this.text);
		this.element.insert(label);
	},
	
	onKeyDown: function(evt) {
		var kCode = evt.keyCode || e.which;
		if(kCode == 13) {
			//Bloque la touche "Enter" pour ne pas submiter le formulaire
			evt.stop();
		}
		
		if (this.timer != null) {
			window.clearTimeout(this.timer);
		}
		this.timer = window.setTimeout(this.onChange.bindAsEventListener(this), 1500);
	},
	
	onChange: function() {
		this.element.fire('component:change');
	},
	
	setData: function(data) {
		this.inputText.value = data;
		this.lastTimeLength = data.length;
	},
	
	getValue: function() {
		return $F(this.inputText) || 0;
	},
	
	getName: function() {
		return this.name;
	}
});


/*
classe qui crée les select duplicable
les boutons + et - sont créés automatiquement
*/
var ComboBoxCloner = Class.create({
	
	initialize: function(label, name) {
		this.cloneBox = null;
		this.element = new Element('div');
		this.label = label;
		this.name = name;
		this.clones = [];
		this.init();
	},
	
	init: function() {
		var comboBox = new ComboBox(this.label, this.name + '[]');
		this.addButton(comboBox.element);
		this.insert(comboBox);
		this.reference = this.clones[0];
	},
	
	clone: function() {
		//be care, insert() must be done after addButton()
		var comboBox = new ComboBox('', this.name + '[]');
		
		var radioAndOr = new RadioBox(this.name + '_AndOr_' + (this.clones.length).toString());
		radioAndOr.setData({'And':'And', 'AndNot':'And Not', 'Or':'Or'}, 1);
		
		if (this.clones.length < 2) {
			this.addButton(comboBox.element, true);
		}
		comboBox.addRadioBox(radioAndOr);
		this.insert(comboBox);
		
		if (this.reference.topData) {
			comboBox.setData(this.reference.data, this.reference.topData);
		}
		else {
			comboBox.setData(this.reference.data);
		}
		comboBox.selectValue('0');
		comboBox.element.down('span.text').addClassName('relation');
		
		return comboBox;
	},
	
	insert: function(comboBox) {
		this.clones.push(comboBox);
		this.element.insert(comboBox.element);
	},
	
	addButton: function(element, remover) {
		var className, callback;
		if(!remover) {
			className = 'btAddClone';
			callback = this.onBtAddClick.bindAsEventListener(this);
		} else {
			className = 'btRemoveClone'; 
			callback = this.onBtRemoveClick.bindAsEventListener(this, this.clones.length);
		}
		
		var bt = new Element('a')
			.writeAttribute('href', '#')
			.addClassName(className)
			.observe('click', callback);	
			
		var buttons = new Element('span')
			.addClassName('buttons')
			.insert(bt);
		
		element.insert({top: buttons});
	},
	
	
	onBtAddClick: function(evt) {
		evt.stop();
		if(evt.findElement('a.btAddClone')) {
			this.clone();
		}
	},
	
	onBtRemoveClick: function(evt, index) {
		evt.stop();
		//this.clones[index].element.remove();
		this.clones[(this.clones.length - 1)].element.remove();
		//delete this.clones[index];
		this.clones.pop();
		this.element.fire('component:change');
	},
	
	selectValue: function(value) {
		if(!value.length) value = [value];
		var combos = this.clones.flatten();
		$A(value).each(function(v, i) {
			(combos[i] ? combos[i] : this.clone()).selectValue(v, this.name, i);
		}, this);
	},
	
	reset: function() {
		$A(this.clones).each(function(clone, i) {
			if(i > 0) {
				if(clone.element) {
					$(clone.element).remove();
					delete clone;
				}
			}
		});
		this.clones = [this.clones[0]];
		this.element.fire('component:change');
	},
	
	getValue: function() {
		return $A(this.clones).collect(function(clone){
			if (clone != null) {
				return clone.getValue();
			}
		}).uniq();
	},
	
	getName: function() {
		return this.name;
	}
	
});


/*
cette classe crée les industry-selector:

une select pour l'industry,
une autre pour les sous industries
*/
var IndustrySelector = Class.create({
	
	initialize: function(name, industries, subindustries) {
		this.name = name;
		this.data = {
			industries: industries,
			subindustries: subindustries
		}
		this.element = new Element('div');
		this.subelement = new Element('div');
		this.selectedIndustry = 0;
		this.isMultiple = true;
		this.init();
	},
	
	init: function() {
		this.comboIndustry = new ComboBox('Industry', this.name + '_industry');
		var data = new Hash();
		$A(this.data.industries).each(function(idy) {
			data.set(idy.id, idy.name);
		});
		this.comboIndustry.setData(data);
		this.comboIndustry.select.observe('change', this.onChangeIndustry.bind(this));
		this.element.insert(this.comboIndustry.element);
		
		this.comboSubIndustries = new ComboBox('Sub industry', this.name + '_subindustry');
		this.subelement.insert(this.comboSubIndustries.element);
		
		this.updateIndustries();
	},
	
	updateIndustries: function() {
		var data = new Hash();
		data.set(0, '---');
		if(this.selectedIndustry == 0) {
			$A(this.data.subindustries).each(function(sdy) {
				data.set(sdy.id, sdy.name);
			});
		} else {
			$A(this.data.subindustries).each(function(sdy) {
				if (sdy.industry == this.selectedIndustry) {
					data.set(sdy.id, sdy.name);
				}
			}, this);
		}
		this.comboSubIndustries.setData(data);
		this.element.fire('component:change');
	},
	
	onChangeIndustry: function() {
		this.selectedIndustry = $(this.comboIndustry.select).getValue();
		this.updateIndustries();
	},
	
	selectIndustry: function(industry) {
		this.comboIndustry.selectValue(industry);
		this.onChangeIndustry();
	},
	
	selectSubIndustry: function(subindustry) {
		this.comboSubIndustries.selectValue(subindustry);
	},
	
	getValue: function() {
		return {
			industry: this.comboIndustry.getValue(),
			subindustry: this.comboSubIndustries.getValue()
		};
	},
	
	getName: function() {
		return this.name;
	}
});


/*
cette classe crée les country-selector:

une select pour le continent,
une autre pour les pays
*/
var CountrySelector = Class.create({
	
	initialize: function(name, regions, countries) {
		this.name = name;
		this.data = {
			regions: regions,
			countries: countries
		}
		this.element = new Element('div');
		this.selectedRegion = 0;
		this.isMultiple = true;
		this.init();
	},
	
	init: function() {
		this.comboRegion = new ComboBox('Region', this.name + '_region');
		var data = new Hash();
		$A(this.data.regions).each(function(reg) {
			data.set(reg.id, reg.name);
		});
		this.comboRegion.setData(data);
		this.comboRegion.select.observe('change', this.onChangeRegion.bind(this));
		this.element.insert(this.comboRegion.element);
		
		this.comboClonerCountry = new ComboBox('Country', this.name + '_country');
		this.element.insert(this.comboClonerCountry.element)
		
		this.updateCountries();
	},
	
	updateCountries: function() {
		var data = new Hash();
		data.set(0, '---');
		if(this.selectedRegion == 0) {
			$A(this.data.countries).each(function(cty) {
				data.set(cty.id, cty.name);
			});
		} else {
			$A(this.data.countries).each(function(cty) {
				if (cty.region == this.selectedRegion) {
					data.set(cty.id, cty.name);
				}
			}, this);
		}
		this.comboClonerCountry.setData(data)
		this.element.fire('component:change');
	},
	
	onChangeRegion: function() {
		this.selectedRegion = $(this.comboRegion.select).getValue();
		//this.comboClonerCountry.reset();
		this.updateCountries();
	},
	
	selectRegion: function(region) {
		this.comboRegion.selectValue(region);
		this.onChangeRegion();
	},
	
	selectCountry: function(country) {
		this.comboClonerCountry.selectValue(country);
	},
	
	getValue: function() {
		return {
			region: this.comboRegion.getValue(),
			country: this.comboClonerCountry.getValue()
		};
	},
	
	getName: function() {
		return this.name;
	}
});


/*
cette classe crée les graduation-selector:

une select pour le from,
une autre pour le to
*/
var GraduationSelector = Class.create({
	
	initialize: function(name, years) {
		this.name = name;
		this.data = {
			years: years
		}
		this.element = new Element('div');
		this.element.addClassName('GradDateSelector');
		
		this.text = new Element('span').addClassName('text').update('Graduation date');
		this.element.insert(this.text);
		
		this.selectedYearFrom = 0;
		this.selectedYearTo = 0;
		this.isMultiple = true;
		this.init();
	},
	
	init: function() {
		this.comboFrom = new ComboBox('From&nbsp;', this.name + '_gradfrom');
		this.comboFrom.setData(this.data.years);
		this.element.insert(this.comboFrom.element);
		
		this.comboTo = new ComboBox('To&nbsp;', this.name + '_gradto');
		this.comboTo.setData(this.data.years);
		this.element.insert(this.comboTo.element);
	},
	
	selectFrom: function(from) {
		this.comboFrom.selectValue(from);
	},
	
	selectTo: function(to) {
		this.comboTo.selectValue(to);
	},
	
	getValue: function() {
		return {
			gradfrom: this.comboFrom.getValue(),
			gradto: this.comboTo.getValue()
		};
	},
	
	getName: function() {
		return this.name;
	}
});


var TotYearsSelector = Class.create({
	
	initialize: function(name, years) {
		this.name = name;
		this.data = {
			years: years
		}
		this.element = new Element('div');
		this.element.addClassName('GradDateSelector');
		
		this.text = new Element('span').addClassName('text').update('Total years of experience');
		this.element.insert(this.text);
		
		this.selectedYearFrom = 0;
		this.selectedYearTo = 0;
		this.isMultiple = true;
		this.init();
	},
	
	init: function() {
		this.comboFrom = new ComboBox('From&nbsp;', this.name + '_totyearsfrom');
		this.comboFrom.setData(this.data.years);
		this.element.insert(this.comboFrom.element);
		
		this.comboTo = new ComboBox('To&nbsp;', this.name + '_totyearsto');
		this.comboTo.setData(this.data.years);
		this.element.insert(this.comboTo.element);
	},
	
	selectFrom: function(from) {
		this.comboFrom.selectValue(from);
	},
	
	selectTo: function(to) {
		this.comboTo.selectValue(to);
	},
	
	getValue: function() {
		return {
			totyearsfrom: this.comboFrom.getValue(),
			totyearsto: this.comboTo.getValue()
		};
	},
	
	getName: function() {
		return this.name;
	}
});


/*
classe qui créer la boite "more ..."
*/
var MoreBox = Class.create({
	
	initialize: function() {
		this.element = new Element('div').addClassName('moreBox');
		this.title = new Element('a')
			.writeAttribute({href: '#'})
			.addClassName('title')
			.update('Show more search criteria ...');
		this.content = new Element('div').addClassName('content');
		this.element.insert(this.title).insert(this.content);
		
		this.content.hide();
		this.title.observe('click', this.onTitleClick.bindAsEventListener(this));
	},
	
	onTitleClick: function(evt) {
		evt.stop();
		if(this.content.visible()) {
			this.close();
		} else {
			this.open();
		}
	},
	
	open: function() {
		this.content.show();
		this.title.addClassName('selected');
	},
	
	close: function() {
		this.content.hide();
		this.title.removeClassName('selected');
	}
});

/*
classe qui permet de creer une checkbox a 2 etats
*/
var CheckboxOnOff = Class.create({
	
	initialize: function(label, name) {
		this.label = label;
		this.name = name;
		this.element = new Element('div').addClassName('marginLeft50');
		label = new Element('label').addClassName('checkbox');
		this.zero = new Element('input')
			.writeAttribute({type: 'hidden', name: this.name, value: 0});
		this.checkbox = new Element('input').writeAttribute({
			type: 'checkbox', 
			name: this.name, 
			value: 1, 
			className: 'checkbox'
		});
		this.text = new Element('span').addClassName('text').update(this.label);
		
		this.element.insert(this.zero);
		this.element.insert(label);
		label.insert(this.checkbox);
		label.insert(this.text);
		
		this.checkbox.observe('click', this.onCheckboxClick.bind(this));
	},
	
	onCheckboxClick: function() {
		this.element.fire('component:change');
	
		if(this.checkbox.checked) {
			if(this.activateCallback) this.activateCallback();
		} else {
			if(this.desactivateCallback) this.desactivateCallback();
		}
	},
	
	registerActivate: function(func) {
		this.activateCallback = func;
	},
	
	registerDesactivate: function(func) {
		this.desactivateCallback = func;
	},
	
	getValue: function() {
		return Number(this.checkbox.checked);
	},
	
	getName: function() {
		return this.name;
	}
	
});


/*
classe de serialisation de formulaire
la methode add sert a ajouter un champ
ceci sert a recuperer les valeurs du formulaire
sous forme d'un objet 
*/
var Serializer = Class.create({
	
	initialize: function() {
		this.items = [];
	},
	
	add: function(item) {
		this.items.push(item);
	},
	
	serialize: function() {
		var o = {}, k, v;
		$A(this.items).each(function(item) {
				k = item.getName();
				v = item.getValue();
				//console.log(k + ': ' + v);
				if (item.isMultiple) {
					$H(v).each(function(pair){
						o[k + '_' + pair.key] = pair.value;
					//console.log(pair.key + ': ' + pair.value);
					})
				}
				else {
					o[k] = v;
				}
			}
		, this);
		return o
	},
	
	saveReference: function() {
		this.reference = this.serialize();
	},
	
	compare: function() {
		var idem = true;
		var o = {}, k, v;
		$A(this.items).each(function(item){
			k = item.getName();
			v = item.getValue();
			if (item.isMultiple) {
				$H(v).each(function(pair){
					if(isNaN(pair.value)) {
						if(typeof(this.reference[k + '_' + pair.key]) == "string") {
							if(this.reference[k + '_' + pair.key] != pair.value) {
								idem = false;
							}
						}
						else {
							if(!this.reference[k + '_' + pair.key].compare($A(pair.value))) {
								idem = false;
							}
						}
					}
					else {
						if(parseInt(this.reference[k + '_' + pair.key]) != parseInt(pair.value)) {
							idem = false;
						}
					}
				}, this)
			}
			else {
				if (isNaN(v)) {
					if(typeof(v) == 'string') {
						if(this.reference[k] != v) {
							idem = false;
						}
					}
					else {
						if (!this.reference[k].compare($A(v))) {
							idem = false;
						}
					}
				}
				else {
					if (parseInt(this.reference[k]) != parseInt(v)) {
						idem = false;
					}
				}
			}
		}
		, this);
		return idem;
	}
});


Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { 
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}

