var agent  = navigator.userAgent.toLowerCase();
var browser_ie = (agent.indexOf("msie") != -1);
Global_run_event_hook = true;
Global_combo_array    = new Array();

Array.prototype.remove=function(dx)
{ 
    if(isNaN(dx)||dx>this.length){self.status='Array_remove:invalid request-'+dx;return false}
    for(var i=0,n=0;i<this.length;i++){  
        if(this[i]!=this[dx]){
            this[n++]=this[i]
        }
    }
    this.length-=1
}

function ComboBox_make(){
    var tmp = $(this.but);
   	// tmp.onfocus = function () { this.blur(); };
	tmp.onclick = new Function ("", this.name + ".toggle()");
	var inp = $(this.inp);
	// inp.onfocus = function () { this.name + ".inp_focus()"};
	inp.onclick = new Function ("", this.name + ".toggle()");
}

function ComboBox_choose(realval,txtval){
    this.value         = realval;
//    var samstring = this.name+".view.childNodes[0].value='"+txtval+"'"
//    window.setTimeout(samstring,1)
   this.valcon.value  = String(txtval).trim() ; //+"|"; // String(nv[0]).trim() ; // '123';// txtval; // realval;
   this.valcon.className = "wide";
   // this.valcon.nodeValue = txtval;
}

function ComboBox_mouseDown(e){
    var obj,len,el,i;
    el = e.target ? e.target : e.srcElement;
    while (el.nodeType != 1) el = el.parentNode;
    var elcl = el.className;
    if(elcl.indexOf("combo-")!=0){
        len=Global_combo_array.length
        for(i=0;i<len;i++){
            curobj = Global_combo_array[i]
            if(curobj.opslist){
                curobj.opslist.style.display='none'
            }
        }
    }
}

function ComboBox_handleKey(e){
    var key,obj,eobj,el,strname;
    eobj = e;
    key  = eobj.keyCode;
    el = e.target ? e.target : e.srcElement;
    while (el.nodeType != 1) el = el.parentNode;
    elcl = el.className
    if(elcl.indexOf("combo-")==0)
    {
        if(elcl.split("-")[1]=="input")
        {
            strname = el.id.split("txt")[0]
            obj = window[strname];
			
            obj.expops.length=0
            obj.update();
            obj.build(obj.expops);
            if(obj.expops.length==1&&obj.expops[0].text=="(No matches)"){}//empty
            else{obj.opslist.style.display='block';}
            obj.value = el.value;
            obj.valcon.value = el.value;
        }
     }
}

function ComboBox_update(){
    var opart,astr,alen,opln,i,boo;
    boo=false;
    opln = this.options.length
    astr = this.txtview.value.toLowerCase();
    alen = astr.length
    if(alen==0){
        for(i=0;i<opln;i++){
            this.expops[this.expops.length]=this.options[i];boo=true;
        }
    }
    else{
        for(i=0;i<opln;i++){
            opart=this.options[i].text.toLowerCase().substring(0,alen)
            if(astr==opart){
                this.expops[this.expops.length]=this.options[i];boo=true;
            }
        }
    }
    if(!boo){this.expops[0]=new ComboBoxItem("(No matches)","")}
}


function ComboBox_remove(index){this.options.remove(index)}

function ComboBox_add(){
    var i,arglen;
    arglen=arguments.length
    for(i=0;i<arglen;i++){this.options[this.options.length]=arguments[i]}
}

function ComboBox_full(data){
var list = data.split(';');
if(list.length>0){
    var arrlen = list.length; //,
//alert("ComboBox_full(): " + arrlen);    
    //    str = '<table class="combo-list-width" cellpadding=0 cellspacing=0>';
    //var strs = new Array(arrlen);
    var txt = String(this.valcon.value).toLowerCase();
    for(var ii=0;ii<arrlen;ii++){
        nv = list[ii].split(',');
        var ln = nv.length;
        if(ln>1)
            this.add(new ComboBoxItem(nv[1],this.cod==0?nv[0]:nv[2]));
        if(String(nv[1]).toLowerCase() == txt)
            this.selected = ii;
//        if(ii> 178) alert("ComboBox_full: " + ii + " " + ln + " " + list[ii])    
    }
    }    
}

function ComboBox_build(arr){
    var str,arrlen
    arrlen=arr.length;
    str = '<table width="100%" class="combo-list-width" cellpadding=0 cellspacing=0>';
    var strs = new Array(arrlen);
    for(var i=0;i<arrlen;i++){
        strs[i] = '<tr>' +
			// '<td id="'+this.inp + '_'+String(i)+ '" class="combo-item" onClick="'+this.name+'.choose(\''+arr[i].value+'\',\''+arr[i].text+'\');'+this.name+'.opslist.style.display=\'none\';"' +
			'<td id="'+this.inp + '_'+String(i)+ '" class="' + (this.selected==i?'combo-hilite':'combo-item')+'" onClick="'+this.name+'.choose(\''+arr[i].value+'\',\''+arr[i].text+'\');'+this.name+'.hide();"' +
			//'onMouseOver="this.className=\'combo-hilite\';" onMouseOut="this.className=\'combo-item\'" >&nbsp;'+arr[i].text+'&nbsp;</td>' +
			// 'onMouseOver="this.className=\'combo-hilite\';" onMouseOut="ComboBox_MouseOut(this,'+this.name+')" >&nbsp;'+arr[i].text+'&nbsp;</td>' +
			// 'onMouseOver="ComboBox_MouseOver(this,'+this.name+');" on_MouseOut="this.className=\'combo-item\'" >'+arr[i].text+'</td>' +
			'onMouseOver="ComboBox_MouseOver(this,'+this.name+');" onMouseOut="ComboBox_MouseOut(this,'+this.name+')" >'+arr[i].text+'</td>' +
			'</tr>';
    }
    str = str + strs.join("") + '</table>'
    
    if(this.opslist){this.view.removeChild(this.opslist);}
    
    this.opslist = document.createElement("DIV")
    this.opslist.innerHTML=str;
    this.opslist.style.display='none';
    this.opslist.className = "combo-list";
    this.opslist.onselectstart=returnFalse;
    this.opslist.onmouseout = new Function ("", this.name + ".MouseOut()");
    this.opslist.onmouseover = new Function ("", this.name + ".MouseOver()");
    this.view.appendChild(this.opslist);    
}

function ComboBox_MouseOut(el,nm){
    var e = $(nm.inp + '_'+String(nm.selected));
    var id = el.id.split('_')[1];
//window.status = "ComboBox_MouseOut: " + el + " " + nm + " " + e.id + " " + nm.selected + "|" + nm.last_sel + ":";    
    nm.last_sel = id;
//window.status += nm.last_sel;
    // nm.selected = "";
    // if(e) e.className = 'combo-item';
}

function ComboBox_MouseOver(el,nm){
    var e = $(nm.inp + '_'+String(nm.selected));
//window.status = 'ComboBox_MouseOver(): ' + nm.inp + '_'+String(nm.selected)+ ": " ;
//console.log('ComboBox_MouseOver(): ' + nm.inp + '_'+String(nm.selected)+ ": ");
    if(e) e.className = 'combo-item';
// window.status = 'ComboBox_MouseOver(): ' + e.id + ' ' + nm.selected;

    el.className='combo-hilite';
    var id = el.id.split('_')[1];
    nm.selected = id;
    nm.last_sel = "-1";
    $(nm.inp).focus();
    //window.status += '|ComboBox_MouseOver: ' + el.id + ' ' + nm.selected;
    
    var top = parseInt(nm.opslist.scrollTop / 18);
    nm.top = top;
    nm.button = top+19;
    //window.status += '| ' + nm.top + ":" + nm.button;
//window.status += "  ComboBox_MouseOver: " + el + " " + nm + " " + e.id + " " + nm.selected+ "|" + nm.last_sel;
    
}

function ComboBox_Show(){
//alert("ComboBox_Show(): " + this.opslist);
    if(this.loading)
    {
        if(!this.opslist)
            this.build(this.options);
        
        if(this.opslist.style.display=="none"){
            this.view.style.zIndex = ++ComboBox.prototype.COMBOBOXZINDEX;
            this.opslist.style.display="block";
            
            var tbl = $(this.tbl);
            // var tbl = $(this.inp);
            this.view.style.width = tbl.offsetWidth + "px";
            var top = calculateOffsetTop(tbl)+tbl.offsetHeight;
	        var left = calculateOffsetLeft(tbl);
	        //var he = get_wh()+getBodyScrollTop();
	        // if(top+h+10>he){top = he - h - 10; left = left + 60;}	

	        this.view.style.left = left+ "px";
	        this.view.style.top  = top + "px";
    	
	        if(this.selected>-1){
	            this.top = this.selected;
	            this.button = this.top + 19;
	            var scroll = this.top * 18;
                this.opslist.scrollTop = scroll;
            }    
	        if(this.frame){
	            this.frame.style.zIndex = ComboBox.prototype.COMBOBOXZINDEX-1;
	            this.frame.style.left = left+ "px";
	            this.frame.style.top  = top + "px";
	            this.frame.style.width = this.opslist.offsetWidth + "px";
	            this.frame.style.height= this.opslist.offsetHeight+ "px";
	            this.frame.style.display="block";
	        }
        }

        $(this.inp).focus();
    }
    else LoadListCountry(this.name);
}

function ComboBox_inp_focus(){
//alert("ComboBox_inp_focus(): " + this.opslist + " " + this.options.length);
    if(this.opslist && this.options.length>0)  this.toggle();
    else LoadListCountry(this.name);
}

function ComboBox_hide(){
if(this.opslist){
    this.opslist.style.display="none";
    if(this.frame) this.frame.style.display="none";
    this.last_sel = "-1";
    }
this.is_mouseout = false;    
}

function ComboBox_toggle(){
// alert("ComboBox_toggle: " + this.opslist + " " + this.options.length);
    // this.last_sel = "";//this.selected;
    clicked();
    if(this.opslist && this.options.length>0){
        if(this.opslist.style.display=="block"){
            this.opslist.style.display="none";
            if(this.frame) this.frame.style.display="none";
        }    
        else this.show();
    }
    else if(this.options.length>0) this.show();
    else LoadListCountry(this.name);
}

function load_Countries(data,sel_obj){
    var curobj;
    var len=Global_combo_array.length
    for(i=0;i<len;i++){
        curobj = Global_combo_array[i];
        curobj.full(data);
        curobj.loading = true;
        if(curobj.name== sel_obj){
            // curobj.full(data);
            curobj.show();
            curobj.setSelected();
        }
    }
}

function loading_Countries(sel_obj){
    var curobj;
    var len=Global_combo_array.length
    for(i=0;i<len;i++){
        curobj = Global_combo_array[i];
        return curobj.loading;
    }
}

function set_loading_Countries(sel_obj){
//alert("set_loading_Countries(): " + sel_obj);
    var curobj;
    var len=Global_combo_array.length
    for(i=0;i<len;i++){
        curobj = Global_combo_array[i];
        curobj.loading = null;
    }
}


function ComboBox(name,inp,but,tbl,par, cod){
//alert("ComboBox:\n" + name+"\n"+inp+"\n"+but+"\n"+tbl+"\n"+par+"\n"+cod);
    this.name     = name;
    this.par      = $(par); //  document.body; // $(inp); // this; // arguments[1]||document.body
    this.inp      = inp;
    this.but      = but;
    this.tbl      = tbl;
    this.cod      = cod;
    this.view     = document.createElement("DIV");
    this.view.style.position='absolute';
    //this.view.style.width = $(tbl).offsetWidth + "px";
    this.options  = new Array();
    this.expops   = new Array();
    this.value    = "";
    this.selected = -1;
    this.last_sel = -1;
    this.top      = 0;
    this.button   = 19;
    this.frame    = null;
    this.loading  = false;
    if(browser_ie){
        this.frame = document.createElement('iframe');
        this.frame.frameborder = "0";
        this.frame.scrolling = "no"; 
        this.frame.src = "javascript://;"
        this.frame.style.position = "absolute";
        this.frame.style.display = 'none';
    }
    
    this.build  = ComboBox_build;
    this.full   = ComboBox_full;
    this.make   = ComboBox_make;
    this.choose = ComboBox_choose;
    this.add    = ComboBox_add;
    this.toggle = ComboBox_toggle;
    this.update = ComboBox_update;
    this.remove = ComboBox_remove;
    this.keydown= ComboBox_keydown;
    this.keyup = ComboBox_keyup;
    this.mouseover=ComboBox_MouseOver;
    this.show  = ComboBox_Show;
    this.hide  = ComboBox_hide;
    this.inp_focus = ComboBox_inp_focus;
    this.setSelected = ComboBox_SetSelected;
    this.MouseOut = ComboBox_OnMouseOut;
    this.MouseOver = ComboBox_OnMouseOver;
    this.ismouseout = ComboBox_IsMouseOut;
    this.ishide     = ComboBox_IsHide;
    // this.view.onkeydown = new Function ("", this.name + ".keydown()");
    this.is_mouseout   = false;
    this.make();
    this.txtview = $(inp);// this.view.childNodes[0]
    this.valcon  = $(inp);// this.view.childNodes[1]
    this.getvalue = ComboBox_GetValue;
    if(this.frame) this.par.appendChild(this.frame);
    this.par.appendChild(this.view);

    Global_combo_array[Global_combo_array.length]=this;
    if(Global_run_event_hook){ComboBox_init()}
}

function ComboBox_IsMouseOut(){
    return this.last_sel != "-1";
}

function ComboBox_IsHide(){
    if(this.opslist)
        return this.opslist.style.display=="none";
    else return false;    
}

ComboBox.prototype.COMBOBOXZINDEX = 1000 //change this if you must

function ComboBox_init() 
{
//	if (document.addEventListener) {
//		document.addEventListener("keyup", ComboBox_handleKey, false );
//		document.addEventListener("mousedown", ComboBox_mouseDown, false );
//	}
//	else if (document.attachEvent) {
//		document.attachEvent("onkeyup", function () { ComboBox_handleKey(window.event); } );
//		document.attachEvent("onmousedown", function () { ComboBox_mouseDown(window.event); } );
//	}
	
    Global_run_event_hook = false;
}

function returnFalse(){return false}

function ComboBoxItem(text,value)
{
    this.text  = text;
    this.value = value;
}

function ComboBox_OnMouseOut(ev){
this.is_mouseout = true;
window.status = "ComboBox_OnMouseOut(): " + this.name;
}

function ComboBox_OnMouseOver(ev){
this.is_mouseout = false;
window.status = "ComboBox_OnMouseOver(): " + this.name;
}

function ComboBox_GetValue(){
var val=null;
var text = String(this.txtview.value).trim().toLowerCase();
for(var i=0;i<this.options.length;i++)
    if(text == this.options[i].text.trim().toLowerCase()){
        val = this.options[i].value;
        break;
    }
return val
}

function ComboBox_keydown(ev){ 
//console.log("ComboBox_keydown(): " + ev.keyCode + " " + this.selected);
    $(this.inp).focus();
    if(ev.keyCode == 38 || ev.keyCode == 40){
        var selected = this.selected;
        if(ev.keyCode == 40 && this.selected < this.options.length-1) this.selected++;
        else if(ev.keyCode == 38  && this.selected > -1) this.selected--;
        var fShow = this.opslist.style.display!='none';
        if(selected != this.selected){
            var el = $(this.inp + '_'+String(selected));
            if(el) el.className = 'combo-item';
            el = $(this.inp + '_'+String(this.selected));
            el.className = 'combo-hilite';
            if(selected < this.selected && this.selected > this.button){this.top+=1;this.button+=1;}
            if(selected > this.selected && this.selected < this.top){this.top-=1;this.button-=1;}
            
            var scroll = this.top * 18;
            this.opslist.scrollTop = scroll;
            if(!fShow)
                this.choose(this.options[this.selected].value,this.options[this.selected].text);
//window.status += "| " + selected+":"+this.selected + "  " + this.top+":"+this.button;     
//console.log("| " + selected+":"+this.selected + "  " + this.top+":"+this.button);      
        }
        return false;
    }
    else if(ev.keyCode == 27) this.toggle();
    else if(ev.keyCode == 13){
        var inp = $(this.inp);
        //inp.value = this.options[this.selected].text;
        this.choose(this.options[this.selected].value,this.options[this.selected].text);
        this.toggle();
        return false;
    }
    else return true;
    
}

function ComboBox_keyup(ev){
    if(ev.keyCode == 38 || ev.keyCode == 40 || ev.keyCode == 27 || ev.keyCode == 13) return false;
    this.setSelected();
    return false;    
}

function ComboBox_SetSelected(){
    var inp = $(this.inp).value;
    var len = inp.length;
    if(len == 0) return;
    this.show();
    inp = String(inp).toLowerCase();
    var selected = this.selected;
    for(var i=0;i<this.options.length;i++)
        if(this.options[i].text.toLowerCase().substring(0,len) == inp){ 
//        window.status = "==: " + this.options[i].text.toLowerCase().substring(0,len)+"  "+inp +"\n"+selected + " " + this.selected;
            this.selected = i;
            var el = $(this.inp + '_'+String(selected));
            if(el) el.className = 'combo-item';
            el = $(this.inp + '_'+String(this.selected));
            el.className = 'combo-hilite';
            
            //if(this.selected>21)
                var scroll = this.selected * 18;
            this.opslist.scrollTop = scroll;
            
            break;
        }
}


