	/* 
	------------------------------------------------------------------------------------------------
							cbxComboBox - a DHTML combobox with searcheable items
	Copyright (C) 2006  Paolo Scuderi

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.   

	If you want to use it in any software (commercial or not) please,
	inform me by email at scrivi@paoloscuderi.it
	------------------------------------------------------------------------------------------------
	*/
	
	var cbxBuffer, cbxTmBuffer, cbxStartIdx, cbxTmStartIdx;
	
	function cbxCreaCombo(nome,matValori,selectedValue,larghezza,larghezzaMenu)
	{
		var s,v,intIdx, strVis, strVal, strDes;
		var maxLen=0;
		if (typeof larghezza=='undefined') larghezza="100";
		if (typeof larghezzaMenu=='undefined') larghezzaMenu=larghezza;
		if (!isNaN(larghezza)) larghezza+='px';
		if (!isNaN(larghezzaMenu)) larghezzaMenu+='px';
		v=''; s=''; intIdx=-1;
		for (i=0;i<matValori.length;i++)
			{
				strVis=matValori[i][1];
				if(typeof strVis=='undefined') strVis=matValori[i][1];
				strVal=matValori[i][0];
				strDes=matValori[i][1];
				if(strDes.length>maxLen) maxLen=strDes.length;
				if (strVal.toString().toLowerCase() == selectedValue.toString().toLowerCase()) intIdx=i;
				v+='<div style="width:100%;" class="selectboxoption" id="cbxOpt_' + nome + '_' + i + '" onmouseover="cbxOver(this)" onclick="cbxClick(this)" value="'+ strVal + '" des="' + strDes + '">' + strVis + '</div>\n';
			}
		if (maxLen * 6 > parseInt(larghezzaMenu.replace('px','').replace('%',''))) larghezzaMenu=(maxLen * 6) + 'px';
		s ='<div style="width:' + larghezza + ';" id="cbx_' + nome + '" class="selectbox" onclick="cbxMostraNascondiCombo(\'' + nome + '\');" onkeydown="cbxTxtOnKeyDown(\'' + nome + '\',event);" selectedindex="' + intIdx + '" itemscount="' + matValori.length + '" >\n';
		s+='	<table border="0" cellpadding="0" cellspacing="0" class="myComboBoxTable">\n';
		s+='		<tr><td><input autocomplete="off" type="text" style="width:' + larghezza + ';" name="' + nome + '_cbxDes" readonly id="cbxTxt_' + nome + '" class="selectboxinput"><input autocomplete="off" type="hidden" name="' + nome + '" id="cbxVal_' + nome + '" value=""></td>\n';
		s+='			<td width="5" align="center" valign="middle" style="BACKGROUND-COLOR: #d8d8cf"><img src="xparrow.gif" border="0" align="absMiddle"></td></tr>\n';
		s+='	</table>';
		s+='</div>';
		s+='<div style="width:' + larghezzaMenu + ';" class="selectboxoptionlist" id="cbxPnl_' + nome + '" onkeydown="cbxOnKeyDown(\'' + nome + '\',event);" onkeyup="cbxOnKeyUp(\'' + nome + '\');" style="DISPLAY: none">\n';
		//s+='<div style="width:' + larghezzaMenu + ';" class="selectboxintestazione" id="cbxInte_' + nome + '" >' + maxLen + '</div>\n';
		s+=v
		//s+='<div style="width:' + larghezzaMenu + ';" class="selectboxcoda" id="cbxCoda_' + nome + '" ></div>\n';
		s+='</div>';
		document.write(s);
		initComboBox(nome);
	}
	//---------------------------------------------------------------------------------------------------------------//
	//----------------- funzione di inizializzazione della singola combo e delle variabili globali ------------------//
	//---------------------------------------------------------------------------------------------------------------//
	function initComboBox(id)
	{
		var cbMain;
		var cb, conto,selIdx;
		cbMain=document.getElementById('cbx_' + id)  ;
		cb=document.getElementById('cbxTxt_' + id)  ;
		if(!cbMain.getAttribute('selectedindex')) {cbMain.setAttribute('selectedindex','-1')} ;
		if(!cbMain.getAttribute('currentindex')) {cbMain.setAttribute('currentindex','-1')} ;
		if(!cbMain.getAttribute('selectedvalue')) {cbMain.setAttribute('selectedvalue','-1')} ;
		if(!cbMain.getAttribute('itemscount')) {cbMain.setAttribute('itemscount','-1')} ;
		// se l'attrivuto itemscount non è impostato, lo calcolo io........//
		conto=cbMain.getAttribute('itemscount');
		selIdx=cbMain.getAttribute('selectedindex');
		cbxBuffer='';
		cbxStartIdx=0;
		if (conto== -1) 
			{
				var i;
				try
					{
						for (i=0;i<10000;i++) { elm=document.getElementById('cbxOpt_' + id + '_' + i).id  ;}
					}
				catch(ee)
					{ 	cbMain.setAttribute('itemscount',i) ;}
			}
		setTimeout('cbxImpostaValore(\'' + id + '\',' + selIdx + ',false)',10);
	}
	//---------------------------------------------------------------------------------------------------------------//
	//----------------- funzione che mostra e nasconde la combobox --------------------------------------------------//
	//---------------------------------------------------------------------------------------------------------------//
	function cbxMostraNascondiCombo(id,impostaValore) {
		var elm,idx;
		if(typeof impostaValore=='undefined') impostaValore=true;
		elm = document.getElementById('cbxPnl_' + id);
			if (elm){
				if (elm.style.display == 'none'){
				elm.style.display = 'block';
				elm.focus();				
			}else{
				elm.style.display = 'none';
				elm = document.getElementById('cbx_' + id);
				idx = elm.getAttribute('selectedindex');
				cbxImpostaValore(id,idx,false)
			}
		}
	}
	
	
	//---------------------------------------------------------------------------------------------------------------//
	//--------------- illumina l'elemento specificato e imposta il currentindex -------------------------------------//
	//---------------------------------------------------------------------------------------------------------------//
	function cbxAttivaElem(Id,elmId,scroll){
		var oldId, elm;
		oldId=document.getElementById('cbx_' + Id).getAttribute('currentindex');
		if(oldId>=0) cbxDisattivaElem(Id,oldId);
		try
		{
		elm = document.getElementById('cbxOpt_' + Id + '_' + elmId);
		elm.className += "_active";
		if(scroll) elm.scrollIntoView();
		document.getElementById('cbx_' + Id).setAttribute('currentindex',elmId);
		}
		catch(e)
		{ }
	}
	
    //---------------------------------------------------------------------------------------------------------------//
    //----------------- disattiva l'elemento specificato ------------------------------------------------------------//
    //---------------------------------------------------------------------------------------------------------------//
	function cbxDisattivaElem(Id,elmId){
		var elm;
		elm = document.getElementById('cbxOpt_' + Id + '_' + elmId);
		elm.className = elm.className.replace("_active","")
	}
	
	
	//---------------------------------------------------------------------------------------------------------------//
	//----------------- imposta il valore della combo e le proprietà con i valori dell'elemento specificato ---------//
	//---------------------------------------------------------------------------------------------------------------//
	function cbxImpostaValore(Id,elmId,nascondi){
		var val;
		var elm;
		if(elmId==-1) return;
		if(typeof nascondi=='undefined') nascondi=true;
		elm = document.getElementById('cbxOpt_' + Id + '_' + elmId);
		val=elm.getAttribute('value');
		document.getElementById('cbxVal_' + Id).value = val;
		document.getElementById('cbxTxt_' + Id).value = elm.getAttribute('des');
		elm = document.getElementById('cbx_' + Id);
		elm.setAttribute('selectedindex',elmId);
		elm.setAttribute('selectedvalue',val);
		if(nascondi) cbxMostraNascondiCombo(Id,true);
	}
	
    //---------------------------------------------------------------------------------------------------------------//
    //------------- Avvia la ricerca delle parole nel buffer e cancella il buffer allo scadere del timeout-----------//
    //---------------------------------------------------------------------------------------------------------------//
	function cbxCercaDaBuffer(Id)
	{	
		var idx;
		clearTimeout(cbxTmStartIdx);
		idx=cbxCercaParola(Id,cbxBuffer,cbxStartIdx)
		cbxStartIdx=parseInt(idx) + 1;
		if(idx>=0) {cbxAttivaElem(Id,idx,true); } ;		
		document.getElementById('cbxTxt_' + Id).value='(' + cbxBuffer + ')...';
		if (isNaN(cbxStartIdx)) {cbxStartIdx=0};
		cbxBuffer='';
		cbxTmStartIdx=setTimeout('function(){cbxStartIdx=0;}',2000); // <<<<---- dopo 2 secondi cancello il buffer dell'indice di ricerca. -----//
	}
	
	
	//---------------------------------------------------------------------------------------------------------------//
	//------------ funzione di ricerca voci tramite Iniziale o Parole iniziale. -------------------------------------//
	//---------------------------------------------------------------------------------------------------------------//
	function cbxCercaParola(Id,str,startIdx)
	{
		var totIdx, val ;
		totIdx=document.getElementById('cbx_' + Id).getAttribute('itemscount');
		totIdx=parseInt(totIdx);
		for (i=parseInt(startIdx) ;i<totIdx;i++)
			{
				try
					{
						opt=document.getElementById('cbxOpt_' + Id + '_' + i)
						val=opt.innerHTML;
						if (val.toLowerCase().indexOf(str.toLowerCase())>=0) {return i;}	
					}
				catch(ex)
					{i=totIdx; }
			}
	}
	
	//---------------------------------------------------------------------------------------------------------------//
	//--------------------        gestione degli eventi          ----------------------------------------------------//
	//---------------------------------------------------------------------------------------------------------------//	
	function cbxOnKeyUp(Id,e)
	{
		var idx,ch;
		e = e || window.event;
		ch = e.which || e.keyCode;
		if ( (ch<65 || ch>90) && (ch != 32)) {return false;}
		clearTimeout(cbxTmBuffer);
		cbxBuffer=cbxBuffer + String.fromCharCode(ch);
		cbxTmBuffer=setTimeout('cbxCercaDaBuffer(\'' + Id + '\')',300);
		
	}
	
	function cbxOnKeyDown(Id,e)
	{
		var prev=0, next=0;
		var idx = document.getElementById('cbx_' + Id).getAttribute('currentindex');
		var tot = document.getElementById('cbx_' + Id).getAttribute('itemscount');
		var ch;
		e = e || window.event;
		ch = e.which || e.keyCode;
		if (ch>65 && ch<90) {return false;}
		idx=parseInt(idx);
		tot=parseInt(tot);
		prev=idx - 1;
		next=idx + 1;
		if(prev<0) prev=0;
		if(next>tot-1) next=tot -1;
		switch(ch)
		{
			case 38: cbxAttivaElem(Id,prev,true); cbxCancel(e); return;		/*- Freccia Su  */
			case 40: cbxAttivaElem(Id,next,true); cbxCancel(e); return;		/*- Freccia Giu */
			case 36: cbxAttivaElem(Id,0,true); cbxCancel(e); return;			/*- inizio      */
			case 35: cbxAttivaElem(Id,tot -1,true); cbxCancel(e); return;		/*- fine        */ 
			case 13: cbxImpostaValore(Id,idx); return		/*- invio */
			case 9: cbxImpostaValore(Id,idx); return		/*- TAB */
			
		}
		
	}
	
	function cbxTxtOnKeyDown(Id,e)
	{
		var ch;
		e = e || window.event;
		ch = e.which || e.keyCode;
		if (ch!=115 && ch!=40) {return false;}
		switch(ch)
		{
			case 115: cbxMostraNascondiCombo(Id,false); cbxCancel(e); return;		/*- F4  */
			case 40: cbxMostraNascondiCombo(Id,false); cbxCancel(e); return;		/*- Freccia Giu */
			
			
		}
	}
	function cbxCancel(e)
	{
		e.returnValue = false;
	}
	function cbxOver(obj)
	{
		var nCbx, nOpt, idOpt;
		idOpt=obj.id.substring(7)  ;
		cbxAttivaElem(idOpt.split('_')[0],idOpt.split('_')[1]);
	}
	function cbxOut(obj)
	{
		var nCbx, nOpt, idOpt;
		idOpt=obj.id.substring(7)  ;
		cbxDisattivaElem(idOpt.split('_')[0],idOpt.split('_')[1]);
	}
	function cbxClick(obj)
	{
		var nCbx, nOpt, idOpt;
		idOpt=obj.id.substring(7)  ;
		cbxImpostaValore(idOpt.split('_')[0],idOpt.split('_')[1]);
	}
	
	//---------------------------------------------------------------------------------------------------------------//
    //-------------                             Crea un array multidimensionale                           -----------//
    //---------------------------------------------------------------------------------------------------------------//
	function cbxArray(iRowIdx,iColIdx) 
		{ 
		var i; 
		var j; 
		var a = new Array(iRowIdx); 
		for (i=0; i <= iRowIdx; i++) 
			{ 
				a[i] = new Array(iColIdx); 
				for (j=0; j <= iColIdx; j++) 
				{ 
					a[i][j] = ""; 
				} 
			} 
		return(a); 
		} 
