﻿var gblSubstancesFound ;
var substanceListWindow ;
var gblNumberOfLines = 6 ;

var maxlines = 20 ;
var m20 = Math.pow(2,maxlines) - 1 ; // au plus 20 lignes!

var FORMATTER = new Formatter() ;

var ll = location.hostname.toLowerCase() ;
var ll2 = location.protocol.toLowerCase() ;



var gblSELECTION =""; // à revoir


function showTool(numberOfLines)
{
	if( numberOfLines > maxlines) numberOfLines = maxlines ;
	gblNumberOfLines = numberOfLines

	for ( var i = 0; i <= substancesArray.length ; i++ ) 
	{	
			if( substancesArray[i])
				gblSELECTION += '<option>' + substancesArray[i].name + '</option>\n';
	}

	var tmp = '<table id="toolTable">\n' ;
	tmp += buildHeaderRow() ;
	for ( var i = 0 ; i < numberOfLines  ; i++ )
	{
		tmp += '<tr>\n'
		tmp += buildLineNumberLabel( i ) ; ; 
		tmp += buildSubstanceCombo(i) + '</td>\n' ;
		tmp += buildEmptyPELCombo(i) ;
		tmp += buildExposureValueInputBox(i) ;
		tmp += buildRatioLabel(i) ;
		tmp += '</tr>' ;
	}
	
	tmp += '</table>\n' ;
	
	tmp += FORMATTER.format(
		STRINGS['toolCtlJS'],
		STRINGS['calculateBtnTitle'], // 0
		STRINGS['computeSymbol'], // 1
		STRINGS['srchCriteria'], // 2
		STRINGS['srchCriteriaBoxTitle'], // 3
		STRINGS['srchBtnTitle'], // 4
		STRINGS['searchSymbol'], // 5
		STRINGS['mainListBtnTitle'], // 6
		STRINGS['listSymbol'], // 7
		STRINGS['alternateLanguage1ListBtnTitle'], //8
		STRINGS['alternateLanguage1'], // 9
		STRINGS['listSymbol'] + ' ' + STRINGS['alternateLanguage1'], // 10
		STRINGS['clearBtnTitle'], // 11
		STRINGS['clearSymbol'] 
		); 
	
	document.getElementById("forApplet").innerHTML =  tmp ;
//	sw() ;
	calculate() ;
	function buildHeaderRow() // private
	{
		var rep = '<tr>\n' ;
		rep += '<td class="lineNumber header">' + STRINGS['headerSubstanceNo'] + '</td>\n' ;
		rep += '<td class="substanceCombo header">' + STRINGS['headerSubstance'] + '</td>\n' ;	
		rep += '<td  class="PELCombo header">' + STRINGS['headerPEL'] + '</td>\n' ;
		rep += '<td class="exposureValueBox header">' + STRINGS['headerExp'] + '</td>' ;
		rep += '<td class="ratioLabel header">' + STRINGS['headerPC'] + '</td>\n' ;
		rep += '</tr>' ;
		return rep ;
	}
 
	function buildLineNumberLabel( rowid ) // private
	{
		return '<td class="lineNumber"><div style="cursor:pointer ; cursor : hand ;" onclick="javascript:clearRow(this)" lineNumber="' + rowid + '">' + FORMATTER.fmtLineNumber(rowid) + '</div></td>\n' ;
	}

	function buildSubstanceCombo(rowid) // private
	{
		var rep = '' ;
		rep += '<td class="substanceCombo"><div><select onChange="javascript:updateGui(this) ; " category="sc" lineNumber="' + rowid + '" id="sc'  + rowid + '">' ;
		return rep + gblSELECTION + '</select></div>' + '</td>\n' ;
	}
	
	function buildEmptyPELCombo(rowid) // private
	{
		var rep = '' ;
		rep += '<td  class="PELCombo"><div><select onChange="javascript:updateGui(this) ; " category="pc" lineNumber="' + rowid + '" id="pc'  + rowid + '">' ;
		rep +=  '</select></div></td>\n' ;
		return rep ;
	}
	
	function buildExposureValueInputBox(rowid) // private
	{
		var rep = '' ;
		rep += '<td class="exposureValueBox"><div><input onChange="javascript:updateGui(this) ; " category="evib" lineNumber="' + rowid + '" id="evib'  + rowid + '"></input></div></td>' ;
		return rep ;
	}
	
	function buildRatioLabel(rowid) // private
	{
		var rep = '' ;
		rep += '<td class="ratioLabel"><div id="rlbl'  + rowid + '">?</div></td>\n' ;
		return rep ;
	}


}

function isExposureValueValid( exposureValue)
{
	return ((typeof exposureValue) != 'undefined') && (! isNaN(exposureValue)) && (exposureValue > 0 ) ;
}



function changeRatioLabel(pels, pos, exposureValueInputBox, ratioLabel) 
{
	ratioLabel.innerHTML = '?' ;
	if( pels.length > 0 )
	{
		var exposureValue = exposureValueInputBox.value ;
		if( isExposureValueValid( exposureValue) ) 
		{
			
				var pel = pels[pos] ;
				ratioLabel.innerHTML = FORMATTER.fmtPC( exposureValue / pel.value) ;
		}
	}
}

function updateGui(obj)
{

	var subst ;
	var lineNumber = obj.attributes.lineNumber.value ;
	var category = obj.attributes.category.value ;
	var objid = category + lineNumber ;
	var currentSC = document.getElementById("sc" + lineNumber) ; // substance control 
	var currentPC = document.getElementById("pc" + lineNumber) ; // pel control 
	var currentEVIB = document.getElementById("evib" + lineNumber) ; // exposure value control
	
	var currentRLBL = document.getElementById("rlbl" + lineNumber) ; // ratio label
	if ( category == 'sc' )
	{
		subst = substancesArray[currentSC.selectedIndex] ;
		changePELsCombo(currentPC, subst.pels ) ;
		changeRatioLabel(subst.pels, 0, currentEVIB, currentRLBL) ;
	}

	if ( category == 'pc' )
	{
		subst = substancesArray[currentSC.selectedIndex] ;
		changeRatioLabel(subst.pels, currentPC.selectedIndex, currentEVIB, currentRLBL) ;
	}

	if ( category == 'evib' )
	{
		subst = substancesArray[currentSC.selectedIndex] ;
		changeRatioLabel(subst.pels, (subst.pels.length > 0 ) ? currentPC.selectedIndex : null , currentEVIB, currentRLBL) ;
	}
	
}




function fmtPEL( pel)
{
	return pel.pelType.abr + " : " + pel.value + " " + pel.unit.abr ;
}
function changePELsCombo( pelCombo, pels)
{
	pelCombo.options.length = 0 ;
	var texte ;
	if ( ! pels ) return ;
	for ( var i = 0 ; i < pels.length ; i++ )
	{
		texte = fmtPEL(pels[i]) ;
		pelCombo.options[i] =  new Option(texte,i,false,false) ;
	}
}

function sw()
{
	
	var i = -1 ;

	i++ ;
	applySelection(i+'|668') ;


	i++ ;
	applySelection(i+'|80') ;

	i++ ;
	applySelection(i+'|664') ;

	i++ ;
	applySelection(i+'|588') ;

	i++ ;
	applySelection(i+'|649') ;

	i++ ;
	applySelection(i+'|480') ;


	i++ ;
	applySelection(i+'|198') ;

	i++ ;
	applySelection(i+'|1') ;


	calculate() ;
	
	
	
}

function applySelection(s)
{
	var v = s.split("|") ;
	var p = parseInt(v[0]) ;
	var sid = parseInt(v[1]) ;
	document.getElementById("sc"+ (p)).selectedIndex = getSubstanceById(sid).arrayIndex ;
	updateGui(document.getElementById("sc" + p)) ;
	
}

function clearRow( obj )
{
	var p = parseInt(obj.attributes.lineNumber.value ) ;
	var ctl = document.getElementById("sc"+ (p)) ;
	if ( ctl.selectedIndex  == 0 ) return ;
	//p++ ; p-- ;
	if(window.confirm(FORMATTER.format(STRINGS['clearRow'], FORMATTER.fmtLineNumber(p))))
	{
		
		document.getElementById("evib"+ (p)).value = '' ;
		ctl.selectedIndex = 0 ;
		updateGui(ctl) ;
		calculate() ;
	}
}


function calculate()
{
	var subst ;
	
	var resContainer = new ResultsContainer() ;
	
	for( var iline = 0 ; iline < gblNumberOfLines ; iline++ )
	{
		
		subst = substancesArray[document.getElementById("sc" + iline).selectedIndex] ;
		var pel = null ;
		if ( subst.pels.length > 0 )
		{
				pel = subst.pels[document.getElementById("pc" + iline).selectedIndex] ;
			
		}
		
		resContainer.addSubstanceToResults( new SelectionLine(iline,subst, pel, document.getElementById("evib" + iline).value ) ) ;
	}
	

	resContainer.combineResults() ;
	
	document.getElementById("zoneDeTexte").innerHTML = resContainer.toHTML() ;
}

function searchSubstances(str)
{
	
	if ( str == '' )
	{
		alert(STRINGS['srchEmptyCriteria']) ;
		return ;
	}
	var re = new RegExp( str,'i' ) ;
	gblSubstancesFound = new Array() ;
	
	
	for ( var i = 1 ; i < substancesArray.length ; i++ )
	{
		if( re.test(substancesArray[i].name))
			gblSubstancesFound[gblSubstancesFound.length] = substancesArray[i] ;
	}


	if(gblSubstancesFound.length == 0)
		alert(STRINGS['srchNoSubstanceFound']) ;
	else
	{
	
		var fmt =STRINGS['srchLstOneEntryJS'] ; 
//		alert(STRINGS['srchLstOneEntryJS']) ;
		var rep = '' ;
		for (var i = 0 ; i < gblSubstancesFound.length ; i++ ) 
			rep += FORMATTER.format(fmt, gblSubstancesFound[i].externalReference,gblSubstancesFound[i].name,STRINGS['srchADD']) ;
		rep = FORMATTER.format(STRINGS['srchLstPage'], STRINGS['srchPageTitle'],STRINGS['srchCriteria'],str, rep) ;
		var f = window.open('','subst','location=yes,toolbar=yes,menubar=no,width=700,height=550,scrollbars=yes,resizable=yes, dependent=yes') ;
		f.document.write(rep) ;
		f.document.close() ;
		f.focus() ;
	}
}

function clearUserSelections()
{
	if(window.confirm(STRINGS['clearAll']))
	{
		for ( var p = 0 ; p < gblNumberOfLines ; p++ )
		{
		document.getElementById("sc"+ (p)).selectedIndex = 0 ;
		document.getElementById("evib"+ (p)).value = '' ;
		updateGui(document.getElementById("sc" + p)) ;
		}	
		calculate() ;
	}
}


function changeUserSelections(sel) {
//		sel = '0+s000340+0+-1.0|1+s000586+3+12.512|2+s000101+0+-1.0|3+s000494+0+13.0|4+s000067+0+-1.0|5+DUMMY+-1+-1.0|6+DUMMY+-1+-1.0|7+s000111+0+1.232345|8+DUMMY+-1+-1.0|9+DUMMY+-1+-1.0|10+DUMMY+-1+-1.0|11+s000080+0+134.555556' ;
		if (sel == "") 	return;

		var splitted1 = sel.split('|');
		var splitted2;
		var lineNumber ;
		var sub ;
		var pelsComboIndex ;
		var expValue ; 	
		var isid ;	
		var currentPC ; // pel combo
		var currentEVIB ; // Exposure value input box
		var currentRLBL ; // Ratio label
		for (var i = 0; i < splitted1.length; i++)
		{
			splitted2 = splitted1[i].split('+');
			lineNumber = splitted2[0] ;
			if(lineNumber < gblNumberOfLines ) 
			{
				isid = Number(splitted2[1].substring(1, splitted2[1].length));
				if ( isNaN(isid)) isid = 0 ; // première substance
				
				sub = getSubstanceById(isid) ;
				pelsComboIndex = splitted2[2] 
				expValue = splitted2[3] ;
				if(isNaN(expValue)) expValue = '' ;
				if(expValue == -1.0 ) expValue = '' ;
				
				document.getElementById(("sc"+ (lineNumber))).selectedIndex = sub.arrayIndex ;
	
				currentPC = document.getElementById(("pc"+ (lineNumber))) ;
				changePELsCombo(currentPC, sub.pels ) ;
				currentPC.selectedIndex = pelsComboIndex ;
				
				currentEVIB = document.getElementById(("evib"+ (lineNumber))) ;
				currentEVIB.value = expValue ;
				
				currentRLBL = document.getElementById("rlbl" + lineNumber) ; // ratio label			
				document.getElementById(("evib"+ (lineNumber)))
				changeRatioLabel(sub.pels, 0, currentEVIB, currentRLBL) ;
			}

		}
		calculate() ;
		

}


function addToUserSelection( sid)
{
	var ind = -1 ;
	var ctl ;
	var firstAvailable = -1 ;
	var isid ;
	for ( var i = 1 ; i < sid.length ; i++ )
	{
		if(sid.charAt(i) != '0' )
		{
			isid = sid.substring(i, sid.length) ;
			break ;
		}
	}
	

	var subst = getSubstanceById(isid) ;
	var indNewSusbstanceIndex = subst.arrayIndex ;
	var substName = subst.name ;
	
	for ( var i = 0 ; i < gblNumberOfLines ; i++ )
	{
		ctl = document.getElementById("sc"+ (i)) ;
		ind = ctl.selectedIndex ;
		
		if( indNewSusbstanceIndex == ind )
		{
			return FORMATTER.format(STRINGS['srchAlreadySelected'], substName)  ; 
		}
		if ( ind == 0 )
		{
			if( firstAvailable == -1) firstAvailable = i ;			
		}
	}
	if( firstAvailable != -1 )
	{
			ctl = document.getElementById("sc"+ (firstAvailable)) ;
			ctl.selectedIndex = getSubstanceById(isid).arrayIndex ;
			updateGui(document.getElementById("sc" + firstAvailable)) ;
			return 'Ok' ;
	}
	
	return  STRINGS['srchNoMoreRoom'] ;
}


function showSubstanceList(lang)
{
	var lng ;
	if( arguments.length == 0 )
		lng = language ;
	else
		lng = lang ;
	if( ! substanceListWindow || substanceListWindow.closed ) 
		substanceListWindow = window.open( lng + '/db.htm','db','location=yes,toolbar=yes,menubar=no,width=700,height=550,scrollbars=yes,resizable=yes, dependent=yes') ;
		substanceListWindow.focus() ;
}


