/*                                                        */
/*  Tree Tools Informática Ltda                           */
/*  Funções para tratamento de combos                     */
/*                                                        */

function ComboControl(cb){
	return new ComboObj(cb);
}
function ComboObj(aCombo){
	if (!aCombo|| !aCombo.type || (!/^select/.test(aCombo.type))) {alert('Combo box não encontrado');return;};
	
	this.combo=aCombo;
	this.selectByValue=_COSelectByValue;
	this.selectByValueEspecial=_COSelectByValueEspecial;
	this.selectByText=_COSelectByText;
	this.select=_COSelect;
	this.getSelectedIndex=_COGetSelectedIndex;
	this.insert=_COInsert;
	this.insertByArray=_COInsertByArray;
	this.insertComboByArray=_COInsertComboByArray;
	this.isEmpty=_COIsEmpty;
	this.getSize=_COGetSize;
	this.clear=_COClear;
}
function _COGetSize(){
	return this.combo.length;
}
function _COIsEmpty(){
	return this.getSize()==0;
}
function _COSelectByValue(vl){
	if(this.isEmpty())return -1;
	var c=this.combo;
	for(var i=0;i<this.getSize();i++)
		if(c.options[i].value==vl){c.selectedIndex= i;return i;}
	

	return -1;
}
function _COSelectByValueEspecial(vl,tipo){
	if(this.isEmpty())return -1;
	var c=this.combo;
	for(var i=0;i<this.getSize();i++)
	{
		var texto = trim(c.options[i].value);
		if(texto.length > 0)
		{
			if (tipo == "1")
				if(trim(texto.substring(0,texto.indexOf("#")))==vl){c.selectedIndex= i;return i;}
				
			if (tipo == "2")
				if(trim(texto.substring(texto.indexOf("#")+1,texto.length))==vl){c.selectedIndex= i;return i;}
		}
	}
}

function _COSelectByText(txt){
	if(this.isEmpty())return -1;
	var c=this.combo;
	for(var i=0;i<this.getSize();i++)
		if(c.options[i].text==txt){c.selectedIndex= i;return i;}
	return -1;
}
function _COSelect(ind){
	this.combo.selectedIndex=ind;
}
function _COGetSelectedIndex(){
	return this.combo.selectedIndex;
}
function _COInsertByArray(itens){
	var c=this.combo,v,t;
	this.clear();
	for(var i=0;i<itens.length;i++){
		if(typeof itens[i]=="string")v=t=itens[i];
		else{v=itens[i][0];t=itens[i][1];}
		this.insert(v,t);
	}
	c.selectedIndex=0;
}
function _COClear(){
	var c=this.combo,i=c.length;
	for (i=c.length;i>=0;i--)
		c.options[i]=null;
}
function _COInsert(vlr,txt){
	var c=this.combo;
	if (!vlr&&!txt) return;
	if (!txt)txt=vlr;
	if (trim(txt)==''&&trim(vlr)=='')return;
	c.options[c.length]=new Option(txt, vlr, false, false);
}
function _COInsertComboByArray(cbo,itens){
	var i = 0;
	if(!cbo||!itens)return;
	if(cbo.combo.options[0].value=="")i=-1;
	var ind = cbo.getSelectedIndex();
	if(cbo.isEmpty()||(i==-1&&ind==0))return;
	var pos = i + cbo.getSelectedIndex();
	if(pos>(itens.length-1)||(pos<0))return;
	this.insertByArray(itens[pos]);
}


