
/*-----------------------------------------------------------------------------

__  __ `__ \  _ \  ___/  __ `/_  __ \  __ \
_  / / / / /  __/ /__ / /_/ /_  / / / /_/ /
/_/ /_/ /_/\___/\___/ \__,_/ /_/ /_/\____/

MSSS Form Management

version:   1.1
author:    Vincent Martin
email:     vincent@mecano.ca

Use:

	--> Scans the entire form to get its elements.
	--> Initializes field status (If required or not AND validity status)
	--> Assign RegExps into an array.
	--> Initializes all default field values.
	--> Assign events on fields (Focus and blur)
		> clears field text on focus field.
		> live validation on blur fields.

------------------------------------------------------------------------------*/


use_form = {
	
	/* FORM INITIALIZATION AND VALIDATION
	=========================================================================== */
	
	
	/* Initialize keyword search field with the dictionnary.
	----------------------------------------------------------- */
	initKeywords: function(){
		var tE = $('keywords');
		if (tE != null) {
			tE.set('value', dict.get('f_keywords'));
			tE.store('defaultValue', tE.get('value'));
			tE.addEvent('focus', function(){
				var tV = this.get('value');
				if(tV == this.retrieve('defaultValue')) this.set('value', '');
			});
			tE.addEvent('blur', function(){
				var tV = this.get('value');
				if(tV == '') this.set('value', this.retrieve('defaultValue'));
			});
		};
	},
	
	
	
	/* Initialize regular expressions
	format: arReg[field name] = Regular expression
	------------------------------------------------ */
	initReg: function(){
		arReg = new Array();
			arReg['f_name']       = /[a-zA-Z0-9_-]{1,}/;
			arReg['f_main_mail']  = /([a-zA-Z0-9_])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})/;
			arReg['f_sec_mail_1'] = /([a-zA-Z0-9_])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})/;
			arReg['f_sec_mail_2'] = /([a-zA-Z0-9_])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})/;
			arReg['f_sec_mail_3'] = /([a-zA-Z0-9_])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})/;
			arReg['f_sec_mail_4'] = /([a-zA-Z0-9_])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})/;
			arReg['f_sec_mail_5'] = /([a-zA-Z0-9_])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})/;
			arReg['f_comment']    = /./;
	},
	
	
	
	/* Initialize fields status
	format: requ_fld[field name] = (Field Required/notRequired, validated = true / not valid = false(not valid by default))
	use: Change requirement status in second level arrays at need.
		--> Required field: required
		--> Not required  : not_required
	------------------------------------------------------------------------------------------------------------------------------ */
	initFieldStatus: function(){
		requ_fld = new Array();
			requ_fld['f_name']       = new Array ('required',false);
			requ_fld['f_main_mail']  = new Array ('required',false);
			requ_fld['f_sec_mail_1'] = new Array ('required',false);
			requ_fld['f_sec_mail_2'] = new Array ('not_required',false);
			requ_fld['f_sec_mail_3'] = new Array ('not_required',false);
			requ_fld['f_sec_mail_4'] = new Array ('not_required',false);
			requ_fld['f_sec_mail_5'] = new Array ('not_required',false);
	},
	
	
	
	/* Initialize field types contained in form
	format: f_type[i] = field type (text, textarea, etc...)
	---------------------------------------------------------- */
	initFieldType: function(){
		f_type = new Array();
			f_type[0] = 'input[type=text]';
			f_type[1] = 'textarea';
	},
	
	
	
	/* initialize main form root function
	------------------------------------------------ */
	initMailForm: function(formName,callnext){
		
		$('error_msg').setStyle('display','none');
		$('sent_msg').setStyle('display','none');
		
		/* Assign field types to variables (can be arrays) */
		var ar_fTxt  = $(formName).getElements(f_type[0]);
		var ar_tArea = $(formName).getElements(f_type[1]);
		
		
		/* Stacks fields initialization by type of field */
		var _aS2 = new ActionStack(this);
		as2 = [];
		
		as2[as2.length] = {func:this.tField_loop, param:[ar_fTxt,_aS2]};
		/*as2[as2.length] = {func:this.tArea_loop, param:[ar_tArea,_aS2],wait:true};*/
		/* May add stacks for radio buttons and select boxes initialization, to implement at need */
		
		_aS2.setStack(as2);
		_aS2.start();
	},
	
	
	
	/* Loops in text fields in order to initialize them with the dictionnary
	-------------------------------------------------------------------------- */
	tField_loop: function(tEl,callnext){
		var self=this;
		if (tEl.length > 0){
			for (i=0; i<tEl.length; i++){
				var tE = tEl[i];
				
				tE.removeEvents('blur');
				tE.removeEvents('focus');
				
				if (requ_fld[tE.name][0] == 'required') nbRequired++;
				
				$(tE.name +'_val').set('class','');
				
				tE.set('value', dict.get(tE.name));
				tE.store('defaultValue', tE.get('value'));
				
				tE.addEvent('focus', function(){
					$('error_msg').setStyle('display','none');
					var tV = this.get('value');
					if(tV == this.retrieve('defaultValue')) this.set('value', '');
					});
				tE.addEvent('blur', function(){
					var tV = this.get('value');
					if(tV == ''){
						/* Checks if field is required when empty, if so... no validation icon is made.
						If required, executes a validation. */
						if (requ_fld[this.name][0] == 'not_required'){
							if (secError > 0) secError--;
							$(this.name +'_val').set('class','');
						} else {
							self.validateForm(this);
						};
						
						/* Shows default value */
						this.set('value', this.retrieve('defaultValue'));
						
						/* Executes a validation if field is NOT empty */
					} else {
						self.validateForm(this);
					};
				});
			};
			callnext.next();
		} else {
			callnext.next();
		};
	},
	
	
	
	/* Loops in text areas in order to initialize them with the dictionnary
	--------------------------------------------------------------------------- */
	tArea_loop: function(tEl,callnext){
		if (tEl.length > 0){
			for (i=0; i<tEl.length; i++){
				
				var tE = tEl[i];
				tE.value = dict.get(tE.name);
			};
			callnext.next();
		} else {
			callnext.next();
		};
	},
	
	
	
	/* Compares string with it's own regExp (returns true or false).
	--------------------------------------------------------------------- */
	checkReg: function(strToValidate){
		stValid = arReg[strToValidate.name].test(strToValidate.value);
		if (stValid) return true
		else return false;
	},
	
	
	
	/* Validates each field or any other form element
	instructions:
		--> Analyzes string with its own regExp.
		--> If field is required, toggles error message on/off, add/substracts an error and update validation array(true or false).
		--> If field is NOT required, only update validation array(true or false).
	------------------------------------------------------------------------------------------------------------------------------------------------ */
	validateForm: function(tE){
		var self=this;
		var tIcon = $(tE.name +'_val');
		if (this.checkReg(tE)){
			/* If the field is valid, shows a valid icon. */
			tIcon.removeClass(tE.name + "_invalid");
			tIcon.addClass(tE.name + "_valid");
			
			/* Check for removing secondary error */
			if (requ_fld[tE.name][0] == 'not_required' && secError > 0) secError--;
			
			/* If the field is valid AND required, shows a valid icon and set the valid status to TRUE. */
			if (requ_fld[tE.name][0] == 'required'){
				if (requ_fld[tE.name][1] == false){
					requ_fld[tE.name][1] = true;
					tIcon.removeClass(tE.name + "_invalid");
					tIcon.addClass(tE.name + "_valid");
					nbValid++;
				}
			}
		} else {
			/* Check for a secondary error */
			if (requ_fld[tE.name][0] == 'not_required'){
				tIcon.removeClass(tE.name + "_valid");
				tIcon.addClass(tE.name + "_invalid");
				secError++;
			};
			
			/* If the field is invalid AND required, shows an invalid icon and set the valid status to FALSE. */
			if (requ_fld[tE.name][0] == 'required'){
				tIcon.removeClass(tE.name + "_valid");
				tIcon.addClass(tE.name + "_invalid");
				if (requ_fld[tE.name][1] == true){
					nbValid--;
					requ_fld[tE.name][1] = false;
				};

			/* If the field is invalid, shows an invalid icon only if required. */
			} else {
				tIcon.removeClass(tE.name + "_valid");
				tIcon.addClass(tE.name + "_invalid");
			};
		};
	},
	
	/* ======================================================================================== */
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/* FORM TOGGLES (Show/Hide) 
	================================================================*/
	
	/* Chooses which box to open
	------------------------------------ */
	lightBox: function(type){
		if (type == 'details'){
			this.show_details_block();
			var track = 'details_etudes';
		}
		if (type == 'form'){
			this.show_choose_form();
			var track = 'share';
		}
		if(pageTracker)	pageTracker._trackPageview('recherche/'+track);	
	},
	
	
	
	/* Shows choose box (Facebook or Email)
	------------------------------------------------ */
	show_choose_form: function(){
		this.close_details_block();
		var tBlock = $('choose_form_shadow');
		tBlock.set('opacity',0);
		tBlock.setStyle('display','block');
		new Fx.Tween(tBlock).start('opacity',0,1);	
	},
	
	
	
	/* Hide choose box (Facebook or Email)
	------------------------------------------------ */
	close_choose_form: function(alreadyOpen, callnext){
		var tBlock = $('choose_form_shadow');
		new Fx.Tween(tBlock).start('opacity',1,0).chain(function(){
			tBlock.setStyle('display','none');
			if (!alreadyOpen) callnext.next();
		});	
	},
	
	
	
	/* Shows main form box
	------------------------------------------------ */
	show_main_form: function(callnext){
		formValid = false;
		nbValid = 0;
		nbRequired = 0;
		secError = 0;
		
		this.initReg();
		this.initFieldStatus();
		this.initFieldType();
		
		var tBlock = $('mainform_shadow');
		tBlock.set('opacity',0);
		tBlock.setStyle('display','block');
		new Fx.Tween(tBlock).start('opacity',0,1).chain(function(){
			callnext.next();
		});
	},
	
	
	
	/* Hide choose box (Facebook or Email)
	------------------------------------------------ */
	close_main_form: function(){
		var tBlock = $('mainform_shadow');
		new Fx.Tween(tBlock).start('opacity',1,0).chain(function(){
			tBlock.setStyle('display','none');
		});
	},
	
	
	
	/* Shows formation details box.
	------------------------------------------------ */
	show_details_block: function(){
		this.close_choose_form(true);
		this.close_main_form();
		
		var tBlock = $('details_block_shadow');
		tBlock.set('opacity',0);
		tBlock.setStyle('display','block');
		new Fx.Tween(tBlock).start('opacity',0,1);	
	},
	
	
	
	/* Hides formation details box.
	------------------------------------------------ */
	close_details_block: function(){
		var tBlock = $('details_block_shadow');
		new Fx.Tween(tBlock).start('opacity',1,0).chain(function(){
			tBlock.setStyle('display','none');
		});	
	},
	
	

	/* Switch between lightboxes.
	------------------------------------------------ */
	switch_form: function(formName){
		var _aS = new ActionStack(this);
		as = [];
		
		as[as.length] = {func:this.close_choose_form, param:[false,_aS], wait:true};
		as[as.length] = {func:this.show_main_form, param:[_aS], wait:true};
		as[as.length] = {func:this.initMailForm, param:[formName,_aS]};
		
		_aS.setStack(as);
		_aS.start();
	},
	
	
	/* =======================================================================================*/
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/* SUBMIT DATA
	================================================================*/
	
	
	/* Submit Validation.
	----------------------------------------------------*/
	onSubmitCareer: function(){
		this.onSubmitValidation();
	},
	

	
	/* Send information if form is valid only
	----------------------------------------------------*/
	onSubmitValidation: function(){
		var tError = $('error_msg');
		if (nbValid == nbRequired && secError == 0){
			this.callData();
		} else {
			tError.setStyle('display','block');
			if ( !$('f_name_val').hasClass('f_name_valid') ) $('f_name_val').addClass('f_name_invalid');
			if ( !$('f_main_mail_val').hasClass('f_main_mail_valid') ) $('f_main_mail_val').addClass('f_main_mail_invalid');
			if ( !$('f_sec_mail_1_val').hasClass('f_sec_mail_1_valid') ) $('f_sec_mail_1_val').addClass('f_sec_mail_1_invalid');
		};
	},
	
	
	
	/* calls data to send (AS).
	----------------------------------------------------*/
	callData: function(){
		var _aS = new ActionStack(this);
		as = [];
		
		as[as.length] = {func:this.SendData, param:[_aS], wait:true};
		as[as.length] = {func:this.showSentMsg, param:[_aS], wait:true};
		as[as.length] = {func:this.close_main_form, param:[]};
		
		_aS.setStack(as);
		_aS.start();
	},
	
	
	
	/* Sends the data.
	----------------------------------------------------*/
	SendData: function(callnext){
		tQ = "";
		tQ += "f_name="+$('f_name').value;
		tQ += "&f_main_mail="+$('f_main_mail').value;
		tQ += "&f_sec_mail_1="+$('f_sec_mail_1').value;
		
		var nbEmail = 1;
		
		/* Get secondary emails (2 to 5)*/
		for (i=2; i<=5; i++){
			if ($('f_sec_mail_'+ i).value != 'Courriel ' + i){
				tQ += "&f_sec_mail_" + i + "="+ $('f_sec_mail_'+ i).value;
				nbEmail++;
			};
		};
		
		/* Get comments if any */
		
		tQ += "&f_comment="+ $('f_comment').value;
	
		var myRequest = new Request({method: 'get', url: '../send_mail.php'});
		myRequest.send(tQ);
		callnext.next();
		
		if(pageTracker)	pageTracker._trackPageview('recherche/share/email/'+nbEmail);	
	},
	
	
	
	/* Shows the "Sent data succesfully" message.
	----------------------------------------------------*/
	showSentMsg: function(callnext){
		var tSent = $('sent_msg');
		tSent.setStyle('display','block');
		(function(){callnext.next();}).delay(2500);
	},
	
	/* ============================================================================ */
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/* ROOT FUNCTIONS
	============================================================================ */
	
	
	/* Use may depend
	--------------------------------------------------------------*/
	empty: function(){
	},
	
	
	
	/* Main function initiation
	--------------------------------------------------------------*/
	init: function(){
		if(this._INIT == null){
			this._INIT = true;
		};
		
		var formValid = false;
		var nbValid = 0;
		var nbRequired = 0;
		var secError = 0;
		
		this.initKeywords();
	},
	
	
	
	/* Startup function
	--------------------------------------------------------------*/
	startup: function(){
	},
	
	
	
	/* Handles window events
	--------------------------------------------------------------*/
	onWindowDomReady: function(){
		this.init();
	},
	
	
	
	onWindowLoad: function(){
		this.init();
	}
};


window.addEvent('domready', function(){
	use_form.onWindowDomReady();
});
window.addEvent('load', function(){
	use_form.onWindowLoad();
});
