function doNothing(){}

function e(id) {
	return document.getElementById(id);
}

function hide(id) {
	var el = e(id);
	if(el)
		el.style.display = 'none';
	return el;
}

function show(id) {
	var el = e(id);
	if (el != null)
		el.style.display = ''; // or 'block'
	return e;
}

function getEventTarget(ev) {
	var event = ev ? ev : window.event;
	var target = event.target ? event.target : event.srcElement;
	if (target.nodeType == 3) target = target.parentNode; // handle Safari bug
	return target;
}

function isIE6(){
	var ua = navigator.userAgent.toLowerCase();
	return /msie 6/.test(ua) && ! /msie 7/.test(ua);
}

var SERVER_DATE;

function getGMTServerDate(){
	newDate = new Date();
	if(SERVER_DATE){
		newDate.setDate(SERVER_DATE.getDate());
		newDate.setMonth(SERVER_DATE.getMonth());
		newDate.setYear(SERVER_DATE.getFullYear());
		newDate.setHours(SERVER_DATE.getHours());
		newDate.setMinutes(SERVER_DATE.getMinutes());
		newDate.setSeconds(SERVER_DATE.getSeconds());
	}
	return newDate;
}

if (typeof logError == "undefined") {
	logError = function(){};
}
if (typeof logDebug == "undefined") {
	logDebug = function(){};
}

function cancelEvent(event) {
	if (event.preventDefault) event.preventDefault(); // FF and others
	if (event.stopPropagation) event.stopPropagation(); // FF and others
	event.returnValue = false; // IE
	event.cancelBubble = true; // IE
}

function isMouseOutForTarget(event, targetId) {
	if (! event) var event = window.event;
	var target = getEventTarget(event);
	if (target.id != targetId) return false; // Mouse left some other element.
	var relTarget = (event.relatedTarget) ? event.relatedTarget : event.toElement;
	while (relTarget != target && relTarget.nodeName != 'BODY') // See if ancestor of related target is the target.
		relTarget = relTarget.parentNode
	if (relTarget == target) return false; // Mouse moved to a link in element or child of element.
	// Mouse out event took place when mouse actually left element with id 'targetId'.
	return true;
}

// --- Company list start ---
var listmap = {};
function getCompanyList(id) {
	var templist = listmap[id];
	if (templist == null) {
		templist = list;
		if (typeof initCompanyListMulti != "undefined") {
			templist = new ListBox();
			initCompanyListMulti(templist);
		} else if (typeof initCompanyList != "undefined") {
			initCompanyList();
		} else if (typeof initHomeCompanyList != "undefined") {
			initHomeCompanyList();
		}
		listmap[id] = templist;
	}
	return templist;
}

// All starting here
var isOverList = false;
var companyListFieldId = null;
function companyListOnFocus(event, id) {
	if(e('keyWords').value=='Company Name')
		e('keyWords').value = '';
	dd("companyListOnFocus " + (companyList == null));
	if (companyList == null) return;

	// Hack to make sure these 2 global variables are always initialized.
	se = document.searchForm;

	try {
		var target;
		// START - For backward compatibility with multicompany.do page.
		if (id) target = e(id); else
		//END - For backward compatibility with multicompany.do page. 
		target = getEventTarget(event);
		var templist = getCompanyList(target.id);
		templist.open(target);
		companyListFieldId = target.id;
		document.getElementById(target.id).select();
	} catch (err) {
		logError(err, "companyListOnFocus");
	}
}

function companyListOnKeyDown(event) {
	if (companyList == null) return;
	if (! event) event = window.event;
	var target = getEventTarget(event);
	var templist = getCompanyList(target.id);
	try {
		templist.processKeyDownEvent(event);
	} catch (err) {
		logError(err, "companyListOnKeyDown");
	}
}

function companyListOnKeyPress(event) {
	if (companyList == null) return;
	if (! event) event = window.event;
	var target = getEventTarget(event);
	var templist = getCompanyList(target.id);
	try {
		templist.processKeyPressEvent(event);
	} catch (err) {
		logError(err, "companyListOnKeyPress");
	}
}

function companyListOnKeyUp(event) {
	if (companyList == null) return;
	if (! event) event = window.event;
	var target = getEventTarget(event);
	var templist = getCompanyList(target.id);
	try {
		templist.processKeyUpEvent(event);
	} catch (err) {
		logError(err, "companyListOnKeyUp");
	}
}

function companyListOnBlur(event) {
	dd("companyListOnBlur " + isOverList + " " + (companyList == null));
	if (isOverList) return;
	if (companyList == null) return;
	var target = getEventTarget(event);
	var templist = getCompanyList(target.id);
	try {
		templist.close();
	} catch (err) {
		// Ignore error on close, not relevant.
	}
}

function ListBox(){
	this.maxLength = 20;
	this.maxShownLength = 10;
	this.maxHeight = 160;
	this.minChars = 3;
	this.scrollingIncrement = 16;

	this.div = null;
	this.targetBox = null;
	this.initialValue = null;
	this._clearResults();
	this.searchHandler = new function(entry){};
	this.fullListHandler = new function(entry){};
	this.codeInputs = new Object();
	this.valueInputs = new Object();
	this.targetObjects = new Object();
	this.fieldsTohide = new Object();
	this.nextFocusField = new Object();
}

var lP=ListBox.prototype;

lP.open=function(pTarget){
	dd("open " + pTarget);
	// Properly close previous list if still open.
	if (this.list != null) this.close();

	this.targetBox = pTarget;
	this.initialValue = pTarget.value;
	this._updateShownList(this.targetBox.value);
	this._toggleSelectFields(false);
	
	isOverList = true;
	
	var node = document.getElementsByTagName("BODY")[0];
	if (! node.addEventListener)
		node.attachEvent("onmousedown", this.onBodyClick);
	else
		node.addEventListener("mousedown", this.onBodyClick, false);
}

lP.mover=function(event){
	dd("mover");
	// IE 8 needs this line to prevent the companylist from hiding, when the user types "can", mouses over the list,
	// exits the list to the right and then clicks on the companylist scrollbar (this exact sequence). IE 6, IE 7, FF and
	// other browsers do not need this (no effect).
	isOverList = true;
}

lP.mout=function(event){
	if (! isMouseOutForTarget(event, "companylist")) return;  // Ignore child triggered events.
	dd("mout");
	isOverList = false;
}

lP.close=function(){
	dd("close " + isOverList);
	isOverList = false;
	if (this.targetBox == null || typeof this.targetBox == 'undefined') return; 
	dd("closing: " + this.targetBox.value + "|" + this.initialValue + "|" + this.currentIndex);
	//below condition was commented to fix the TR95009527
	//if (this.targetBox.value != this.initialValue && this.currentIndex != -1) {
	if (this.list !=null && this.currentIndex != -1) {
		this._updateCurrentField();
		this._updateRegisteredInputs();
	}
	this._hide();
	this._clearResults();
	this._toggleSelectFields(true);

	var node = document.getElementsByTagName("body")[0];
	if (! node.addEventListener)
		node.detachEvent("onmousedown", this.onBodyClick);
	else
		node.removeEventListener("mousedown", this.onBodyClick, false);
}

lP.onBodyClick=function(event) {
	dd("onBodyClick");
	var target = getEventTarget(event);
	while (target.id != "companylist" && target.id != companyListFieldId && target.nodeName != 'BODY')
		target = target.parentNode;

	if (target.id == "companylist" || target.id == companyListFieldId) return; // Click was done inside companylist.

	var templist = getCompanyList(companyListFieldId);
	templist.currentIndex = -1;
	templist.close(); 
}

lP.mouseOverItem=function(event){
	isOverList = true;
	var templist = getCompanyList(companyListFieldId);
	templist.unselect();
	var target = getEventTarget(event);
	target.className = "over";
	templist.currentIndex = target.getAttribute("pos");
}

lP.mouseOutItem=function(event){
	var templist = getCompanyList(companyListFieldId);
	var target = getEventTarget(event);
	target.className = "";
}

lP.processKeyDownEvent=function(event){
	// START - For backward compatibility with searchForm.do page.
	if (this.list == null) {
		if (! event) event = window.event;
		this.open(getEventTarget(event));
	} 
	//END - For backward compatibility with searchForm.do page. 
	switch(event['keyCode']){
		case 38: this.selectPrevious(); break;		// Up arrow
		case 40: this.selectNext(); break;			// Down arrow
		case 9:											// Tab
			if (this.currentIndex == -1) this.currentIndex = 0;
			isOverList = false;
			this.close(); // Added for IE8 which changes how events are handled
			break;
		case 13:										// Enter
			if (this.currentIndex == -1) this.currentIndex = 0;
			isOverList = false;
			this.close(); // Added for IE8 which changes how events are handled
			this.nextFocus();
			break;
	}
}

lP.processKeyPressEvent=function(event){
	switch(event['keyCode']){
		case 38: case 40: case 13: cancelEvent(event); break;
	}
}

lP.processKeyUpEvent=function(event){
	switch(event['keyCode']){
		case 38: case 40: case 9: case 13:
			break;
		default: this._updateShownList(this.targetBox.value);
	}
}

// START - For backward compatibility with searchForm.do page. 
lP.clickOut=function(event){
	dd("clickOut");
	var templist = getCompanyList(companyListFieldId);
	templist.close(); 
}

lP.clickDown=function(event){
	dd("clickDown");
	var templist = getCompanyList(companyListFieldId);
	templist.close(); 
	return true;
}

lP.processKeyEvent=function(event){
	var templist = getCompanyList(companyListFieldId);
	templist.processKeyUpEvent(event);
}
lP.hide=function(){
	var templist = getCompanyList(companyListFieldId);
	templist._hide();
}
//END - For backward compatibility with searchForm.do page. 
	
lP._show=function(){
	dd("_show");
	if (this.div != null) {
		this._position();
		this.div.style.display = "";
	}
}

lP._clearResults=function(){
	this.list = null;
	this.currentIndex = -1;
	this.initialValue = null;
}

lP._hide=function(){
	dd("_hide");
	if (this.div) this.div.style.display = "none";
	if (! e("companylist")) return; // For backward compatibility with searchForm.do page.
	e("companylist").style.display = "none";
	if (! e("companysearchinfodiv")) return; // For backward compatibility with searchForm.do page.
	e("companysearchinfodiv").style.display = "none";
	if (! e("companysearchinfodiverror")) return; // For backward compatibility with searchForm.do page.
	e("companysearchinfodiverror").style.display = "none";
}

lP._toggleSelectFields=function(show){
	if (this.targetBox == null || this.targetBox.id == null) return;
	var fields = this.fieldsTohide[this.targetBox.id];
	if (fields == null) return;
	for (var i = 0; i < fields.length; i++){
		var field = e(fields[i]);
		if (! field) continue;
		var replacementField = e(fields[i] + "_replacement");
		if (show) {
			if (replacementField) replacementField.style.display = "none";
			field.style.display = "";
		} else {
			var tmpValue = field.options[field.selectedIndex].text;
			var tmpWidth = field.offsetWidth;
			//var tmpHeight = field.offsetHeight;
			field.style.display = "none";
			if (replacementField) {
				if (tmpWidth > 0) {
				 replacementField.style.width = tmpWidth + "px";
				 replacementField.style.paddingLeft = "3px";
				 replacementField.style.paddingTop = "1px";
				 replacementField.style.paddingBottom = "0px";
				 replacementField.style.marginTop = "0px";
				 replacementField.style.marginBottom = "1px";
				}
				 replacementField.style.display = "";
				 replacementField.value = tmpValue;
			}
		}
	}
}

lP._populateDiv=function(data){
	dd("_populateDiv");
	this.div.style.height = (data.length >= this.maxShownLength) ? this.maxHeight + "px" : "";
	this.div.innerHTML = "";
	this.div.className = "listbox";

	for (var i = 0; i < data.length && i < this.maxLength; i++){
		var node = document.createElement("div");
		node.setAttribute("pos", i);
		node.setAttribute("code", data[i].value);
		node.appendChild(document.createTextNode(data[i].text));
		if (! node.addEventListener){
			node.attachEvent("onmouseover", this.mouseOverItem);
			node.attachEvent("onmouseout", this.mouseOutItem);
			node.attachEvent("onmousedown", this.clickDown);
		}else{
			node.addEventListener("mouseover", this.mouseOverItem, false);
			node.addEventListener("mouseout", this.mouseOutItem, false);
			node.addEventListener("mousedown", this.clickDown, false);
		}
		this.div.appendChild(node);
	}
}

lP._configureDiv=function(){
	dd("_configureDiv");
	this.div = e("companylist");
	if (! this.div) {
		logError("Missing companylist DIV", "companylist.js@lP.open");

		// IE (all versions) will unload the page if the companylist is used before page is
		// completely loaded. To avoid this, make sure an empty DIV with an id of
		// "companylist" exists on the page so this code never gets executed.
		this.div = document.createElement("div");
		this.div.setAttribute("id", "companylist");
		document.getElementsByTagName("body")[0].appendChild(this.div);
	}
	if(! this.div.addEventListener){
		this.div.attachEvent("onmouseover", this.mover);
		this.div.attachEvent("onmouseout", this.mout);
	}else{
		this.div.addEventListener("mouseover", this.mover, false);
		this.div.addEventListener("mouseout", this.mout, false);
	}
}

lP._updateCurrentField=function(){
	if (this.list != null && this.list.length > 0 && this.currentIndex != -1) {
		dd("_updateCurrentField true " + this.getSelectedValue());
		this.targetBox.value = this.getSelectedValue();
		this.targetBox.className = "";
	} else {
		dd("_updateCurrentField false");
	}
}

lP.unselect=function(){
	if (this.list == null) return;
	for (var i = 0; i < this.div.childNodes.length; i++)
		this.div.childNodes[i].className = "";
}

lP.selectFirst=function(){
	if (this.list.length < 1) return;
	this.unselect();
	this.div.childNodes[0].className = "on";
}

lP.scrollUp=function(){
	var presentVisible = parseInt((this.currentIndex) * this.scrollingIncrement);
	this.div.scrollTop = presentVisible - this.scrollingIncrement;
}

lP.scrollDown=function(){
	var presentVisible = parseInt((this.currentIndex - 3) * this.scrollingIncrement);
	this.div.scrollTop = presentVisible + this.scrollingIncrement;
}

lP.selectNext=function(){
	this.unselect();
	if (this.currentIndex < 0) this.currentIndex = 0;
	else if (this.currentIndex < (this.div.childNodes.length - 1)){this.currentIndex++; this.scrollDown();}
	this.div.childNodes[this.currentIndex].className = "on";
}

lP.selectPrevious=function(){
	this.unselect();
	if (this.currentIndex > 0){ this.currentIndex--; this.scrollUp();}
	this.div.childNodes[this.currentIndex].className = "on";
}

lP.getSelectedCode=function()  {return this.isValidSelected() ? this.list[this.currentIndex].value : "";}
lP.getSelectedObject=function(){return this.isValidSelected() ? this.list[this.currentIndex] : null;}
lP.getSelectedValue=function() {return this.isValidSelected() ? this.list[this.currentIndex].text : "";}
lP.isValidSelected=function(){
	return this.list != null && this.currentIndex >= 0 && this.currentIndex < this.list.length;
}
lP._showInfoDiv=function(){
	var listInfoDiv = (this.targetBox.className == 'invalid') ? e('companysearchinfodiverror'): e('companysearchinfodiv');
	if (! listInfoDiv) return;
	listInfoDiv.style.position = "absolute";
	listInfoDiv.style.left = this.findPosX(this.targetBox) + "px";
	listInfoDiv.style.top = (this.findPosY(this.targetBox) + 18) + "px";
	listInfoDiv.style.display = "block";
}

lP._hideInfoDiv=function(){
	if (! e('companysearchinfodiv')) return;
	e('companysearchinfodiv').style.display = "none";
	if (e('companysearchinfodiverror')) e('companysearchinfodiverror').style.display = "none";
}

lP._updateShownList=function(inputValue){
	dd("_updateShownList");
	if (! this.div) this._configureDiv();
	if (this.div.scrollTop != null) this.div.scrollTop = 0;

	if (inputValue.length < this.minChars) {
		this._clearResults();
		this.targetBox.className = '';
		this._hide();
		this._showInfoDiv();
		return true;
	}

	this.list = this.searchHandler(inputValue);
	if (this.list.length == 0) {
		this._clearResults();
		this.targetBox.className = 'invalid';
		this._hide();
		this._showInfoDiv();
		return true;
	}

	this.currentIndex = 0;
	this.targetBox.className = '' ;
	this._populateDiv(this.list);
	this.div.childNodes[this.currentIndex].className = "over";
	this._hideInfoDiv();
	this._show();
}

lP.processFullListing=function(target){
	var data = this.fullListHandler();
	(this.data.length == 0) ? this.hide() : this.open(target);
}
lP.setSearchHandler=function(f){this.searchHandler = f;}
lP.setFullListHandler=function(f){this.fullListHandler = f;}
lP._updateRegisteredInputs=function(){
	dd("_updateRegisteredInputs " + this.getSelectedCode());
	this._setRegisteredInputs(this.codeInputs, this.targetBox.id, this.getSelectedCode());
	this._setRegisteredInputs(this.valueInputs, this.targetBox.id, this.getSelectedValue());
	this.targetObjects[this.targetBox.id] = this.getSelectedObject();
}
lP._setRegisteredInputs=function(regInputs, targetId, value){
	var inputs = regInputs[targetId];
	if (inputs == null) return;
	for (var i = 0; i < inputs.length; i++){
		if (e(inputs[i]) != null)
			e(inputs[i]).value = value;
	}
}
lP.registerCodeInput=function(sourceFieldId, targetFieldId){
	if (this.codeInputs[sourceFieldId] == null) this.codeInputs[sourceFieldId] = new Array();
	this.codeInputs[sourceFieldId].push(targetFieldId);
}
lP.registerNextFocusField=function(fieldId, nextFieldId){
	this.nextFocusField[fieldId] = nextFieldId;
}
lP.nextFocus=function(){
	var fieldId = this.nextFocusField[this.targetBox.id];
	if (fieldId != null && e(fieldId) != null)
		e(fieldId).focus();
}
lP.findPosX=function(obj){
	var curleft=0;
	if(obj.offsetParent){
		while(obj.offsetParent){
			curleft+=obj.offsetLeft;
			obj=obj.offsetParent;
		}
	}
	else if(obj.x) curleft+=obj.x;
	return curleft;
}
lP.findPosY=function(obj){
	var curtop=0;
	if(obj.offsetParent){
		while(obj.offsetParent){
			curtop+=obj.offsetTop;
			obj=obj.offsetParent;
		}
	}
	else if(obj.y) curtop+=obj.y;
	return curtop;
}
lP._position=function(){
	var c=this.div;
	c.style.position="absolute";
	c.style.left=this.findPosX(this.targetBox)+"px";
	c.style.top=(this.findPosY(this.targetBox)+18)+"px";
	c.style.display="block";
}

function parseInputString(input){
	if (! input) return null;
	input = input.replace(/\([^)]+\)/g, "");
	input=input.replace(/[éèêëÉÈÊË]/g,"e");
	input=input.replace(/[àâäÀÂÄ]/g,"a");
	input=input.replace(/[ïîìÏÎÌ]/g,"i");
	input=input.replace(/[ôöòÔÖÒ]/g,"o");
	input=input.replace(/[ûüùÛÜÙ]/g,"u");
	input=input.replace(/[çÇ]/g,"c");
	input = input.replace(/[-()]/g, " ");
	input = input.replace(/[^A-Za-z0-9\.\/' \-]+/g," ");
	return input.toLowerCase();
}

String.prototype.soundex=function(p){
	p=isNaN(p)?4:p>10?10:p<4?4:p;
	var m={BFPV:1,CGJKQSXZ:2,DT:3,L:4,MN:5,R:6},r=(s=this.toUpperCase().replace(/[^A-Z]/g,"").split("")).splice(0,1);
	for(var i in s){
		for(var j in m){
			if(j.indexOf(s[i])+1&&r[r.length-1]!=m[j]&&r.push(m[j])) break;
		}
	}
	return r.length>p&&(r.length=p),r.join("")+(new Array(p-r.length+1)).join("0");
}

function CompanyList(){
	this.companies=new Array();
	this.listInUse=false;
	this.populate();
}

var cP=CompanyList.prototype;
cP.add=function(ac,n,err){
	var companyInfo=new setCompanyInfo(ac,n,err);
	companyInfo.setText();
	this.companies.push(companyInfo);
}
cP.populate=function(){populateCompanies(this);}
cP.sortCompaniesByName=function(a,b) {
	if(a.name==b.name)return 0;
	if(a.name<b.name){return -1};
	if(a.name>b.name){return 1};

}
cP.getFullCompaniesList=function(){
	var tempCompanies=new Array();
		for(var cpt=0;cpt<this.companies.length;cpt++){
			tempCompanies.push(this.companies[cpt]);
		}
	tempCompanies.sort(cP.sortCompaniesByName);
	return tempCompanies;
}
cP.searchCompanies=function(value, isFromSubmit){
	value = parseInputString(value);
	
	var results = new Array();
	for (var i = 0; i < 6; i++)
		results[i] = new Array();
	
	var count = 0;
	for (i = 0; i < companyList.companies.length; i++) {
		var companyInfo = companyList.companies[i];
		if (this.equalsMatch(value, companyInfo.code)) {
			results[0].push(companyInfo);
			continue;
		}
		
		if (this.wordMatch(value, companyInfo.cleanName) || this.equalsMatch(value, companyInfo.text)) {
			results[1].push(companyInfo);
			continue;
		}

		count--;
		if (count > nbresults) break;
	}

	if (isFromSubmit == true && count == 0 && value.length > 5) {
		results[5] = this.findSoundex(value);
	}
	
	// Combine results in search order, avoiding duplicated.
	var combinedResults = new Array();
	for (i = 0; i < 6; i++) {
		var subResults = results[i];
		for (var j = 0; j < subResults.length; j++) {
			var companyInfo = subResults[j];
			for (var k = 0; k < combinedResults.length; k++)
				if (companyInfo.code == combinedResults[k].code) break;
			if (k == combinedResults.length) // Not found.
				combinedResults.push(companyInfo);
		}
	}
	
	return combinedResults;
}
cP.equalsMatch=function(value, potentialMatch) {
	return value == parseInputString(potentialMatch);
}
cP.wordMatch=function(value, potentialMatch) {
	if (! potentialMatch) return;
	potentialMatch = parseInputString(potentialMatch);
	var re = new RegExp("\\b" + value);
	return potentialMatch.match(re);
}
cP.prefixMatch=function(value, potentialMatch) {
	if (! potentialMatch) return;
	potentialMatch = parseInputString(potentialMatch);
	return value == potentialMatch.substring(0, value.length);
}
cP.findSoundex=function(value){
	value = parseInputString(value);
	if (value.length <= 4) return;

	var results = new Array();
	for (var i = 0; i < this.companies.length; i++){
		var companyInfo = this.companies[i]; 
		if (companyInfo.cleanName.substring(0,1) == value.substring(0, 1)) {
			var name = parseInputString(companyInfo.cleanName.substring(0, value.length));
			if (name.soundex() == value.soundex())
				results.push(companyInfo);
		}
	}
	
	return results;
}

function setCompanyInfo(ac,n,err){
	this.code=ac;
	this.name=n;
	this.cleanName=parseInputString(n);
	this.value=ac;
	this.text=null;
	this.errMsg=err;
}

var aP=setCompanyInfo.prototype;
aP.getCode=function(){return this.code;}
aP.setText=function(){
	this.text=this.name;
//	this.text=this.text+" ("+this.code+")"; // IMPORTANT
	return this.text;
}
aP.getValue=function(){return this.name;}
aP.getName=function(){return this.name;}
aP.getCleanName=function(){return this.cleanName;}

function searchCompanies(value, isFromSubmit){
	return companyList.searchCompanies(value, isFromSubmit);
}
function getAllCompaniesList(){
	var resultCompaniesList = companyList.getFullCompaniesList();
	return	resultCompaniesList;
}

// Debug helper code.
var cldbg = "";
function dd(text) { // good here
	cldbg = cldbg + text + "\n";
}
	
/*****************************************************************************************************************/

//
// Declare global variables for the companyInfo list.
//
var nbresults;
var companyList = null; // good here
var list = null;

function initHomeCompanyList() {
	try {
		// Initialize companyInfo list global variables.
		nbresults = 1000;
		companyList = new CompanyList();
		list = new ListBox();

		list.maxLength = nbresults;
		list.setSearchHandler(searchCompanies);
		list.setFullListHandler(getAllCompaniesList);
//		list.registerCodeInput("keyWords", "origin1");
//		list.registerNextFocusField("keyWords", "dest1");
	} catch (err) {
		logError(err, "something@initHomeCompanyList");
	}
}

function initHomePage() {
	try {
		initHomeCompanyList();
	} catch(err) {
		logError(err, "rolloverhome@initHomePage");
	}
}
