/*
 *	ComboBox
 *	By Jared Nuzzolillo
 *
 *	Updated by Erik Arvidsson
 *	http://webfx.eae.net/contact.html#erik
 *	2002-06-13	Fixed Mozilla support and improved build performance
 *      2009-03-20 nilschd: rewrite to use divs and change event trapping logic
 */

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 bt,nm;
    nm = this.name+"Text"; 
    this.txtview = document.getElementById(nm);
    var comboBtn = (document.getElementById(this.name+"Btn")||null);

    if(this.needToSetupHtml) {
        this.txtview = document.createElement("INPUT");
	this.txtview.type = "text";
	this.txtview.name = nm;
	this.txtview.id = nm;
	this.view.appendChild(this.txtview);

	this.valcon = document.createElement("INPUT");
	this.valcon.type = "hidden";
	this.valcon.name = this.name;
	this.valcon.id = this.name;
	this.view.appendChild(this.valcon);

	comboBtn = document.createElement("BUTTON");
	comboBtn.appendChild(document.createTextNode("6"));
	comboBtn.id=this.name+"Btn";
	this.view.appendChild(comboBtn);

    }

    //        this.txtview.className = "combo-input";
    //comboBtn.className = "combo-button";
    if(comboBtn!=null) {
        comboBtn.onfocus = function () { this.blur(); };
        comboBtn.onclick = new Function ("", this.name + ".toggle(); return false;" );
    }
	

   
	//    var tmp = document.createElement("IMG");
	//tmp.src = "___";
	//tmp.style.width = "1px";
	//tmp.style.height = "0";
	//this.view.appendChild(tmp);
    

    


}

function ComboBox_choose(realval,txtval)
{
    this.value         = realval;
    //    var samstring = this.name+".view.childNodes[0].value='"+txtval+"'";

    var samstring = 'document.getElementById("'+this.name+'Text").value="'+txtval+'"';
    window.setTimeout(samstring,1);
    this.valcon.value  = realval;
}

function ComboBox_selectNext() {
    if(this.opslist == null) return;

    if( this.currentIndex > -1 ) {
	document.getElementById(this.name+'_comboOption_'+this.currentIndex).className='combo-item';
    }
    this.currentIndex++;

    if(this.currentIndex >= this.activeOptions.length) {
	this.currentIndex=this.activeOptions.length-1;
    }
    document.getElementById(this.name+'_comboOption_'+this.currentIndex).className='combo-hilite';
    this.choose(this.activeOptions[this.currentIndex].value,this.activeOptions[this.currentIndex].text);
}

function ComboBox_selectPrev() {
    if(this.opslist == null) return;
        
    if( this.currentIndex > -1 ) {
	document.getElementById(this.name+'_comboOption_'+this.currentIndex).className='combo-item';
    }
    this.currentIndex--;
    if(this.currentIndex < 0) { this.currentIndex = 0;}

    document.getElementById(this.name+'_comboOption_'+this.currentIndex).className='combo-hilite';
    this.choose(this.activeOptions[this.currentIndex].value,this.activeOptions[this.currentIndex].text);
}

function ComboBox_selectCurrent() {
    if(this.opslist == null) return;
    setTimeout('document.getElementById("'+this.opslist.id+'").style.display="none";',1);
    //select
}



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_handleKeyDown(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.id;

    if( elcl.indexOf("comboBox")==0 &&  elcl.indexOf("Text") > 0) {
        strname = el.id.split("Text")[0];
        obj = window[strname];
        //        o2Debug.log("down "+key);
        if(key == 13) {//enter
          if (!obj.isExpanded()) {
            return; // Allow search form to be submitted when the user hits return
          }
            obj.selectCurrent();
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        }
        /*        else if(key ==27) { //esc
            obj.toggle();
            }*/
    }

    return false;
}

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.id;
    if( elcl.indexOf("comboBox")==0 &&  elcl.indexOf("Text") > 0) {
        strname = el.id.split("Text")[0];
        obj = window[strname];
        obj.valcon.value = el.value;
       
        if(key == 40 ){//down arrow
            return obj.selectNext();
        }
        else if(key == 38) {//up arrow 
            return obj.selectPrev();
        }
        else if(key == 13) {//enter
            return obj.selectCurrent();
        }
        
        obj.expops.length=0;
        obj.update();
        obj.build(obj.expops);
        if(obj.expops.length==1&&obj.expops[0].text==this.noMatchLabel){
            obj.opslist.style.display="none";
        }//empty
        else{
            //            var g = __elementGeometry(document.getElementById(obj.name+"Parent"));
            // var h = document.getElementById(obj.name+"Parent").offsetHeight;
            //obj.opslist.style.width=document.getElementById(obj.name+"Parent").offsetWidth+"px";
            //obj.opslist.style.left=g.left+"px";
            //obj.opslist.style.top=(g.top+h-1)+"px";
            this.currentIndex=-1;
        }
        obj.value = el.value;
        // 20080208 nilschd to allow mode == "select"
        // 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;

    this.currentIndex=-1;

    if(alen==0)
    {
        if(this.showSuggestionOnEmpty) {
            for(i=0;i<opln;i++) {
                this.expops[this.expops.length]=this.options[i];boo=true;
            }
        }
        else {
            if(this.opslist!=null)
                this.opslist.style.display='none';
        }
    }
    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(this.noMatchLabel,"")}
}


function ComboBox_remove(index)
{
    if(isNaN(index)||index>this.options.length){self.status='Array_remove:invalid request-'+index;return false}

    for(var i=0,n=0;i<this.optionslength;i++)
    {  
        if(this.options[i]!=this.options[dx])
        {
            this.options[n++]=this.options[i];
        }
    }
    this.optionslength-=1

	//    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_build(arr) {

    if(this.opslist){this.view.removeChild(this.opslist);}

    this.opslist = document.createElement('DIV');
    this.opslist.id=this.name+"List";

    this.activeOptions = new Array();
    
    var length=arr.length;

    if(this.optionsPreview!=null && this.optionsPreview < length) {
        length=this.optionsPreview;
    }

    for(var i=0;i < length;i++) {
        var divOption = document.createElement('DIV');
        divOption.id=this.name+'_comboOption_'+i;
        divOption.className='combo-item';
        o2.addEvent(divOption,'mousedown', new Function(this.name+'.choose(\''+arr[i].value+'\',\''+arr[i].text+'\');'+this.name+'.opslist.style.display=\'none\';'));
        o2.addEvent(divOption,'mouseover', new Function('document.getElementById("'+divOption.id+'").className="combo-hilite";'));
        o2.addEvent(divOption,'mouseout', new Function('document.getElementById("'+divOption.id+'").className="combo-item";'));
        this.activeOptions[i] = arr[i];
        divOption.innerHTML=arr[i].text;
        this.opslist.appendChild(divOption);
    }
    

    this.opslist.onselectstart=returnFalse;
    this.opslist.className='combo-item-list';
    this.opslist.style.display='';
    this.view.appendChild(this.opslist);    

}


function ComboBox_toggle() {
    if(this.opslist) {
        if(this.opslist.style.display=="block") {
            this.opslist.style.display="none"
        }
        else {
            this.update();
            this.build(this.options);
	    //            this.view.style.zIndex = ++ComboBox.prototype.COMBOBOXZINDEX
	     this.opslist.style.display="block"
        }
    }
    else {
        this.update();
        this.build(this.options);
	//       this.view.style.zIndex = ++ComboBox.prototype.COMBOBOXZINDEX
        this.opslist.style.display="block"
    }

    
    var g = __elementGeometry(document.getElementById(this.name+"Parent"));
    var h = document.getElementById(this.name+"Parent").offsetHeight;
    //    this.opslist.style.position='absolute';
    // this.opslist.style.width=document.getElementById(this.name+"Parent").offsetWidth+"px";
    // this.opslist.style.left=g.left+"px";
    // this.opslist.style.top=(g.top+h-1)+"px";
    document.getElementById(this.name+"Text").select();
    document.getElementById(this.name+"Text").focus();

}

function ComboBox()
{
    if(arguments.length==0)
    {
        self.status="ComboBox invalid - no name arg"
    }

    this.name     = arguments[0];
    this.optionsPreview = arguments[1]||null;
    this.noMatchLabel   = arguments[2]||null;
    this.par      = arguments[3]||document.body;

    

    this.options  = new Array();
    this.expops   = new Array();
    this.value    = ""

    this.build  = ComboBox_build
    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.selectNext = ComboBox_selectNext;
    this.selectPrev = ComboBox_selectPrev;
    this.selectCurrent = ComboBox_selectCurrent;
    this.isExpanded = ComboBox_isExpanded;
    this.showSuggestionOnEmpty = false;
    this.currentIndex  =-1;

    this.needToSetupHtml= (document.getElementById(this.name+"Parent") == null);

    if(this.needToSetupHtml) {
	this.view     = document.createElement("DIV");
        //this.view.style.position='absolute';
	this.par.appendChild(this.view)
    }
    else {
	this.view     = document.getElementById(this.name+'Parent');
    }
    this.make();
    this.txtview = document.getElementById(this.name+'Text');//||this.view.childNodes[0];
    this.valcon  = document.getElementById(this.name);//this.view.childNodes[1];
    
    Global_combo_array[Global_combo_array.length]=this;
    if(Global_run_event_hook){ComboBox_init()}
}

ComboBox.prototype.COMBOBOXZINDEX = 1000 //change this if you must

function ComboBox_init() 
{
	if (document.addEventListener) {
            document.addEventListener("keydown", ComboBox_handleKeyDown, false );
            document.addEventListener("keyup", ComboBox_handleKey, false );
            document.addEventListener("mousedown", ComboBox_mouseDown, false );
	}
	else if (document.attachEvent) {
            document.attachEvent("onkeydown", function () { ComboBox_handleKeyDown(window.event); } );
            document.attachEvent("onkeyup", function () { ComboBox_handleKey(window.event); } );
            document.attachEvent("onmousedown", function () { ComboBox_mouseDown(window.event); } );
	}
	
    Global_run_event_hook = false;
}

function ComboBox_isExpanded() {
  if (this.opslist == null) {
    return false;
  }
  return document.getElementById( this.opslist.id ).style.display !== "none";
}

function returnFalse(){return false}

function ComboBoxItem(text,value)
{
    this.text  = text;
    this.value = value;
}

//document.write('<link rel="STYLESHEET" type="text/css" href="ComboBox.css">')


function __elementGeometry(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
        
	return {left:curleft,top:curtop};
}

