var allACObjs = new Array();
var hx_pasteOP = false;

function AutoCompleteObj(){
		this.install										= hx_aco_install;
		this.update									=hx_aco_update;
		this.ajaxURL									= null;
		this.objIndex									= allACObjs.length;
		this.setURL									=xg_aco_seturl;
		this.maxObjects							=-1;
		this.pWidth									=150;
		this.pExtended								=false;
		this.pValidation								=null;
		this.block										=hx_aco_block;
		this.values										=new Array();
		this.request = null;
		this.busy = false;
		this.reqCount = 0;
        this._xtimer = null;
        this._currentRequest = null;

		allACObjs[allACObjs.length]		=this;
}


function hx_aco_block(){

	if (this.values.length == this.maxObjects){
		//I will block
		this._input.style.visibility = "hidden";
	}else{
		this._input.style.visibility = "visible";		
	}
	
	this.parentInput.value = this.values.toHString();
	try{
	this.parentInput.onchange();
	}catch(e){}
}

function xg_aco_seturl(nurl){
	this.ajaxURL = nurl;
}

function hx_aco_update(){
	this.values = new Array();
	this._parentObj.innerHTML = "";
	this.install(this._parentObj.id,this.parentInput.id,this.maxObjects,this.ajaxURL);
}
function hx_aco_install(parentObj,parentInput,count,aurl,tabindex,parent){
	if (typeof(parent) != "object") this._parentScroll = xg.obj(parent);
		else this._parentScroll = parent;

	var _div = xg.obj(parentObj);
	this._parentObj = _div;
	this.ajaxURL = aurl;
	this.maxObjects = count;
	var _input = null;
	var _wrapper = null;
	this.parentInput = xg.obj(parentInput);
	var _valuexx = this.parentInput.value;
	_valuexx = replaceStr(_valuexx,"|",",");
	this.parentInput.value = _valuexx.trim();


	_input = document.createElement("INPUT");

	if (xg.browser.sName == "ie") {
		_wrapper = document.createElement("<DIV style='float:left;' />");
	}
		else _wrapper = document.createElement("DIV");
	
	
	_input.className ="h_input";
	_input.style.border = "none";
	_input.style.position = "relative";
	_input.style.left = "0px";
	_input.style.top = "0px";
	_input.style.backgroundColor = "transparent";
	
	if (xg.browser.sName == "sf"){
		_input.style.left = "-4px";
		_input.style.top = "-6px";
		_input.style.paddingLeft = "5px";
		_input.style.paddingTop = "7px";
		_input.style.paddingBottom = "7px";
	}


	_wrapper.className = "h_input";
	_wrapper.style.float = "left";
	_wrapper.style.display = "inline-block";
	_wrapper.style.width = "40px";
	_wrapper.style.height = "18px";
	_wrapper.style.padding = "2px";
	_wrapper.style.margin = "2px";
	if (xg.browser.sName == "sf")	_wrapper.style.overflow = "hidden";

	var _ttip = document.createElement("DIV");
	_ttip.style.position = "absolute";
	_ttip.style.left = "1px";
	_ttip.style.top = "1px";
	_ttip.className = "h_input";
	_ttip.style.whiteSpace = "nowrap";
	_ttip.style.visibility = "hidden";

	_wrapper.appendChild(_input);
	_div.appendChild(_wrapper);
	_div.appendChild(_ttip);

	_div.onclick = function(){
			try{
				_input.focus();
			}catch(e){}
	}
	
	
	_input.tabIndex = tabindex;
	


	var popup = new xgPopup();
	popup.setContent("<div style='width:150px;height:50px;color:white;'></div>");
	popup._sindex = -1;
	this._popup = popup;
	this._input = _input;
	
	var ac = this;
	
	if (_input.id != null || _input.id.length == 0) _input.id = "ac_in_"+GenerateID();

	_input.onpaste = function(evt){
		
		window.setTimeout("ac_blur_CP('"+this.id+"');",10);
	}
		
	_input.onblur = function(evt){
			if(!ac._popup.visible){
				if (hx_aco_validate(ac,_input.value)){
				
					hx_aco_installDIVS(_div,_input,_wrapper,ac);
					_ttip.innerHTML = "";
					ac.block();
				}else{
					_input.value = "";
				}
			}
	
	}
	
	var _obj =xg.obj(parentInput);
	var _obj_value = _obj.value;
	if (!_obj_value.endsWith(",")) _obj_value = _obj_value+",";

	if (_obj_value.length > 0){
		while (_obj_value.indexOf(",")>-1){
			var _myvalue = _obj_value.substring(0,_obj_value.indexOf(","));
			if(this.pExtended){
				_myvalue = replaceStr(_myvalue,"<","[");
				_myvalue = replaceStr(_myvalue,">","]");
				_myvalue = "<b>"+_myvalue.substring(0,_myvalue.indexOf("["))+"</b>&nbsp;"+_myvalue.substring(_myvalue.indexOf("["));
			}
		_input.value =_myvalue;
		_input.onblur();
		_obj_value = _obj_value.substring(_obj_value.indexOf(",")+1);
		}
	}

	

    _input.onkeyup=  function(evt){
        if (!evt) evt = event;
	    ac._evt = evt;
        ac._input = this;
        if (ac._xtimer != null) window.clearTimeout(ac._xtimer);
        ac._xtimer = window.setTimeout("ac_input_onkeyup('"+ac.objIndex+"')",400);
    }



	_input.onkeydown = function(evt){
		if (!evt) evt = event;
		var chr= String.fromCharCode(evt.keyCode);

        if (evt.keyCode == 32) chr = " ";
		_ttip.innerHTML = _input.value+chr;
		_input.style.width = parseInt(_ttip.offsetWidth+15)+"px";
		_wrapper.style.width = (parseInt(_input.offsetWidth)-10)+"px";

		if (evt.keyCode == 13){
			if (popup.visible){
				ac_popup_selectValue(ac);
			}
				if (hx_aco_validate(ac,_input.value)){
					hx_aco_installDIVS(_div,_input,_wrapper,ac);
					_ttip.innerHTML = "";
					ac.block();
				}
				return false;
		}
	}
}

	ac_input_onkeyup = function(index){
        var ac = allACObjs[index];
		var evt = ac._evt;
			if (hx_pasteOP){
			hx_pasteOP=false;
			ac._input.onblur();
		}

		if (ac._popup.visible && (evt.keyCode == 40 || evt.keyCode == 38)){
			if(evt.keyCode == 40){
					ac._popup._sindex++;
			}else
				if (evt.keyCode == 38){
					ac._popup._sindex--;
				}
				ac_popup_select(ac,ac._popup._sindex);
				return false;
		}


		if (ac._input.value.length == 0) {
			if (ac._popup.visible) ac._popup.hide();
			return;
		}


		ac.request = xg.xhr.post(ac.ajaxURL+ac._input.value+"&before=<div class='ac_div' onclick='ac_click_item(this,"+ac.objIndex+")' onmouseover='ac_mitem_over(this)' onmouseout='ac_mitem_out(this)'>",
			function (resObj){
                ac.request = null;
				if (resObj.length ==0) {
					popup.hide();
					return;
				}

		var _scroll = 20;
		try {
			_scroll = parseInt(parseFloat(ac._parentScroll.scrollTop));
		}catch(e){}

		if (!ac._popup.visible) {
			ac._popup.show(xg.util.getLeft(this)-20,xg.util.getTop(ac._input)-ac._popup.height-_scroll);
			ac._popup.setOrientation(2);
		}
		if (resObj.trim().length>0){
				ac._popup._sindex = -1;
				ac._popup.setContent("<div style='width:"+ac.pWidth+"px;overflow:hidden;margin-top:10px;'>"+resObj+"</div>");
				var _top = xg.util.getTop(ac._input)-ac._popup.height;
				_top = xg.util.getTop(ac._input)+15-_scroll;
				ac._popup.setOrientation(2);
				ac._popup.autosize();

				ac._popup.move(xg.util.getLeft(ac._input)-25,_top+25);
		}else{
			if (ac._popup.visible) ac._popup.hide();
		}
		});

	}

function ac_blur_CP(objid){
	var obj = xg.obj(objid);
	obj.blur();
}

function ac_popup_selectValue(myac){
	if (myac._popup._sindex > -1){
			var _myvalue = myac._popup._htmlc.childNodes[0].childNodes[myac._popup._sindex].innerHTML;
			myac._input.value = _myvalue;
	}
}

function ac_popup_select(myac,item){
	if (item > myac._popup._htmlc.childNodes[0].childNodes.length-1){
		item = 0;
	}
	if (item < 0){
		item = myac._popup._htmlc.childNodes[0].childNodes.length-1;
	}
	var _myobj = myac._popup._htmlc.childNodes[0].childNodes[item];
	ac_mitem_over(_myobj);
	if (myac._lastselected){
		ac_mitem_out(myac._lastselected);
		var _parent = _myobj.offsetParent;
		if (_parent)_parent.scrollTop = _myobj.offsetTop-parseInt(_parent.offsetHeight)+30;
	}
	myac._lastselected = _myobj;
	myac._popup._sindex = item;
}

function ac_click_item(obj,acindex){
	var myac = allACObjs[acindex];
	myac._popup.hide();
	myac._input.value = obj.innerHTML;
  	myac._input.onblur();
	try{
	myac._input.focus();
	}catch(e){}
}

function ac_mitem_over(obj){
	obj.className = "ac_div_over";
}

function ac_mitem_out(obj){
	obj.className = "ac_div";
}

function hx_aco_validate(ac,value){
	if (ac.pValidation != null){
		if (ac.pValidation == "email"){
			if (value.indexOf("[")>-1 && value.indexOf("]")>-1 && value.indexOf("@")>-1) value = value.substring(value.indexOf("[")+1,value.indexOf("]"));
            value = value.trim();
			var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/; 
			return emailPattern.test(value);
		}else
		if (ac.pValidation == "phone"){
		    if (value.indexOf("[")>-1 && value.indexOf("]")>-1) value = value.substring(value.indexOf("[")+1,value.indexOf("]"));
            value = value.trim();
            if(value.startsWith("+")) value = value.substring(1);
            if (value.indexOf(".")>-1) value = replaceStr(value,".","");
            var phonePattern = /^(([0-9]{1})*[- .(]*([0-9a-zA-Z]{3})*[- .)]*[0-9a-zA-Z]{3}[- .]*[0-9a-zA-Z]{4})+$/;
            return phonePattern.test(value);
		}
	}
	return true;
}

function hx_aco_installDIVS(_div,_input,_wp,myac){
   	if (_input.value.trim().length == 0) return;
   			var _newDiv = null;
			if (xg.browser.sName == "ie") _newDiv = document.createElement("<DIV style='float:left'>");
				else _newDiv = document.createElement("DIV");
				_newDiv.className = "ac_tag";
			var _myValue = _input.value;
			var _myIValue = _myValue;
			if (myac.pExtended){
				_myValue =	_myValue.substring(0,_myValue.indexOf("["));
				if (myac.pValidation == "phone"){
						_myIValue = replaceStr(_myIValue,"&nbsp;","");
						_myIValue = replaceStr(_myIValue,"<b>","");
						_myIValue = replaceStr(_myIValue,"</b>","");
						_myIValue = replaceStr(_myIValue,"<B>","");
						_myIValue = replaceStr(_myIValue,"</B>","");
				}else{
					_myIValue = _myIValue.substring(_myIValue.indexOf("[")+1,_myIValue.indexOf("]"));
				}
				if (_myValue.length == 0){
					_myValue = _input.value;
				}
				if (_myIValue.length == 0) _myIValue = _input.value;
				var t = _input.value;
				t = replaceStr(t,"&nbsp;","");
				t = replaceStr(t,"<b>","");
				t = replaceStr(t,"</b>","");
				t = replaceStr(t,"<B>","");
				t = replaceStr(t,"</B>","");
				_newDiv.title = t;

			}
			_newDiv.innerHTML = _myValue;
			
			if (location.protocol.indexOf("https")>-1){
				_newDiv.style.backgroundImage = "url('https://heeloo.net/imgs/close.png')";
			}else{
				_newDiv.style.backgroundImage = "url('http://imgs.nbahn.com/close.png')";
			}
			_newDiv.style.backgroundRepeat = "no-repeat";
				_newDiv.style.backgroundPosition = "-50px 0px";

			_div.insertBefore(_newDiv,_wp);
			
			myac.values[myac.values.length]= _myIValue;
			_input.value = "";
				_input.style.width = parseInt(20)+"px";
			_wp.style.width = (5)+"px";



			_newDiv.onmouseover = function(){
				this.className = "ac_tag_over";
				this.style.backgroundPosition = (parseInt(this.offsetWidth)-16)+"px 5px";
			}	

			_newDiv.onmouseout = function(){
				this.className = "ac_tag";
				this.style.backgroundPosition = (parseInt(this.offsetWidth)+20)+"px 5px";

			}
            
			_newDiv.onclick = function(evt){
				if (!evt) evt =event;
				var _x = evt.clientX-parseInt(xg.util.getLeft(this));
				var _y = evt.clientY - parseInt(xg.util.getTop(this));
			
				if (_x > (parseFloat(this.offsetWidth)-20))	{
					hx_aco_closeAC(this,_div,myac);
				}
			}
}


function hx_aco_closeAC(obj,_parent,myac){
	if (myac.pValidation == "phone"){
		myac.values = myac.values.remove(obj.title);
	}else{
		myac.values = myac.values.remove(obj.innerHTML);
	}
	if (location.protocol.indexOf("https")>-1){
				obj.style.backgroundImage = "url('https://heeloo.net/imgs/close_over.png')";
			}else{
				obj.style.backgroundImage = "url('http://imgs.nbahn.com/close_over.png')";
			}
	_parent.removeChild(obj);
	myac.block();

}
