/* ******************************************************************* */

function SearchObject(values) {
    this.values = values;
}

SearchObject.prototype.GetDisplayString = function() {
    return this.values.join(", ");
}

SearchObject.prototype.GetValue = function() {
    return this.values.join(", ");
}

/* return values: 1 = match on toplevel item; 2 = match on subitem; 0 = no match */
SearchObject.prototype.IsMatch = function(searchstring) {
    for(var i = 0; i < this.values.length; i++)
    {
        if(this.values[i].indexOf(searchstring) > -1) return 1;
    }
    
    if(this._subitems != null)        
    {
        for(var x = 0; x < this._subitems.length; x++)
        {
            if(this._subitems[x].IsMatch(searchstring)) return 2;
        }
    }
    
    return 0;
}

/* ******************************************************************* */

function SearchAccount(values) {
    this.values = values;
}

SearchAccount.prototype.GetDisplayString = function() {   
    return this.values.join(", ");
}

SearchAccount.prototype.GetValue = function() {   
    return this.values[2];
}

/* return values: 1 = match on toplevel item; 2 = match on subitem; 0 = no match */
SearchAccount.prototype.IsMatch = function(searchstring) {
    for(var i = 0; i < this.values.length; i++)
    {
        if(this.values[i].indexOf(searchstring) > -1) return 1;
    }
    
    if(this._subitems != null)        
    {
        for(var x = 0; x < this._subitems.length; x++)
        {
            if(this._subitems[x].IsMatch(searchstring)) return 2;
        }
    }
    
    return 0;
}

/* ******************************************************************* */
function SearchProduct(values) {
    this.values = values;
}

SearchProduct.prototype.GetDisplayString = function() {   
    return this.itemno;
}

SearchProduct.prototype.GetValue = function()  {   
    return this.values[0];
}

// return values: 1 = match on toplevel item; 2 = match on subitem; 0 = no match
SearchProduct.prototype.IsMatch = function(searchstring)
{
    for(var i = 0; i < this.values.length; i++)
    {
        if(this.values[i].indexOf(searchstring) > -1) return 1;
    }
    
    if(this.itemno.indexOf(searchstring) > -1) return 1;
    
    if(this._subitems != null)        
    {
        for(var x = 0; x < this._subitems.length; x++)
        {
            if(this._subitems[x].IsMatch(searchstring)) return 2;
        }
    }
    
    return 0;
}

/* ************************************* Generic autocomplete *********************************/
var useAutocomplete;

if (useAutocomplete)
{
	if (typeof(atc) == "undefined")
		atc = {}
	_atc = atc;
}
else
{
	_atc = this;
}

if (typeof(_atc.Autosuggest) == "undefined")
	_atc.Autosuggest = {}

_atc.AutoSuggest = function (fldID, param, getSuggestionsMethodName)
{
	if (!document.getElementById) return false;
	
	this.fld = _atc.DOM.getElement(fldID);
	this.getSuggestionsMethodName = getSuggestionsMethodName;

	if (!this.fld) return false;
	
	// init variables
	this.sInput 		= "";
	this.nInputChars 	= 0;
	this.aSuggestions 	= [];
	this.iHighlighted = 0;
	this.iSubHighlighted = 0;
	
	// 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.className)									this.oP.className = "autosuggest";
	if (!this.oP.timeout)									this.oP.timeout = 2500;
	if (!this.oP.delay)										this.oP.delay = 250;
	if (!this.oP.offsety)									this.oP.offsety = -5;
	if (!this.oP.shownoresults)								this.oP.shownoresults = true;
	if (!this.oP.noresults)									this.oP.noresults = "No results!";
	if (!this.oP.maxheight && this.oP.maxheight !== 0)		this.oP.maxheight = 250;
	if (!this.oP.cache && this.oP.cache != false)			this.oP.cache = true;
	if (!this.oP.enforceExistingValue)			            this.oP.enforceExistingValue = false;
	
	// set keyup handler for field
	// and prevent autocomplete from client
	var pointer = this;
	
	this.fld.onkeypress 	= function(ev){ return pointer.onKeyPress(ev); }
	this.fld.onkeyup 		= function(ev){ return pointer.onKeyUp(ev); }
	
	if(this.oP.enforceExistingValue)
	{
	    this.fld.onblur     = function(ev){ return pointer.onEnforceExistingValue(ev); }
	}
	
	this.fld.setAttribute("autocomplete","off");
}

_atc.AutoSuggest.prototype.onKeyPress = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	var bubble = true;

	switch(key)
	{
		case RETURN:
			this.setHighlightedValue();
			bubble = false;
			break;

		case ESC:
			this.clearSuggestions();
			break;
	}

	return bubble;
}

_atc.AutoSuggest.prototype.onEnforceExistingValue = function(ev)
{
    if(this.fld.value == "") return true;
    
    this.setSuggestions();
    for(var i = 0; i < this.aSuggestions.length; i++)
    {
        if(this.aSuggestions[i]._subitems == null)
        {
            if(this.aSuggestions[i].GetDisplayString() == this.fld.value)
            {
                this.oP.callback( this.aSuggestions[i]);
                return false;
            }
        }
        else
        {
            for(var j = 0; j < this.aSuggestions[i]._subitems.length; j++)
            {
                if(this.aSuggestions[i]._subitems[j].GetValue() == this.fld.value)
                {
                    this.oP.callback( this.aSuggestions[i], this.aSuggestions[i]._subitems[j] );
                    return false;
                }
            }
        }
    } 
    
    alert("You have to select an existing value. Type the first letters to get automatic completion support.");
    this.fld.focus();
    return true;
}

_atc.AutoSuggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;

	var ARRUP = 38;
	var ARRDN = 40;
	
	var bubble = true;

	switch(key)
	{
		case ARRUP:
			this.changeHighlight(key);
			bubble = false;
			break;

		case ARRDN:
			this.changeHighlight(key);
			bubble = false;
			break;
		
		default:
			this.getSuggestions(this.fld.value);
	}
	return bubble;
}

_atc.AutoSuggest.prototype.getSuggestions = function (val)
{
	// if input stays the same, do nothing
	if (val == this.sInput)
		return false;

	// input length is less than the min required to trigger a request
	// reset input string
	// do nothing
	if (val.length < this.oP.minchars)
	{
		this.sInput = "";
		return false;
	}
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	if (val.length>this.nInputChars && this.aSuggestions.length && this.oP.cache)
	{
	    
		var arr = [];
		for (var i=0;i<this.aSuggestions.length;i++)
		{
		    var match = this.aSuggestions[i].IsMatch(val);
		    if(match > 0) arr.push( this.aSuggestions[i] );
		}
		
		this.sInput = val;
		this.nInputChars = val.length;
		this.aSuggestions = arr;
		
		this.createList(this.aSuggestions);
		
		return false;
	}
	else
	{
		this.sInput = val;
		this.nInputChars = val.length;

		var pointer = this;
		clearTimeout(this.ajID);
		pointer.setSuggestions()
	}

	return false;
}

_atc.AutoSuggest.prototype.setSuggestions = function ()
{
	this.aSuggestions = [];
	this.aSuggestions = eval(this.getSuggestionsMethodName + '()');
	
	this.idAs = "as_"+this.fld.id;
	//this.createList(this.aSuggestions);
}

_atc.AutoSuggest.prototype.buildSubitems = function(n, list)
{
    var pointer = this;
    var index = Number(n);
    var ul = _atc.DOM.createElement("ul");
	
	this.aSuggestions[index - 1].aSubSuggestions = new Array();
	var match = this.aSuggestions[index-1].IsMatch(this.sInput) == 1;
	for(var i = 0; i < this.aSuggestions[index-1]._subitems.length; i++)
	{
	    var subdiv = list.childNodes[index-1].childNodes[1];    
	    if(match || this.aSuggestions[index-1]._subitems[i].IsMatch(this.sInput) == 1)
	    {
	        this.aSuggestions[index-1].aSubSuggestions.push(this.aSuggestions[index-1]._subitems[i]);
	        
	        var li = _atc.DOM.createElement("li");
	        var a = _atc.DOM.createElement("a", {}, this.aSuggestions[index-1]._subitems[i].GetDisplayString(), true);
	        a.name = (index).toString() + "_" + (this.aSuggestions[index-1].aSubSuggestions.length).toString();
    	    
	        a.onclick = function () { pointer.setHighlightedValue(this.name); return false; }
	        a.onmouseover = function () { pointer.setSubHighlight(this.name); }
    	    
	        li.appendChild(a);
	        ul.appendChild(li);
	    }
	}
    
    subdiv.appendChild(ul);
	
	if(this.aSuggestions[index - 1].aSubSuggestions != null && this.aSuggestions[index - 1].aSubSuggestions.length > 10)
	{
	    subdiv.style.maxHeight = "280px";
	    subdiv.style.overflow = "scroll";
	}
}

_atc.AutoSuggest.prototype.createList = function(arr)
{

	var pointer = this;
	
	_atc.DOM.removeElement(this.idAs);
	this.killTimeout();
	
	var div = _atc.DOM.createElement("div", {id:this.idAs, className:this.oP.className});	
	
	var hcorner = _atc.DOM.createElement("div", {className:"as_corner"});
	var hbar = _atc.DOM.createElement("div", {className:"as_bar"});
	var header = _atc.DOM.createElement("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	var ul = _atc.DOM.createElement("ul", {id:"as_ul"});
	for (var i=0;i<arr.length;i++)
	{
		var val = arr[i];
		var output = val.GetDisplayString();
		
		var span = _atc.DOM.createElement("span", {}, output, true);
		var a = _atc.DOM.createElement("a", { href:"#" });
		
		var tl = _atc.DOM.createElement("span", {className:"tl"}, " ");
		var tr = _atc.DOM.createElement("span", {className:"tr"}, " ");
		
		a.appendChild(tl);
		a.appendChild(tr);
		a.appendChild(span);
		
		var subdiv = _atc.DOM.createElement("div", {id:"subDiv"}, "", true);
		subdiv.style.display = "none";
		
		var li = _atc.DOM.createElement("li", {});
		li.appendChild(a);
		li.appendChild(subdiv)
		
		ul.appendChild(li);
		
		a.name = i + 1;
		if(val._subitems == null)
		{
		    a.onclick = function () { pointer.setHighlightedValue(); return false; }
    		a.onmouseover = function () { pointer.setHighlight(this.name); }
		}
	    else
	    {
    		a.onmouseover = function () { pointer.setHighlight(this.name); }
    		this.buildSubitems(a.name, ul);
    		a.onclick = function() { pointer.expand(this.name); }
	    }	
	}
	
	if (arr.length == 0)
	{
		var lix = _atc.DOM.createElement("li", {className:"as_warning"}, this.oP.noresults);
		ul.appendChild( lix );
	}
	
	div.appendChild( ul );
	
	var fcorner = _atc.DOM.createElement("div", {className:"as_corner"});
	var fbar = _atc.DOM.createElement("div", {className:"as_bar"});
	var footer = _atc.DOM.createElement("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	var pos = _atc.DOM.getPos(this.fld);
	
	div.style.left = pos.x + "px";
	div.style.top = ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	
	if(this.fld.offsetWidth > 100)	
	    div.style.width = this.fld.offsetWidth + "px";
	else
	    div.style.width = "240px";
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	div.onmouseover = function(){ pointer.killTimeout() }
	div.onmouseout = function(){ pointer.resetTimeout() }

	// add DIV to document
	document.getElementsByTagName("body")[0].appendChild(div);
	
	// currently no item is highlighted
	this.iHighlighted = 0;
	
	// remove list after an interval
	var pointerx = this;
	
	this.toID = setTimeout(function () { pointerx.clearSuggestions() }, this.oP.timeout);
}

_atc.AutoSuggest.prototype.changeHighlight = function(key)
{	
	var list = _atc.DOM.getElement("as_ul");
	if (!list)
		return false;
	
	var n;
    var m;
    
	var hasVisibleSubItems = this.iHighlighted != 0 && list.childNodes[this.iHighlighted - 1].childNodes[1].style.display != "none";
    
	if (key == 40)
	{
	    if(this.iHighlighted != 0 && hasVisibleSubItems)
	    {
	        if(this.iSubHighlighted == this.aSuggestions[this.iHighlighted - 1].aSubSuggestions.length)
	        {
    	        this.setHighlight(this.iHighlighted + 1);
	        }
	        else
	        {
	            this.iSubHighlighted++;
	            this.setSubHighlight(this.iHighlighted.toString() + "_" + this.iSubHighlighted.toString());
	        }
	    }
	    else
	    {
	        this.setHighlight(this.iHighlighted + 1);
	    }
	}
	else if (key == 38)
	{
	    if(this.iHighlighted != 0 && hasVisibleSubItems)
	    {
	        if(this.iSubHighlighted == 1)
	        {
    	        this.setHighlight(this.iHighlighted);
	        }
	        else if(this.iSubHighlighted == 0)
	        {
    	        this.setHighlight(this.iHighlighted - 1);
	        }
	        else
	        {
        	    this.iSubHighlighted--;
	            this.setSubHighlight(this.iHighlighted.toString() + "_" + this.iSubHighlighted.toString());
	        }
	    }
	    else
	    {
	        this.setHighlight(this.iHighlighted - 1);
	    }
	}
}

_atc.AutoSuggest.prototype.setHighlight = function(index)
{
	var list = _atc.DOM.getElement("as_ul");
	var n = Number(index);
    
    if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;

	var listx = _atc.DOM.getElement("as_ul");
	if (!listx)
		return false;
	
	if (this.iHighlighted > 0)
		this.clearHighlight();
	
	this.iHighlighted = n;
	this.iSubHighlighted = 0;
	
	listx.childNodes[this.iHighlighted-1].className = "as_highlight";
	this.killTimeout();
}

_atc.AutoSuggest.prototype.setSubHighlight = function(n)
{
	var list = _atc.DOM.getElement("as_ul");
	if (!list)
		return false;
	
	if (this.iHighlighted > 0)
		this.clearHighlight();

	var numbers = n.split("_");
	this.iHighlighted = Number(numbers[0]);
	this.iSubHighlighted = Number(numbers[1]);

	var subdiv = list.childNodes[this.iHighlighted-1].childNodes[1];
	var ul = subdiv.childNodes[0];
	//TODO: set style ul.childNodes[this.iSubHighlighted-1].style.backgroundColor = "red";
	this.killTimeout();
}

_atc.AutoSuggest.prototype.expand = function(n)
{
    var pointer = this;
    var list = _atc.DOM.getElement("as_ul");
	if (!list)
		return false;

    var index = Number(n);
    var toggled = false;
    	
	// hide subitems
	for(var i = 0; i < this.aSuggestions.length; i++)
	{
	    var subdiv = list.childNodes[i].childNodes[1];
	    if(subdiv.style.display != "none" && index -1 == i) toggled = true;
	    subdiv.style.display = "none";
	}
	
	if(toggled) return;
   
    var subdivx = list.childNodes[index-1].childNodes[1];
	subdivx.style.display = "block";
	this.killTimeout();
}

_atc.AutoSuggest.prototype.clearHighlight = function()
{
	var list = _atc.DOM.getElement("as_ul");
	if (!list)
		return false;
	
	if (this.iHighlighted > 0)
	{
		list.childNodes[this.iHighlighted-1].className = "";
		this.iHighlighted = 0;
	}
}

_atc.AutoSuggest.prototype.setHighlightedSubValue = function(n)
{
	var list = _atc.DOM.getElement("as_ul");
	if (!list) return false;
	
	if (this.iHighlighted)
	{
	    var numbers = n.split("_");
	    var index = Number(numbers[1]);
	    this.sInput = this.fld.value = this.aSuggestions[this.iHighlighted - 1].aSubSuggestions[index-1].GetValue();
	}
	
	// move cursor to end of input (safari)
    this.fld.focus();
    if (this.fld.selectionStart)
        this.fld.setSelectionRange(this.sInput.length, this.sInput.length);

    this.clearSuggestions();
}


_atc.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHighlighted && this.aSuggestions.length > 0 && this.aSuggestions.length > 0)
	{
	    if(this.aSuggestions[this.iHighlighted - 1].aSubSuggestions != null && this.aSuggestions[this.iHighlighted - 1].aSubSuggestions.length > 0)
	    {
	        if(this.iSubHighlighted)
	        {
	            this.setValue(this.aSuggestions[this.iHighlighted - 1].aSubSuggestions[this.iSubHighlighted - 1].GetValue());
	            
                // pass selected object to callback function, if exists
                if (typeof(this.oP.callback) == "function")
	                this.oP.callback( this.aSuggestions[this.iHighlighted-1], this.aSuggestions[this.iHighlighted - 1].aSubSuggestions[this.iSubHighlighted - 1] );
	        }
	        else
	        {
	            this.expand(this.iHighlighted);
	        }
	    }
	    else
	    {
	        this.setValue(this.aSuggestions[ this.iHighlighted-1 ].GetValue());
	        
            // pass selected object to callback function, if exists
            if (typeof(this.oP.callback) == "function")
	            this.oP.callback( this.aSuggestions[this.iHighlighted-1] );	      
	    }
	}
}

_atc.AutoSuggest.prototype.setValue = function(val)
{
    this.sInput = this.fld.value = val;
    		
    // move cursor to end of input (safari)
    this.fld.focus();
    if (this.fld.selectionStart)
	    this.fld.setSelectionRange(this.sInput.length, this.sInput.length);

    this.clearSuggestions();
}

_atc.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
}

_atc.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
}

_atc.AutoSuggest.prototype.clearSuggestions = function ()
{
	this.killTimeout();
	
	var ele = _atc.DOM.getElement(this.idAs);
	var pointer = this;
	if (ele)
	{
		var fade = new _atc.Fader(ele,1,0,250,function () { _atc.DOM.removeElement(pointer.idAs) });
	}
}

// DOM PROTOTYPE _____________________________________________


if (typeof(_atc.DOM) == "undefined")
	_atc.DOM = {}

_atc.DOM.createElement = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return false;
		
	for (var a in attr)
		ne[a] = attr[a];
		
	if (typeof(cont) == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (typeof(cont) == "string" && html)
		ne.innerHTML = cont;
	else if (typeof(cont) == "object")
		ne.appendChild( cont );

	return ne;
}

_atc.DOM.clearElement = function ( id )
{
	var ele = this.getElement( id );
	
	if (!ele)
		return false;
	
	while (ele.childNodes.length)
		ele.removeChild( ele.childNodes[0] );
	
	return true;
}


_atc.DOM.removeElement = function ( ele )
{
	var e = this.getElement(ele);
	
	if (!e)
		return false;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return false;
}

_atc.DOM.replaceContent = function ( id, cont, html )
{
	var ele = this.getElement( id );
	
	if (!ele)
		return false;
	
	this.clearElement( ele );
	
	if (typeof(cont) == "string" && !html)
		ele.appendChild( document.createTextNode(cont) );
	else if (typeof(cont) == "string" && html)
		ele.innerHTML = cont;
	else if (typeof(cont) == "object")
		ele.appendChild( cont );
}


_atc.DOM.getElement = function ( ele )
{
	if (typeof(ele) == "undefined")
	{
		return false;
	}
	else if (typeof(ele) == "string")
	{
		var re = document.getElementById( ele );
		if (!re)
			return false;
		else if (typeof(re.appendChild) != "undefined" ) {
			return re;
		} else {
			return false;
		}
	}
	else if (typeof(ele.appendChild) != "undefined")
		return ele;
	else
		return false;
}

_atc.DOM.appendChildren = function ( id, arr )
{
	var ele = this.getElement( id );
	
	if (!ele)
		return false;
	
	if (typeof(arr) != "object")
		return false;
		
	for (var i=0;i<arr.length;i++)
	{
		var cont = arr[i];
		if (typeof(cont) == "string")
			ele.appendChild( document.createTextNode(cont) );
		else if (typeof(cont) == "object")
			ele.appendChild( cont );
	}
}

_atc.DOM.getPos = function ( ele )
{
	var xele = this.getElement(ele);

	var obj = xele;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;


	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop}
}

// FADER PROTOTYPE _____________________________________________

if (typeof(_atc.Fader) == "undefined")
	_atc.Fader = {}

_atc.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return false;
	
	this.ele = ele;
	
	this.from = from;
	this.to = to;
	
	this.callback = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
}

_atc.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
	var op = ieop / 100;
	
	if (this.ele.filters) // internet explorer
	{
		try
		{
			this.ele.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.ele.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.ele.style.opacity = op;
	}
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.callback != undefined)
			this.callback();
	}
}

_atc.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
}


/* ************************************* End generic autocomplete *****************************/