// JavaScript Document
var i = window.document.getElementById("item_no");
var q = window.document.getElementById("item_qty");
var drop_down = window.document.getElementById("drop_box");
var l = window.document.getElementById("list_script");
var selectedItem = false;
var done = false;
var o = false;

addListener(i, 'keydown', checkKey, true);

window.drop_down.style.width = 450 + 'px';

var last_value = '';

setTimeout ( "checkItem()", 400 );

function run_it()
{
	if(window.o)
	{
		document.body.removeChild(window.o);
	}
	
	window.o = document.createElement('script');
	window.o.id = 'dropscript';
	window.o.src = '/list.php?item_no=' + window.i.value;
	window.o.type = 'text/javascript';
	window.o.language = 'javascript';
	document.body.appendChild(window.o);
}

function checkItem()
{	
	if(window.i.value != window.last_value)
	{
		window.selectItem(false);
		window.done = false;
		window.run_it();
		window.drop_down.style.left = input_x(window.i) + 'px';
		window.drop_down.style.top = input_y(window.i) + 'px';
		window.last_value = window.i.value;
	}
	setTimeout ( "checkItem()", 400 );
}

function input_x (ox) { 
	var par = ox;
	var x = ox.offsetLeft - 3;
	while(par){
		  x += parseInt(par.offsetLeft);
		  par = par.offsetParent;
	}
	return x;
}

function input_y (oy) { 
	var par = oy;
	var y = oy.offsetHeight - 2;
	while(par){
		  y += parseInt(par.offsetTop);
		  par = par.offsetParent;
	}
	return y;
}

function addListener(element, type, expression, bubbling)
{
	bubbling = bubbling || false;
	if(window.addEventListener)
	{
		element.addEventListener(type, expression, bubbling);
		return true;
	}
	else if(window.attachEvent)
	{
		element.attachEvent('on' + type, expression);
		return true;
	}
	else return false;
}

function checkKey(e)
{
	if(e.keyCode == 40)
	{
		if(window.selectedItem != false)
		{
			p = window.selectedItem.id.split('_');
			d = document.getElementById('drop_item_' + (parseInt(p[2])+1));
		}
		else
		{
			d = document.getElementById('drop_item_1');
		}
		
		selectItem(d);
	}
	if(e.keyCode == 38)
	{
		if(window.selectedItem != false)
		{
			p = window.selectedItem.id.split('_');
			d = document.getElementById('drop_item_' + (parseInt(p[2])-1));
		}
		else
		{
			d = document.getElementById('drop_item_');
		}
		
		selectItem(d);
	}
	if(e.keyCode == 13)
	{
		window.useSelectedItem();
		window.q.select();
		return false;
	}
	
}

function selectItem(si)
{
	if(window.selectedItem)
	{
		window.selectedItem.className = 'drop_item';
	}
	
	if(si)
	{
		si.className = 'drop_item_selected';
		window.selectedItem = si;
	}
	else
	{
		window.selectedItem = false;	
	}
}

function useSelectedItem()
{
	if(window.selectedItem !== false)
	{
		window.i.value = window.selectedItem.childNodes[0].innerHTML;
		window.last_value = window.i.value;
		window.drop_down.style.visibility = 'hidden';
	}
}