var ACTIVE_CACHE_AUTO_COMPL = true;
var ACTIVE_ELEMENT_BGCOLOR_AUTO_COMPL = "#D8D8D8";
var WIDTH_COEF_AUTO_COMPL = 1;
var HEIGHT_MAX_AUTO_COMPL = "100px";


var verifBrowserAutoCompl = (document.all)? true : false;
var overDivAutoCompl = false;

function initAutoCompl(oInput,filePhp) {
	oInput = $AutoCompl(oInput);
	
	oInput.setAttribute('file',filePhp);
	
	oInput.onkeyup = function (event) {
		if (!event)	event = window.event;
		activeEventAutoCompl(this,event);
	}
	
	oInput.onblur = function () {
		removeDivAutoCompl();
	}
	//oInput.setAttribute('autocomplete','off');
}

function activeEventAutoCompl(oInput,evt) {
	oInput = $AutoCompl(oInput);
	
	if(trimAutoCompl(oInput.value) == "") {
		removeDivAutoCompl();
		return;
	}
	if(evt.keyCode == 13) { // entree
		optcurr = getActivOptAutoCompl();
		if(optcurr) {
			setInputValueAutoCompl(optcurr);
		}
		else {
			sendKeyDownAutoCompl(oInput);
		}
		return;	
	}
	else if(evt.keyCode == 27) { // espace
		removeDivAutoCompl();
		return;
	}
	else if(evt.keyCode == 8) { // backspace
		//return;	
	}
	else if(evt.keyCode == 46) { // suppr
		return;	
	}
	else if(evt.keyCode == 16 || evt.keyCode == 17  || evt.keyCode == 18) { // maj - ctrl - alt
		return;	
	}
	else if(evt.keyCode == 37) { // gauche
		return;	 
	}
	else if(evt.keyCode == 38) { // haut
		acitveOptionAutoCompl('haut',oInput);
		return;	 
	}
	else if(evt.keyCode == 39) { // droite
		return;	 
	}else if(evt.keyCode == 40) { // bas
		acitveOptionAutoCompl('bas',oInput);
		return;	
	}
	
	clearTimeout(timeout_autoCompl);
	timeout_autoCompl = setTimeout(function(){sendRequestAutoCompl(oInput);},80);

}

function setParamAutoCompl(oInput,strParam) {
	$AutoCompl(oInput).setAttribute('otherParam',strParam);
}

function setKeyDownAutoCompl(oInput,strParam) {
	$AutoCompl(oInput).setAttribute('event_down',strParam);
}


function removeDivAutoCompl() {
	if(overDivAutoCompl && verifBrowserAutoCompl)return;
	if($AutoCompl('divAutoComplete')) {
		$AutoCompl('divAutoComplete').parentNode.removeChild($AutoCompl('divAutoComplete'));
	}
}



function acitveOptionAutoCompl(sens) {
	var optActif = null;
	if($AutoCompl('divAutoComplete')) {
		optcurr = getActivOptAutoCompl();
		if(optcurr) {
			if(sens == "bas") {
				if(optcurr.nextSibling && optcurr.nextSibling.tagName.toString().toUpperCase() == 'DIV') {
					optActif = colorieOptActivAutoCompl(optcurr.nextSibling);
				}
			}else if(sens == "haut") {
				if(optcurr.previousSibling && optcurr.previousSibling.tagName.toString().toUpperCase() == 'DIV') {
					optActif = colorieOptActivAutoCompl(optcurr.previousSibling);
				}else {
					removeDivAutoCompl();
				}
			}
		}else {
			if($AutoCompl('divAutoComplete')) {
				if($AutoCompl('divAutoComplete').firstChild && $AutoCompl('divAutoComplete').firstChild.tagName.toString().toUpperCase() == 'DIV') {
					optActif = colorieOptActivAutoCompl($AutoCompl('divAutoComplete').firstChild);
				}
			}
		}
		if(optActif) {
			$AutoCompl('divAutoComplete').scrollTo(0,optActif.offsetTop);
		}

	}else {
		if(arguments[1]) {
			sendRequestAutoCompl(arguments[1]);
		}
	}
}


function colorieOptActivAutoCompl(oDiv) {
	if($AutoCompl('divAutoComplete')) {
		listDiv = $AutoCompl('divAutoComplete').getElementsByTagName('div');
		for(var iList = 0 ; iList < listDiv.length; iList++) {
			listDiv[iList].setAttribute('active','false');
			listDiv[iList].style.background = "none";
			listDiv[iList].style.whiteSpace = "nowrap";
		}
		oDiv = $AutoCompl(oDiv);
		if(oDiv) {
			oDiv.setAttribute('active','true');
			oDiv.style.backgroundColor = ACTIVE_ELEMENT_BGCOLOR_AUTO_COMPL;
			oDiv.style.whiteSpace = "";
		}
	}
	return oDiv;
}


function getActivOptAutoCompl() {
	if($AutoCompl('divAutoComplete')) {
		listDiv = $AutoCompl('divAutoComplete').getElementsByTagName('div');
		for(var iList = 0 ; iList < listDiv.length; iList++) {
			if(listDiv[iList].getAttribute('active',false) == 'true') {
				return listDiv[iList];
			}
		}
		return false;
	}else {
		return false;
	}
}

function getXhrReturnAutoCompl() {
  if(window.XMLHttpRequest) //
  	var xhrautoCompl = new XMLHttpRequest();
  else if(window.ActiveXObject) {
		try {
			var xhrautoCompl = new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e) {
			var xhrautoCompl = new ActiveXObject("Microsoft.XMLHTTP");
		}
  }else {
    xhrautoCompl = false;
  }
  return xhrautoCompl;
}


var LIST_OLD_RESULT_AUTO_COMPL = new Array();
var xhrAutoCompl = null;
var timeout_autoCompl = setTimeout('',100);
function sendRequestAutoCompl(oInput) {
	oInput = $AutoCompl(oInput);
	debRech = oInput.value;
	if(debRech == "") {
		return;
	}
	if(ACTIVE_CACHE_AUTO_COMPL) {
		for(var iOld = 0; iOld < LIST_OLD_RESULT_AUTO_COMPL.length; iOld++) {
			if(LIST_OLD_RESULT_AUTO_COMPL[iOld][0] == oInput.id) {
				if(LIST_OLD_RESULT_AUTO_COMPL[iOld][1] == oInput.getAttribute('otherParam',false)) {			
					if(LIST_OLD_RESULT_AUTO_COMPL[iOld][2] == debRech) {
						buildOptAutoCompl(LIST_OLD_RESULT_AUTO_COMPL[iOld][3],oInput);
						return;
					}
				}
			}
		}
	}
	if(xhrAutoCompl != null) {
		return;
	}
	xhrAutoCompl = getXhrReturnAutoCompl();
  xhrAutoCompl.onreadystatechange = function(){
    if(xhrAutoCompl.readyState == 4 && xhrAutoCompl.status == 200) {
	    strRep = xhrAutoCompl.responseText; 
	    
	    buildOptAutoCompl(strRep,oInput);
	    xhrAutoCompl = null;
    }
  }
	randParam = '&rand='+Math.random();
  otherParam = oInput.getAttribute('otherParam',false);

 	filePhp = oInput.getAttribute('file',false);
 	param = "query="+debRech+"&"+otherParam+randParam;
  
  xhrAutoCompl.open("POST",filePhp,true);  
	xhrAutoCompl.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhrAutoCompl.send(param);
}


function buildOptAutoCompl(strRep,oInput) {
	var oRep = evalStrAutoCompl(strRep);
	if(oRep) {
		
		aToPush = new Array(oInput.id,oInput.getAttribute('otherParam',false),debRech,strRep);
		LIST_OLD_RESULT_AUTO_COMPL.push(aToPush);
		
		overDivAutoCompl = false;
		removeDivAutoCompl();
		
		divLeft = getOffsetAutoCompl(oInput,'offsetLeft');
		divTop = getOffsetAutoCompl(oInput,'offsetTop')+oInput.offsetHeight;
		
		bigDiv = newEltautoCompl('div',document.body,true);
		bigDiv.id = "divAutoComplete";
		
		if(verifBrowserAutoCompl) {
			bigDiv.onmouseover = function() {
				overDivAutoCompl = true;
			}
			bigDiv.onscroll = function () {
				oInput.focus();
			}
			bigDiv.onmouseout = function() {
				overDivAutoCompl = false;			
			}
		}
		
		if(!verifBrowserAutoCompl) {
			bigDiv.style.display = "none";
		}
		toTopAutoCompl(bigDiv);
		
		bigDiv.style.left = divLeft;
		bigDiv.style.top = divTop;

		debRech = debRech.replace(/[AÀÁÂÃÄÅaàáâãäå]/,"[aàáâãäå]");
		debRech = debRech.replace(/[EÈÉÊËeèéêë]/,"[eèéêë]");
		debRech = debRech.replace(/[IÌÍÎÏiìíîï]/,"[iìíîï]");
		debRech = debRech.replace(/[OÒÓÔÕÖoðòóôõö]/,"[oðòóôõö]");
		debRech = debRech.replace(/[UÙÚÛÜuùúûü]/,"[uùúûü]");
		debRech = debRech.replace(/[YÝyýÿ]/,"[yýÿ]");
		debRech = debRech.replace(/[CÇcç]/,"[cç]");
		
		myRe = new RegExp ('('+debRech+')','ig');
		var iNumChoix = 0;
		for(var item in oRep) {
			if(oRep[item]) {
				//if(myRe.test(oRep[item].name)) {
					textDiv = trimAutoCompl(oRep[item].name);
					idDiv = trimAutoCompl(oRep[item].idx);
					
					divElt = newEltautoCompl('div',bigDiv,true);
					divElt.setAttribute('textvalue',textDiv);
					divElt.setAttribute('textId',idDiv);

					divElt.setAttribute('inputId',oInput.id);
					
					divElt.style.whiteSpace = "nowrap";
					
					aj = textDiv.replace(myRe,"<span>$1</span>");
					divElt.innerHTML = aj;
					
					iNumChoix++;
				//}
			}
		}
		
		
		if(bigDiv.childNodes.length == 0) {
			removeDivAutoCompl();
			//oInput.value = "";
			return;
		}
		
		bigDiv.style.width = oInput.offsetWidth*WIDTH_COEF_AUTO_COMPL;
		
		if(iNumChoix > 6) {
			bigDiv.style.height = HEIGHT_MAX_AUTO_COMPL;
			bigDiv.style.overflowY = "auto";
			bigDiv.style.overflowX = "hidden";
		}else {
			bigDiv.style.height = "";
			bigDiv.style.overflow = "hidden";
		}
		
		bigDiv.style.display = "block";
		
		
		if(verifBrowserAutoCompl) {
			divFrame = newEltautoCompl('iframe',bigDiv,true);
		}
		animDivAutoCompl('divAutoComplete',oInput);
	}else {
		removeDivAutoCompl();
		//oInput.value = "";
	}
}

function evalStrAutoCompl(str) {
	try {
		eval('var oRep = '+str);
	}catch(e) {
		var oRep = false;
		if(/error|warning/i.test(str)) {
			affAl = str.replace(/<br {0,}\/{0,}>/g,'\n');
			affAl = str.replace(/&quot;/g,'\'');
			affAl = affAl.replace(/<[^<>]{1,}>|<\/[^<>]{1,}>/ig,' ');
		}else if (/[a-z]{1,}\r/.test(str)) {
			//
		}
	}
	if(oRep && oRep.err && oRep.err != "") {
		oRep = false;
	}
	return oRep;
}

function getOffsetAutoCompl(element,attr){
	element = $AutoCompl(element);
	var offset=0;
	while(element) {
		offset+=element[attr];
		element=element.offsetParent
  }
	return offset;
}

function newEltautoCompl(tag,parentElt,bool) {
	if(bool) {
		var newElement = document.createElement(tag);
	}else {
		var newElement = document.createTextNode(tag);
	}
	$AutoCompl(parentElt).appendChild(newElement);
	return newElement;
}

function toTopAutoCompl(obj) {
	var listDiv = document.getElementsByTagName("div");
	var zIndexMax = 0;
	for (var i = 0; i < listDiv.length; i++) {
		if(parseInt(listDiv[i].style.zIndex) > parseInt(zIndexMax)) {
			zIndexMax = parseInt(listDiv[i].style.zIndex);
		}
	}	
	$AutoCompl(obj).style.zIndex = parseInt(zIndexMax) + 1;
}

function $AutoCompl(obj) {
	return $(obj);
	if(document.getElementById(obj)) {
		return document.getElementById(obj);
	}else if(typeof(obj) == 'object'){
			return obj;
	}else {
		return false;
	}
}

function getStyleAutoCompl(element, property) {
	if (element.style[property]) {
		return element.style[property]
	} else if (element.currentStyle) {
		return element.currentStyle[property]
	} else if (document.defaultView && document.defaultView.getComputedStyle) {
		var style = document.defaultView.getComputedStyle(element, null)
		return style.getPropertyValue(property)
	} else {
		return null;
	}
}

function animDivAutoCompl(divObj) {
	listDiv = $AutoCompl(divObj).getElementsByTagName('div');
	for(var iList = 0 ; iList < listDiv.length; iList++) {
		with(listDiv[iList].style) {
			cursor = "default";
		}
		listDiv[iList].onmouseover = function() {
			colorieOptActivAutoCompl(this);
		}
		listDiv[iList].onmousedown = function() {
			setInputValueAutoCompl(this);
		}		
	}
}

function sendKeyDownAutoCompl(inputId) {
	if($AutoCompl(inputId)) {
		event_down = $AutoCompl(inputId).getAttribute('event_down',false);
		try {
			eval(event_down);
		}catch (e) {
			//	
		}
	}
}

function trimAutoCompl(str) {
	str = str.replace(/^[\W]{0,}|[\W]{0,}$/g,'');
	return str;
}

function setInputValueAutoCompl(complOpt) {
	complOpt = $AutoCompl(complOpt);
	textvalue = complOpt.getAttribute('textvalue',false);
	textId = complOpt.getAttribute('textId',false);
	
	textvalue = trimAutoCompl(textvalue);
	inputId = $AutoCompl(complOpt.getAttribute('inputId',false));
	if(inputId) {
		inputId.setAttribute('textId',textId);
		inputId.value = textvalue;
		inputId.focus();
		sendKeyDownAutoCompl(inputId);
	}
	overDivAutoCompl = false;
	removeDivAutoCompl();
}


function listeResultZone(){
	
		idReceiver = 'result_ctrlResearch';						
		var dept = document.getElementById("ctrlResearch_listdept");
		var iddep = dept.options[dept.options.selectedIndex].value;
		
		var inputSrch = document.getElementById("result_ctrlResearch");				
		var txtSrch = inputSrch.value;
		forrmm = "";
		
		listInput = $('ctrlResearchService').getElementsByTagName('input');
		for(ilo=0; ilo < listInput.length; ilo++) {
			if(listInput[ilo].type == "radio" && listInput[ilo].checked) {
				forrmm = listInput[ilo].value;
				break;
			}
		}
		
		param_select = "act=findzone";		
		param_select += "&iddep="+iddep;
		param_select += "&param_select="+forrmm;
				
		if(txtSrch != "") {			
			initAutoCompl(idReceiver,'ajax.inc.php');
			setParamAutoCompl(idReceiver,param_select);
			setKeyDownAutoCompl(idReceiver,"$('valzonegeo').value=$('result_ctrlResearch').getAttribute('textId',false);")
		}
}

function zoomZone(param){
	var aparam = param.split("_");
	
	var zone = aparam[0];
	var idx = aparam[1];
	
	parCadre = "zone="+zone+"&idx="+idx+"&act=zoomzone";
	gMap.tool.setMode(GSMAP_ZOOMZONE) ;
	gMap.sendX_Load(parCadre) ;	
	gMap.tool.setMode(GSMAP_PAN) ;
}

function clickRechScte() {
	rechercheSociete(document.getElementById('nom_societeLocal').getAttribute('textId',false));
}

