// JavaScript Document
// pl - prompt list

overInput = 0;
overDiv = 0;
objectsEditValue = '';

function pl_showHideIFrame(field, prefix, state, divRef)
{
	var browser = navigator.appName;
	var el = document.getElementById('promt_list_place_for_iframe');
	if (state)
	{
		if (browser == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') == -1)
		{
			var ifr_id = prefix+field+'_divShim';
			el.innerHTML = '<iframe id="'+ifr_id+'" style="position: absolute;  width: 1px; height: 1px; z-index: 2;" frameborder="no" scrolling="no"></iframe>';
			var ifrRef = document.getElementById(ifr_id);
			ifrRef.style.top = divRef.style.top;
			ifrRef.style.left = divRef.style.left;
			ifrRef.style.width = divRef.offsetWidth;
			ifrRef.style.height = divRef.offsetHeight;
		}
	}
	else {
		if (browser == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') == -1){
			el.innerHTML = '';
		}
	}
}

/*
function pl_getMainDiv()
{
	var div = null;
	// get main edit popup div
	// where id for this div match /_fieldsDiv$/
	var allDivs = document.getElementsByTagName("div");
	for (var i=0; i<allDivs.length; i++){
	    div = allDivs[i];
	    if (div.id.match(/_fieldsDiv$/)){
	    	return div;
	    	break;
	    }
	}	
}	*/
/*
function pl_getToolbarOffsetHeight()
{
	var obj = pl_getMainDiv();
	var toolbarHeight = 0;
	// get offsetHeight sum for all tables before main edit popup's fields Div
	if (obj.previousSibling){
		while (obj.previousSibling){
			if (obj.previousSibling.nodeName.toLowerCase()=='table'){
				toolbarHeight += obj.previousSibling.offsetHeight;
			}
			obj = obj.previousSibling;
		}
	}
	return toolbarHeight;
}	*/
/*
function pl_resetObjectsListTopPos(field, prefix)
{
	var _objectsEdit = document.getElementsByName(field)[0];
	
	var posleft = findPosX(_objectsEdit);
	var postop = findPosY(_objectsEdit);
	var _objectsList = document.getElementById(prefix+field+'_prompt_list_objects_listing');
	
	var browser = navigator.appName;
	
	if (browser == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') == -1)
	{
		// do nothing
	}
	else {
		postop = postop - pl_getMainDiv().scrollTop + _objectsEdit.offsetHeight;
		_objectsList.style.top = postop+'px';
	}
}	*/

function pl_getAjaxLoaderPath()
{
	return base_path + '/c/i/ajax-loader.gif';
}

function pl_showList(field, prefix, suggest_field)
{
	var _objectsEdit = document.getElementsByName(field)[0];
	
	var posleft = findPosX(_objectsEdit);
	var postop = findPosY(_objectsEdit);
	var _objectsList = document.getElementById(prefix+field+'_prompt_list_objects_listing');
	
	var browser = navigator.appName;
	
	if (browser == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') == -1){
		postop = postop + _objectsEdit.offsetHeight;
	} else {
		postop = postop + _objectsEdit.offsetHeight;
	}
	
	_objectsList.style.left = posleft+'px';
	_objectsList.style.top = postop+'px';
	_objectsList.style.display = 'block';
	_objectsList.style.width = _objectsEdit.offsetWidth+'px';
	
	orig_w = _objectsEdit.offsetWidth;
	
	if (!eval(prefix+field+suggest_field+'_loaded'))
	{
		_objectsList.innerHTML = '<img src="'+pl_getAjaxLoaderPath()+'" alt="Loading..." align="absmiddle" /> Loading...';
		pl_showHideIFrame(field, prefix, true, _objectsList);
	}
	else {
	//	if (_objectsEdit.value != objectsEditValue)
		_objectsList.style.padding = "0"; // clear init padding
		pl_rebuildList(field, prefix, _objectsList, _objectsEdit.value, suggest_field);
		objectsEditValue = _objectsEdit.value;
	}
}

function pl_rebuildList(field, prefix, list, val, suggest_field)
{
	var list_html = '';
	var div_prop = 'onMouseOver="this.style.backgroundColor = '+"'"+'#000077'+"'"+'; this.style.color = '+"'"+'#FFFFFF'+"'"+';" onMouseOut="this.style.backgroundColor = '+"'"+'#FFFFFF'+"'"+'; this.style.color = '+"'"+'#000000'+"'"+';" onClick="pl_setEditValue('+"'"+field+"', '"+prefix+"', "+'this.innerHTML)"';
	var div_prop_with_no_color = ' onClick="pl_setEditValue('+"'"+field+"', '"+prefix+"', "+'this.innerHTML)"';
	reg_val = val;
	reg_val = reg_val.replace(/[āa]/gi,'[āa]');
	reg_val = reg_val.replace(/[čc]/gi,'[čc]');
	reg_val = reg_val.replace(/[ēe]/gi,'[ēe]');
	reg_val = reg_val.replace(/[ģg]/gi,'[ģg]');
	reg_val = reg_val.replace(/[īi]/gi,'[īi]');
	reg_val = reg_val.replace(/[ķk]/gi,'[ķk]');
	reg_val = reg_val.replace(/[ļl]/gi,'[ļl]');
	reg_val = reg_val.replace(/[ņn]/gi,'[ņn]');
	reg_val = reg_val.replace(/[šs]/gi,'[šs]');
	reg_val = reg_val.replace(/[ūu]/gi,'[ūu]');
	reg_val = reg_val.replace(/[žz]/gi,'[žz]');
	reg_val = reg_val.replace(/\"/gi,'[\"(&quot;)]');
	reg_val = reg_val.replace(/\\/gi,'');
	reg_val = reg_val.replace(/\//gi,'');
	if ((Number(reg_val)).toString() == reg_val)
		regex = eval('/^([A-Z0-9\.]{1,4} )?'+reg_val+'|'+reg_val+'([A-Z0-9\/\.]{1,4})?$/gi');
	else
		regex = eval('/^([A-Z0-9\.]{1,4} )?'+reg_val+'/gi');
	
	var _array = eval(prefix+field+suggest_field+'_aTitles');
	_array = pl_clearPrototype(_array, 'string');
	
	var c = -1; // counter
	for (var i in _array){
		var style = 'white-space:nowrap; width:'+parseInt(list.style.width)+'px; overflow:hidden; ';
		if (val != ''){
		//	alert('_array[i]='+_array[i]+', regex='+regex);
			if (_array[i].match(regex)){
				++c;
				if (c == cur_pos){
					style += ' background-color:#000077; color:#ffffff;';
					cur_value = _array[i];
				}
				style += ' line-height:'+line_h+'px;';
				var style_attrib = ' style="'+style+'"';
				list_html += '<div '+div_prop+' '+style_attrib+'>' + _array[i] + '</div>';
			}
		}
		else {
			++c;
			if (c == cur_pos){
				style += ' background-color:#000077; color:#ffffff;';
				cur_value = _array[i];
			}
			style += ' line-height:'+line_h+'px;';
			var style_attrib = ' style="'+style+'"';
			list_html += '<div '+div_prop+' '+style_attrib+'>' + _array[i] + '</div>';
		}
	}
	cur_count = c + 1;
	
	if(list_html == '')
	{
		pl_hideList(field, prefix, true);
	}
	else {
	/*	if (cur_count < max_lines){
			list.innerHTML = list_html;
		} else {*/
			//list.innerHTML = '<div style="border:1px solid #ff0000; width:'+parseInt(list.style.width)+'px;">'+list_html+'</div>';
			list.innerHTML = list_html;
			var old_list_w = parseInt(list.style.width);
			
			if (cur_count < max_lines){
				list.style.width = orig_w + 'px';
				if (is_msie())
					list.style.overflow = 'hidden';
			} else {
				list.style.width = orig_w + 17 + 'px';
				if (is_msie())
					list.style.overflowY = 'auto';
			}
	//	}
		
		if (dir == 'up'){
			if (cur_pos > -1 && cur_pos_in_box < 0){
				list.scrollTop -= line_h;
			}
		}
		else if (dir == 'down'){
			if (cur_pos >= max_lines && cur_pos_in_box+1 >= max_lines){
				list.scrollTop += line_h;
			}
		}
		list.style.height = ((cur_count < max_lines) ? cur_count : max_lines) * line_h + "px";
		pl_showHideIFrame(field, prefix, true, list);
	}
	//rewriteLog(prefix, field);
}

function pl_setEditValue(field, prefix, val)
{
	var _objectsEdit = document.getElementsByName(field)[0];
	_objectsEdit.value = val;
	overDiv = 0;
	pl_hideList(field, prefix);
}

function pl_hideList(field, prefix, always)
{
	if (typeof always == "undefined")
		always = false;
	
	if (!(overInput || overDiv) || always)
	{
		var _objectsList = document.getElementById(prefix+field+'_prompt_list_objects_listing');
		_objectsList.style.display = 'none';
		pl_showHideIFrame(field, prefix, false, _objectsList)
	}
}

function pl_preProcessEnter(field, prefix)
{
	if (cur_pos == -1){
		cur_value = document.getElementsByName(field)[0].value;
	}
	pl_setEditValue(field, prefix, cur_value);
	submitted = true;
}

dir = '';	// direction: "up", "down" or not.
cur_pos = -1;
cur_pos_in_box = -1;
cur_count = 0;
cur_value = '';
submitted = false;
s = 0;	// scroll top
line_h = 14;
max_lines = 7;

function pl_resetValues(div_obj)
{
	cur_pos = -1;
	cur_pos_in_box = -1;
	cur_count = 0;
	submitted = false;
	div_obj.scrollTop = 0;
}

function pl_moveUp(prefix, field_name)
{
	--cur_pos;
	if (cur_pos < -1) cur_pos = -1;
	
	--cur_pos_in_box;
	if (cur_pos_in_box < -1) cur_pos_in_box = -1;
}

function pl_moveDown(prefix, field_name)
{
	++cur_pos;
	if (cur_pos > cur_count-1) cur_pos = cur_count-1;
	
	++cur_pos_in_box;
	if (cur_pos_in_box > max_lines-1) cur_pos_in_box = max_lines-1;
}

function rewriteLog(prefix, field)
{
	var _objectsList = document.getElementById(prefix+field+'_prompt_list_objects_listing');
	window.status = "cur_pos="+cur_pos+", cur_count="+cur_count+", s="+s+", cur_pos_in_box="+cur_pos_in_box+", list.scrollTop="+_objectsList.scrollTop;
}

function pl_initSuggestions(prefix, field_name, suggest_field)
{
	if (!eval(prefix+field_name+suggest_field+'_loaded') && !eval(prefix+field_name+suggest_field+'_ajaxStarted'))
	{
		eval(prefix+field_name+suggest_field+'_ajaxStarted = true;');
		var uri = base_path+'/ajax_server_scripts/get_suggestions.php?field='+suggest_field;
		asyncRequest("GET", uri, function(xhr)
		{
			eval(prefix+field_name+suggest_field+'_aTitles = '+xhr.responseText);
			eval(prefix+field_name+suggest_field+'_loaded = true;');
			pl_showList(field_name, prefix, suggest_field);
		});
	}
}

function pl_init(prefix, field_name, suggest_field)
{
	if (document.getElementById('promt_list_place_for_iframe') == null)
	{
		var span_obj = document.createElement("SPAN");
		span_obj.setAttribute("id", "promt_list_place_for_iframe");
		document.body.appendChild( span_obj );
	}
	
	eval(prefix+field_name+suggest_field+'_loaded = false;');
	eval(prefix+field_name+suggest_field+'_ajaxStarted = false;');
	
	if (typeof ajaxLoader == "undefined")
	{
		var ajaxLoader = new Image();
		ajaxLoader.src = pl_getAjaxLoaderPath();
	}
	
	var div_obj = document.createElement("DIV")
	div_obj.setAttribute("id", prefix+field_name+"_prompt_list_objects_listing")
	with (div_obj.style){
		position="absolute"; display="none"; width="350px";
	//	height=(line_h*max_lines)+"px";
		padding="5px";
		backgroundColor="#FFFFFF"; border="1px solid #666666"; zIndex="3"; overflow="auto"; textAlign="left";
		cursor="default";
	}
	addEvent(div_obj, 'mouseover', function(){
										overDiv=1;
									 })
	addEvent(div_obj, 'mouseout', function(){
										overDiv=0;
										if (typeof(hide_timeout) != 'undefined')
											clearTimeout(hide_timeout);
										hide_timeout = setTimeout('pl_hideList(\''+field_name+'\', \''+prefix+'\')', 1000);
									 })
	document.body.appendChild( div_obj );
	
	var input_box = document.kernel_form.elements[field_name];
	if (typeof input_box == "undefined"){
		var input_box = document.getElementById('search_form').elements[field_name];
	}

	input_box.setAttribute("AUTOCOMPLETE", "off");
	
	addEvent(input_box, 'focus', function(){
										pl_initSuggestions(prefix, field_name, suggest_field);
									 })
	addEvent(input_box, 'click', function(){
										pl_initSuggestions(prefix, field_name, suggest_field);
										pl_showList(field_name, prefix, suggest_field);
									 })
	addEvent(input_box, 'keydown', function(oEvent){
										oEvent = window.event || oEvent;
										iKeyCode = oEvent.keyCode;
										switch(iKeyCode){
											case 38: // up arrow
													pl_moveUp(prefix, field_name);
													dir = 'up';
												break;
											case 40: // down arrow
													pl_moveDown(prefix, field_name);
													dir = 'down';
												break;
											case 13:
													overInput = overDiv = 0;
												break;
											default:
													pl_resetValues(div_obj);
													dir = '';
												break;
										}
									 })
	addEvent(input_box, 'keyup', function(){
										if (submitted)
											pl_hideList(field_name, prefix);
										else
											pl_showList(field_name, prefix, suggest_field);
									 })
	addEvent(input_box, 'blur', function(){
										overInput=0;
										pl_hideList(field_name, prefix);
									 })
	addEvent(input_box, 'mouseover', function(){
										overInput=1;
									 })
	addEvent(input_box, 'mouseout', function(){
										overInput=0;
									 })
}


function pl_clearPrototype(obj, need_type)
{
	if (typeof obj.each == "function") {	// it's prototype framework
		var o = {};
		for (var i in obj){
			if (typeof(obj[i]) == need_type){
				var k = i.match(/^[0-9]/) ? "_"+i : i;
				eval("o."+k+" = '"+obj[i]+"';")
			}
		}
		return o;
	} else {
		return obj;
	}
}
