/**
 *  author:		Timothy Groves - http://www.brandspankingnew.net
 *	version:	1.0 - 2006-08-03
 *
 *	requires:	bsn.DOM.js
 *				bsn.Ajax.js
 *
 */

var useBSNns;

if (useBSNns)
{
	if (typeof(bsn) == "undefined")
		bsn = {}
	_bsn = bsn;
}
else
{
	_bsn = this;
}


if (typeof(_bsn.DOM) == "undefined")
	_bsn.DOM = {}
	







_bsn.AutoSuggest = function (fldID, param)
{

	if (!document.getElementById)
		return false;
	
	this.fld = _bsn.DOM.getElement(fldID);	

	if (!this.fld)
		return false;
				
	//this.nInputChars = 0;
	this.aSuggestions = [];
	this.iHighlighted = 0;
	
	this.selectedOptions = new Object();
	
	
	// parameters object
	this.oP = (param) ? param : {};
	// defaults	
	if (!this.oP.minchars)		this.oP.minchars = 1;
	if (!this.oP.method)		this.oP.meth = "get";
	if (!this.oP.varname)		this.oP.varname = "input";
	if (!this.oP.varsearchname)	this.oP.varsearchname = "search_field";
	if (!this.oP.className)		this.oP.className = "autosuggest";
	if (!this.oP.timeout)		this.oP.timeout = 2500;
	if (!this.oP.delay)			this.oP.delay = 500;
	if (!this.oP.maxheight && this.oP.maxheight !== 0)		this.oP.maxheight = 170;
	//if (!this.oP.maxheight && this.oP.maxheight !== 0)		this.oP.maxheight = 150;
	if (!this.oP.cache)			this.oP.cache = true;
	if (!this.oP.separator)		this.oP.separator = ",";
	if (!this.oP.multivalue)	this.oP.multivalue = "N";
	if (!this.oP.codefield)		this.oP.codefield = "";
	if (this.oP.codefield)	this.codefield = _bsn.DOM.getElement(this.oP.codefield);

	
	if (!this.oP.argform)	this.oP.argform = "";
	if (!this.oP.argfield1)	this.oP.argfield1 = "";
	
	var pointer = this;
	
	//20.04.07
	

	this.fld.onkeyup = function () { pointer.getSuggestions( this.value )  };
	//this.fld.onblur = function () { pointer.setHighlightedValue() };
	
	

	this.fld.setAttribute("autocomplete","off");
	
  if ( this.oP.multivalue == "Y" && this.oP.codefield != ""){
		var oldValues = this.fld.value.split(",");	
		var oldCodes = this.codefield.value.split(",");	
		for (i=0; i<=oldValues.length - 2; i++){
			this.selectedOptions[lTrim(oldCodes[i])] = lTrim(oldValues[i]);
		}		
	}
  
}


_bsn.AutoSuggest.prototype.getSuggestions = function (val)
{	

	/*if ((document.forms[this.oP.argform]) && (document.forms[this.oP.argform].elements[this.oP.argfield1])){
		/* 18/04/07
		if (document.forms[this.oP.argform].elements[this.oP.argfield1].value == 0){
			alert("Please select the city first!")
			return false;
		}
		* /
	}*/	
	
	if ( this.oP.multivalue == "Y" ){
		var resultados = this.fld.value.split(",");	
		val = lTrim(resultados[resultados.length - 1]);
	}

	if (val.length < this.oP.minchars)
	{
		this.aSuggestions = [];
		this.clearSuggestions();
		return false;
	}	


	var pointer = this;
	clearTimeout(this.ajID);
	this.ajID = setTimeout( function() { pointer.doAjaxRequest() }, this.oP.delay );

	return false;

}



_bsn.AutoSuggest.prototype.doAjaxRequest = function ()
{
	var pointer = this;
	var url = "";	
	
	// create ajax request
	if ( this.oP.multivalue == "Y" ){

		var resultados = this.fld.value.split(",");	
		//var resultados = this.fld.value.split("-");	
		var search = lTrim(resultados[resultados.length - 1]);
		url = this.oP.script+this.oP.varname+"="+search;
	} else {
		url = this.oP.script+this.oP.varname+"="+this.fld.value;
	}

	if ( (this.oP.argform) && (this.oP.argfield1) ){
		if ((document.forms[this.oP.argform]) && (document.forms[this.oP.argform].elements[this.oP.argfield1]))
			url = url + "&" + this.oP.varsearchname + "=" + document.forms[this.oP.argform].elements[this.oP.argfield1].value;
	}
	
	
	var meth = this.oP.meth;	
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req) };
	var onErrorFunc = function (status) { alert("AJAX error: "+status); };

	var myAjax = new _bsn.Ajax;	
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
}


_bsn.AutoSuggest.prototype.setSuggestions = function (req)
{
	
	var xml = req.responseXML;
	
	// traverse xml
	//
	this.aSuggestions = new Object();
	var results = xml.getElementsByTagName('results')[0].childNodes;
	

	for (var i=0;i<results.length;i++)
	{
		if (results[i].hasChildNodes()){
			
			//20.04.07
			var index = (results[i].getAttribute("id")) ? results[i].getAttribute("id") : i;
			//var index = (results[i].getAttribute("info")) ? results[i].getAttribute("info") : i;
			this.aSuggestions[index] = ( results[i].childNodes[0].nodeValue );
		}
	}
	
	this.idAs = "as_"+this.fld.id;
	
	
	this.createList(this.aSuggestions);

}


_bsn.AutoSuggest.prototype.createList = function(arr)
{

	// clear previous list
	//
	this.clearSuggestions();

	// create and populate ul
	//
	var ul = _bsn.DOM.createElement("ul", {id:this.idAs, className:this.oP.className});
	
	//19.04.07
	/*
	for (j=0; j<document.forms.length; j++){
		for (i=0; i<document.forms[j].elements.length; i++){
			if(document.forms[j].elements[i].type == "select-one")
				document.forms[j].elements[i].style.visibility="hidden";
		}
	}
	*/
	
	var pointer = this;
	i = 0;
	for (it in arr)
	{		
		var a = _bsn.DOM.createElement("a", { href:"#", id:it, styleclass:"autosuggest" }, arr[it]);
		a.onclick = function () { pointer.setValue(this.getAttribute("id"), this.childNodes[0].nodeValue); return false; }
		//a.onmouseover = function () { this.iHighlighted = i; ; return false; };
		var li = _bsn.DOM.createElement(  "li", {}, a  );
		ul.appendChild(  li  );
		i++;
	}
	
	var pos = _bsn.DOM.getPos(this.fld);

	ul.style.left = pos.x + "px";
	ul.style.width = this.fld.offsetWidth+"px";

	//28.04.07
	
	if( i < 10 )	{
		_maxheight = i * 17;
	} else {
		_maxheight = this.oP.maxheight;
	}		
		
	//ul.style.top = ( pos.y + this.fld.offsetHeight ) + "px";
	ul.style.top = ( pos.y - _maxheight) + "px";


    //choi
	//ul.onmouseover = function(){ pointer.killTimeout() }
	//ul.onmouseout = function(){ pointer.resetTimeout() }


	document.getElementsByTagName("body")[0].appendChild(ul);
	
	if (ul.offsetHeight > this.oP.maxheight && this.oP.maxheight != 0)
	{
		ul.style['height'] = this.oP.maxheight;
	}
	

	
	var TAB = 9;
	var ESC = 27;
	var KEYUP = 38;
	var KEYDN = 40;
	var RETURN = 13;
	var COM = 188;
		
	
	this.fld.onkeydown = function(ev)
	{
		var key = (window.event) ? window.event.keyCode : ev.keyCode;

		switch(key)
		{
			case TAB:
			pointer.setHighlightedValue();
			pointer.clearSuggestions();
			break;
			
			case RETURN:
			pointer.setHighlightedValue();		
			pointer.clearSuggestions();
			return false;
			break;

			case ESC:
			pointer.clearSuggestions();
			break;

			case KEYUP:
			pointer.changeHighlight(key);
			return false; 
			break;

			case KEYDN:
			pointer.changeHighlight(key);
			return false; 
			break;
			
			case COM:
			//default:
			pointer.setCom();
			return false; 
			break;
		}

	};
    this.iHighlighted = 0;
	
	
	// remove autosuggest after an interval
	//19.04.07
	/*
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
	*/
}


_bsn.AutoSuggest.prototype.changeHighlight = function(key)
{
	//alert('change!');
	var list = _bsn.DOM.getElement(this.idAs);
	

	if	(!list) 
		return false;

	
	if (this.iHighlighted > 0)
		list.childNodes[this.iHighlighted-1].className = "";
	
	if (key == 40)
		this.iHighlighted ++;
	else if (key = 38)
		this.iHighlighted --;
	
	
	if (this.iHighlighted > list.childNodes.length)
		this.iHighlighted = list.childNodes.length;
	if (this.iHighlighted < 1)
		this.iHighlighted = 1;
	
	list.childNodes[this.iHighlighted-1].className = "highlight";

	//19.04.07
	/*	
	var oldValues = this.fld.value.split(",");	
	var oldValue = "";		
	

	for (i=0; i<=oldValues.length - 2; i++){
		oldValue += lTrim(oldValues[i]) + ', ';
	}
	*/
	//this.fld.value = oldValue + list.childNodes[this.iHighlighted-1].firstChild.firstChild.nodeValue;
	this.fld.value = list.childNodes[this.iHighlighted-1].firstChild.firstChild.nodeValue;
	
	/*
	var oldValues = this.codefield.value.split(",");	
	var oldValue = "";	
	*/

	//19.04.07
	/*	
	for (i=0; i<=oldValues.length - 2; i++){
		oldValue += lTrim(oldValues[i]) + ', ';
	}	
	*/

  //this.codefield.value = oldValue + list.childNodes[this.iHighlighted-1].firstChild.getAttribute("id");
    this.codefield.value = list.childNodes[this.iHighlighted-1].firstChild.getAttribute("id");
  
	//alert('change');
	//19.04.07
	
	//if (this.oP.multivalue != "Y") updateSearch( "true" );
	this.killTimeout();

}


_bsn.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
}

_bsn.AutoSuggest.prototype.resetTimeout = function()
{

	clearTimeout(this.toID);
	var pointer = this;
	
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);

}


_bsn.AutoSuggest.prototype.clearSuggestions = function ()
{

	if (document.getElementById(this.idAs))
		_bsn.DOM.removeElement(this.idAs);
	this.fld.onkeydown = null;

/*
	for (j=0; j<document.forms.length; j++){
		for (i=0; i<document.forms[j].elements.length; i++){
			if(document.forms[j].elements[i].type == "select-one")
				document.forms[j].elements[i].style.visibility="visible";
		}
	}
*/

}


_bsn.AutoSuggest.prototype.setHighlightedValue = function ()
{
	

	
	//alert("entrou");
	//alert(this.iHighlighted);
	/*
	if (document.getElementById(this.idAs)){
		alert('444');
		return false;

	}
	*/
	//alert(this.oP.codefield);
		if ( this.oP.multivalue == "Y" && this.oP.codefield != ""){
			
			
			//alert(list.childNodes.length);
			if (list.childNodes.length == 1) {
				this.changeHighlight('');
			}
						
			
			var allCodes = this.codefield.value.split(",");		

			var lastCode = lTrim(allCodes[allCodes.length - 1]);
			
			var allValues = this.fld.value.split(",");		

			var lastValue = lTrim(allValues[allValues.length - 1]);
			
			//alert(lastCode + " - " + lastValue);
			if ( !lastCode || !lastValue )
				return;
			
			//alert(lastCode + " - " + lastValue);

			this.selectedOptions[lastCode] = lastValue;
			//this.codefield.value += ",";
			//this.fld.value += ", ";
			
			var oldValue = "";
			//alert(allValues.length);
			for (i=0; i<=allValues.length - 1; i++){
				if (lTrim(allValues[i])) oldValue += lTrim(allValues[i]) + ', ';
				//alert("old: " + oldValue);
			}
			this.fld.value = oldValue;
			
			var oldCode = "";
			for (i=0; i<=allCodes.length - 1; i++)
				if (lTrim(allCodes[i])) oldCode += lTrim(allCodes[i]) + ', ';
				
			this.codefield.value = oldCode;
			
		
		}

		if (this.oP.multivalue != "Y") updateSearch( "true" );
		
			
}


_bsn.AutoSuggest.prototype.setCom = function ()
{	

	if ( this.oP.multivalue == "Y" && this.oP.codefield != ""){

		var allCodes = this.codefield.value.split(",");		
		var lastCode = lTrim(allCodes[allCodes.length - 1]);		
		var allValues = this.fld.value.split(",");		
		var lastValue = lTrim(allValues[allValues.length - 1]);
		this.selectedOptions[lastCode] = lastValue;
	}
	//19.04.07
	this.codefield.value += ",";
	if (this.oP.multivalue != "Y") updateSearch( "true" );
}



_bsn.AutoSuggest.prototype.setValue = function (code, val)
{

	if ( this.oP.multivalue == "Y" ){
    
		// setting the value
		var oldValues = this.fld.value.split(",");	
		var oldValue = "";				
		if (existsInArray(oldValues, val)){
			this.resetTimeout();	
			this.fld.focus();
			return;
		}
		for (i=0; i<oldValues.length - 1; i++){
			if (lTrim(oldValues[i])) oldValue += lTrim(oldValues[i]) + ', ';
		}			
		this.fld.value = oldValue + val + ', ';
		
		// setting the code
		if ( this.oP.multivalue == "Y" && this.oP.codefield != ""){
			this.selectedOptions[code] = val;
			
			var oldValues = this.codefield.value.split(",");	
			var oldValue = "";
			for (i=0; i<oldValues.length - 1; i++){
	
				if (lTrim(oldValues[i])) oldValue += lTrim(oldValues[i]) + ', ';					
			}		
			this.codefield.value = oldValue + code + ', ';
		}
	} else {
		this.fld.value = val;
		if ( this.oP.codefield != "" ) this.codefield.value = code;
	}

	if (this.oP.multivalue != "Y") updateSearch( "true" );
	
	this.resetTimeout();	
	this.fld.focus();
}

// OTHERS FUNCTIONS

function trim(STRING){
	STRING = LTrim(STRING);
	return RTrim(STRING);
}

function rTrim(STRING){
	while(STRING.charAt((STRING.length -1))==" "){
		STRING = STRING.substring(0,STRING.length-1);
	}
	return STRING;
}

function lTrim(STRING){
	while(STRING.charAt(0)==" "){
		STRING = STRING.replace(STRING.charAt(0),"");
	}
	return STRING;
}

function existsInArray( arr, val ){
	for (i=0; i<arr.length - 1; i++){
		if (val == lTrim(arr[i])) return true;
	}
	return false;
}

function submitRemoveDeletedCodes( obj ){
	
	//alert(obj.oP.multivalue)
	// invalid codes
	var codeValues = "";
	var descriptionValues = (obj.fld.value + ",").split(",");
	for (it in obj.selectedOptions){
		if ( existsInArray(descriptionValues, rTrim(obj.selectedOptions[it])) )
			if (it) {
				if (obj.oP.multivalue == "Y") codeValues += it + ",";
				else codeValues = it;
			}
	}
	if (obj.oP.multivalue == "Y") obj.codefield.value=codeValues;
	
	
	// invalid names
	var descriptionValue = "";
	var codeValues = obj.codefield.value.split(",");
	for (it in obj.selectedOptions){
		//alert(it + " - " + rTrim(obj.selectedOptions[it]) + " - " + existsInArray(codeValues, it));
		if ( existsInArray(codeValues, it))
			if (it) {
				if (obj.oP.multivalue == "Y") descriptionValue += rTrim(obj.selectedOptions[it]) + ", ";
				else descriptionValue += rTrim(obj.selectedOptions[it]) ;
			}
			
	}
	if (obj.oP.multivalue == "Y") descriptionValue = descriptionValue.substring(0,descriptionValue.length-2);	
	
}

function submitRemoveDeletedCodes2( obj ){
	
	
	// invalid codes
	var codeValues = "";
	var descriptionValues = (obj.fld.value + ",").split(",");
	for (it in obj.selectedOptions){
		if ( existsInArray(descriptionValues, rTrim(obj.selectedOptions[it])) )
		//19.04.07
			//if (it) codeValues += it + ",";
			if (it) codeValues = it;
	}
	//18/04/07
	//obj.codefield.value=codeValues;
	
	
	// invalid names
	var descriptionValue = "";
	var codeValues = obj.codefield.value.split(",");
	for (it in obj.selectedOptions){
		//alert(it + " - " + rTrim(obj.selectedOptions[it]) + " - " + existsInArray(codeValues, it));
		if ( existsInArray(codeValues, it))
			//19.04.07
			//if (it) descriptionValue += rTrim(obj.selectedOptions[it]) + ", ";
			if (it) descriptionValue += rTrim(obj.selectedOptions[it]) ;
			
		//alert(descriptionValue);
	}
	//descriptionValue = descriptionValue.substring(0,descriptionValue.length-2);
	//18/04/07
	//obj.fld.value=descriptionValue;
	
	
}