String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

doMfpFRValidation = function() {            
    
	if( $('allergies_0').checked && $('allergies_1').value.trim() == "" ){
		return showCustomAlert('Entrez du texte ou décochez la case','allergies_1');
	}
	if( $('ntolerences_0').checked && $('ntolerences_1').value.trim() == "" ){
		return showCustomAlert( 'Entrez du texte ou décochez la case','ntolerences_1');		
	}
	if( $('diabete_0').checked && $('diabete_1').value.trim() == "" ){		
		return showCustomAlert( 'Entrez du texte ou décochez la case','diabete_1');
	}
	if( $('grossesse_0').checked && $('grossesse_1').value.trim() == "" ){		
		return showCustomAlert( 'Entrez du texte ou décochez la case','grossesse_1');		
	}
	if( $('contagionpossible_0').checked && $('contagionpossible_1').value.trim() == "" ){
		return showCustomAlert( 'Entrez du texte ou décochez la case','contagionpossible_1');		
	}
	
	//date of birth (date de naissance) must be less than current date	
	if( checkDateDiff( 'datedenaissance' , "La date de naissance est incorrecte", 1, 0 ) == false){
		return false;
	}
	// Date de sortie has to be equal or greater to the Date d’entrée
	if( checkDateDiff( 'datedesortieprevue' , "La date de sortie est incorrecte", 0, 0,'dateetheuredentree' ) == false){
		return false;
	}
	// Date d'entré superior or equal to the current date
	if( checkDateDiff( 'dateetheuredentree' , "La date d’entrée est incorrecte", 0, 0 ) == false){
		return false;
	}

	//check allergies if values are present in text box	
	if( $('allergies_1').value.trim() != "" || $('medicaments5').value.trim() != "" || $('medicaments6').value.trim() != ""  ){		$('allergies_0').checked = true;	}else{		$('allergies_0').checked = false;	}
	
	//check Intolerences if values are present in text box	
	if( $('ntolerences_1').value.trim() != "" || $('medicaments7').value.trim() != "" || $('medicaments8').value.trim() != ""  ){		$('ntolerences_0').checked = true;	}else{		$('ntolerences_0').checked = false;	}
	
	//check Diabetes if values are present in text box	
	if( $('diabete_1').value.trim() != "" || $('medicaments9').value.trim() != "" || $('medicaments10').value.trim() != ""  ){		$('diabete_0').checked = true;	}else{		$('diabete_0').checked = false;	}
	
	//check Grossesse if values are present in text box	
	if( $('grossesse_1').value.trim() != "" ){		$('grossesse_0').checked = true;	}else{		$('grossesse_0').checked = false;	}
	
	//check Contagion possible if values are present in text box	
	if( $('contagionpossible_1').value.trim() != "" ){		$('contagionpossible_0').checked = true;	}else{		$('contagionpossible_0').checked = false;	}		
	
	//When the value for the field « Evolution post-op » is equal to « EMS » or « SDS » the field « Etablissement souhaité » become required	
	if( ( $('evolutionpostoperatoire').value == "EMS" || $('evolutionpostoperatoire').value == "SDS" ) && $('etablissementsouhaite').value.trim() == "" ){		
		return showCustomAlert("Etablissement souhaité manquant",'etablissementsouhaite');		
	}	
		
	/*$('ntolerences_0').checked
	$('diabete_0').checked
	$('grossesse_0').checked
	$('contagionpossible_0').checked
	*/
	if ( addHourandMin('dateetheuredentree', 'Date et heure d’entrée manquant') == false ){ return false; }
	if ( addHourandMin('dateetheureconsultation', 'Date et heure de la consultation anesthésie manquant') == false){ return false; }
	if ( addHourandMin('dateetheuredintervention', 'Date et heure d’intervention manquant') == false ){ return false; }

    //fix word lengths for all text areas
	fixWordLength('adresse',25);
    fixWordLength('commentaires',25);
    fixWordLength('diagnostic',25);
    fixWordLength('preparationsinecessaire',25);
    fixWordLength('materielsinecessaire',25);
    fixWordLength('etablissementsouhaite',25);
    fixWordLength('commentaires_1',25);

	$('mfpFeuR').submit();
}

function fixWordLength(object,maxLength){
    var wordsarray = $(object).value.split(/[\s]+/);
    var tmpWord='';
    var errorOccured = false;
    var finalWord = '';
    
    for(var i=0;i<wordsarray.length;i++){    
        if(wordsarray[i].length > maxLength){
            tmpWord = wordsarray[i].substring(0,maxLength);
            tmpWord += ' ' + wordsarray[i].substring(maxLength);
            wordsarray[i] = tmpWord;
            errorOccured = true;
        }
        finalWord += wordsarray[i] + ' ';
    }
    $(object).value = finalWord;
    if(errorOccured ){fixWordLength(object,maxLength);}
}


addHourandMin = function(targetId,msg,noAlerts){
	if($(targetId).value)	{
		if( $(targetId+'_hour').value && $(targetId+'_min').value )	{
			
			//	first extract only the first 8 characters in the field			
			$(targetId).value = $(targetId).value.truncate(10,'') + " " + $(targetId+'_hour').value + ":" + $(targetId+'_min').value;
		}	else	{
			setHighLight(targetId+'_hour');
			setHighLight(targetId+'_min');
			if( !noAlerts ){
				showCustomAlert(msg,targetId,1);
			}else{
				setHighLight(targetId);
			}
			return false;
		}
	}
	removeHighlights(targetId);
	removeHighlights(targetId+'_hour');
	removeHighlights(targetId+'_min');
}

showCustomAlert =function(	msg,targetId,keepHighlight,noAlert 	)	{	
	setHighLight(targetId);
	if( !noAlert )	{
		alert( msg );
	}
	$(targetId).focus();
	if(!keepHighlight){
		removeHighlights(targetId);
	}
	return false;
}
setHighLight = function (targetId)	{
	$(targetId).style.border = "2px solid #FF552A";
}
removeHighlights = function(targetId)	{
	$(targetId).style.border = "1px solid #0066CC";
}

checkDateDiff =function(	dateA, msg, dateAGreater, noAlert, dateB	)	{
	
	var currentTime = new Date()
	var mon2 = currentTime.getMonth() + 1;
	var	dt2 = currentTime.getDate();
	var	yr2 = currentTime.getFullYear();
	var a,b,c;
	var str1  = $(dateA).value;		
	var str2;	
	if(str1 == "") return true;
	
	var dt1   = parseInt(str1.substring(0,2),10);
	var mon1  = parseInt(str1.substring(3,5),10);
	var yr1   = parseInt(str1.substring(6,10),10);
	//if target date is given
	if( dateB != null ){		
		str2  = $(dateB).value;	
		dt2   = parseInt(str2.substring(0,2),10);
		mon2  = parseInt(str2.substring(3,5),10);
		yr2   = parseInt(str2.substring(6,10),10);
	}				
		
	var date1 = new Date(yr1, mon1, dt1);
	var date2 = new Date(yr2, mon2, dt2); 	
	
	// check if a is greater
	if(	dateAGreater ){
		if( date1 > date2 ){
			return showCustomAlert(msg,dateA,1,noAlert);
			//alert("yes a: " + date1 + " b: " + date2);
		}
		//alert($(dateA).value + " - date1:" + date1 + " date2:" + date2 + " \n mon1: " + mon1 + " mon2:" + mon2);
	}else{
		if( date2 > date1 ){
			return showCustomAlert(msg,dateA,1,noAlert);
		}
	}
	removeHighlights(dateA);
	return true;
}

// validate inputs after submission
document.observe("dom:loaded",function(){ if( $('mailFormSubmitFR') ){ $('mailFormSubmitFR').onclick = function() { doMfpFRValidation();};} });

// date of birth (date de naissance) must be less than current date
document.observe("dom:loaded",function(){ if( $('datedenaissance') ){ $('datedenaissance').onchange = function() { checkDateDiff( 'datedenaissance' , "Date de naissance can’t be in the future", 1 ,1 ); };} });
// Date de sortie has to be equal or greater to the Date d’entrée
document.observe("dom:loaded",function(){ if( $('datedesortieprevue') ){ $('datedesortieprevue').onchange = function() { checkDateDiff( 'datedesortieprevue' , "Date de sortie has to be equal or Superior to the Date d’entrée", 0, 1,'dateetheuredentree' ); };} });

// Date d'entré inferior or equal to the current date and //make sure hour and minutes are entered
document.observe("dom:loaded",function(){ if( $('dateetheuredentree') ){ $('dateetheuredentree').onchange = function() { addHourandMin('dateetheuredentree', 'Date et heure d’entrée manquant',1); checkDateDiff( 'dateetheuredentree' , "Date d'entré inferior or equal to the current date", 1 ,1 ); };} });
document.observe("dom:loaded",function(){ if( $('dateetheureconsultation') ){ $('dateetheureconsultation').onchange = function() { addHourandMin('dateetheureconsultation', 'Date et heure de la consultation anesthésie manquant',1); };} });
document.observe("dom:loaded",function(){ if( $('dateetheuredintervention') ){ $('dateetheuredintervention').onchange = function() { addHourandMin('dateetheuredintervention', 'Date et heure d’intervention manquant',1); };} });
//check again for minutes and hours
document.observe("dom:loaded",function(){ if( $('dateetheuredentree_min') ){ $('dateetheuredentree_min').onchange = function() { addHourandMin('dateetheuredentree', 'Date et heure d’entrée manquant',1); };} });
document.observe("dom:loaded",function(){ if( $('dateetheureconsultation_min') ){ $('dateetheureconsultation_min').onchange = function() { addHourandMin('dateetheureconsultation', 'Date et heure de la consultation anesthésie manquant',1); };} });
document.observe("dom:loaded",function(){ if( $('dateetheuredintervention_min') ){ $('dateetheuredintervention_min').onchange = function() { addHourandMin('dateetheuredintervention', 'Date et heure d’intervention manquant',1); };} });
document.observe("dom:loaded",function(){ if( $('dateetheuredentree_hour') ){ $('dateetheuredentree_hour').onchange = function() { addHourandMin('dateetheuredentree', 'Date et heure d’entrée manquant',1); };} });
document.observe("dom:loaded",function(){ if( $('dateetheureconsultation_hour') ){ $('dateetheureconsultation_hour').onchange = function() { addHourandMin('dateetheureconsultation', 'Date et heure de la consultation anesthésie manquant',1); };} });
document.observe("dom:loaded",function(){ if( $('dateetheuredintervention_hour') ){ $('dateetheuredintervention_hour').onchange = function() { addHourandMin('dateetheuredintervention', 'Date et heure d’intervention manquant',1); };} });

// hide print button
/*
	document.observe("dom:loaded",function(){ if( $('cw_toolspages') && !$('cw_toolspages_show') ){ $('cw_toolspages').style.display = 'none'; } });
*/
