function trim( str ){
	if( !str ) return '';
	str = str.replace( /^\s/g, '' );
	str = str.replace( /\s$/g, '' );
	return str;
}

// Active/Desactive le champ email
function activeEmail(frm)
{
	if ( frm.newsletter.checked==true ){
		frm.email.nextSibling.className = 'show';
		frm.email.disabled=false;
	} else {
		frm.email.nextSibling.className = 'hide';
		frm.email.disabled=true;
	}
}

// Fonction pour valider ou non un email
function checkEmail(str){
	var filter=/^[a-z0-9\.\-\_]+@[a-z0-9\.\-\_]+$/i;
	if (filter.test(str))
		return true;
	else
		return false;
}

// S'assure que les champs obligatoires ont bien été remplis
function submitContactForm(frm){
	var error = new Array(false,false)
	frm.valid = true;
	if( !trim(frm.society.value) ){
		frm.society.parentNode.className = 'missing';
		error[0] = true;
	}
	if( !trim(frm.name.value) ){
		frm.name.parentNode.className = 'missing';
		error[0] = true;
	}
	if( !trim(frm.phone.value) ){
		frm.phone.parentNode.className = 'missing';
		error[0] = true;
	}
	if ( frm.newsletter.checked==true ){
		if( !trim(frm.email.value) ){
			frm.email.parentNode.className = 'missing';
			error[0] = true;
		}
		else{
			if( !checkEmail(frm.email.value) ) {
				frm.email.parentNode.className = 'missing';
				error[1] = true;
			}
		}
	}
	var err = document.getElementById('errors');
	if( err ){
		if( error[0]==false && error[1]==false )
			err.style.display = 'none';
		else
		{
			err.innerHTML = ''
			if( error[0]==true )
			{
				err.innerHTML = 'Les champs marqués d\'une * sont obligatoires. ';
			}
			if( error[1]==true )
			{
				err.innerHTML = err.innerHTML+'Veuillez vérifier votre email. ';
			}
			err.style.display = 'block';
			frm.valid=false;
		}
	}
	return frm.valid;
}
function inputKeyUp(){
	if( !this.form.valid )
		this.parentNode.className = this.value=='' ? 'missing' : '';
}

// Connecte les fonctions javascript au code html du formulaire de contact
function bindContactForm(){
	var frm = document.getElementById('frm-contact');
	if( frm ){
		frm.valid = true;
		frm.onsubmit = function(){
			return submitContactForm(this);
		}
		for( var i=0; i<frm.elements.length; i++ )
			if( frm.elements[i].type=='text' )
				frm.elements[i].onkeyup = inputKeyUp;
	}
}
window.onload = bindContactForm;

