var current_key_code = 0;
var partial_response_http_request;
var current_partial_edit_obj = null;
var previous_partial_search_value = '';
var partial_result_count;
var partial_result_array= new Array();
var current_partial_selection_index = 0;
var partial_list_visible = false;
var partial_query_active = false;
var current_partial_search_media = 1;
var current_partial_search_table = 'author';
var partial_fetch_timer = null;

function partial_fill_utf_encode(str) 
{
str = str.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < str.length; n++) 
	{
  var c = str.charCodeAt(n);
  if (c < 128) 
  	{
    utftext += String.fromCharCode(c);
  	}
  else if((c > 127) && (c < 2048)) 
  	{
    utftext += String.fromCharCode((c >> 6) | 192);
    utftext += String.fromCharCode((c & 63) | 128);
  	}
  else 
  	{
    utftext += String.fromCharCode((c >> 12) | 224);
    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
    utftext += String.fromCharCode((c & 63) | 128);
  	}
	}
return utftext;
}

function partial_fill_utf_decode(utftext) 
{
if(utftext == null) 
	return '';
if(utftext == undefined)
	return '';
if(utftext.length == 0)
	return '';
//return utftext;
var str = "";
var i = 0;
var c = c1 = c2 = 0;
if(utftext == null)
	return '';
while ( i < utftext.length ) 
	{

	c = utftext.charCodeAt(i);
	
	if (c < 128) 
		{
    str += String.fromCharCode(c);
    i++;
		}
	else if((c > 191) && (c < 224)) 
		{
    c2 = utftext.charCodeAt(i+1);
    str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
    i += 2;
		}
	else 
		{
		c2 = utftext.charCodeAt(i+1);
		c3 = utftext.charCodeAt(i+2);
		str += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
		i += 3;
		}
	}
return str;
}

function replace_str(str, search, replace)
{
	var i;
	var arr = str.split(search);
	str = '';
	for(i = 0; i < arr.length; ++i)
		{
		str += arr[i];
		if(i != arr.length-1)
			{
			str += replace;
			}
		}
	return str;
}

function partial_result_handle_response()
{
if(partial_response_http_request != null)
	{
	if(partial_response_http_request.readyState == 4)
		{
		var str = partial_response_http_request.responseText;
		var response = str.split("|");
		//alert(str);
		partial_query_active = false;
		if(response[1] != "error")
			{
			response.shift();
			response = decode_partial_fill_data(response);
			partial_result_array = response.slice();
			show_partial_fill_help(response);
			}
		else
			{
			alert(response[2]);
			}
		}
	}
}

function decode_partial_fill_data(response)
{
var i;
for(i = 0; i < response.length; ++i)
	{
	response[i] = partial_fill_utf_decode(response[i]);
	}
return response;
}

function show_partial_fill_help(data_array)
{
var partial_search = data_array.shift();
var count = data_array.shift()*1;
var control_id = data_array.shift();
var i;
var str = '';
var author_name;
var part1, part2;
var partial_length;

//alert(control_id);
if(control_id.length != 0)
	{
	var obj = document.getElementById(control_id);
	if(obj != null)
		{
		obj.style.background = '#FFFFFF';
		}
	if(current_partial_edit_obj == null)
		{
		return;
		}
	if(current_partial_edit_obj.id != control_id)
		{
		return;
		}
	}
else
	{
	if(current_partial_edit_obj == null)
		{
		return;
		}
	}	
var elem = document.getElementById('partial_list');
if(elem == null)
	{
	return;
	}

partial_result_count = count;
if(current_partial_edit_obj == null || count == 0)
	{
	elem.style.visibility='hidden';
	return;
	}
str = get_current_partial_edit_str()
//if(partial_search != str)
//{
	//if(str.length > 3)
	//	fetch_partial_result_item(str);
	//else
//	elem.style.visibility='hidden';
//	return;
//	}
partial_search = str;
partial_length = partial_search.length;
if(count == 1 && partial_search == data_array[0])
	{
	elem.style.visibility='hidden';
	return;
	}
str = '';
for(i = 0; i < count; ++i)
	{
	if(i == 0)
		{
		str += '<table style="font-family: arial; font-weight: normal;" border="0" cellpadding="0" cellspacing="0">\n';
		}
	author_name = (replace_str(data_array[i],',',''));
	//author_name = replace_str(author_name,' ','&nbsp;');
	part1 = author_name.substring(0, partial_length);
	part2 = author_name.substring(partial_length);
	part1 = replace_str(part1, ' ','&nbsp;');
	part2 = replace_str(part2, ' ','&nbsp;');


	str += '<tr align="left"><td>\n';
	str += '<span style="font-size: 10pt; font-family: arial; cursor: pointer; cursor: hand;" onclick="special_partial_result_selection(13)" onmouseover="show_partial_result_selection('+i+')" id="partial_help_'+i+'_index">\n';
	str += '<span style="color: green;">&nbsp;'+part1+'</span>';
	str += '<span style="color: red;">'+part2+'&nbsp;</span>';
	str += '</span>\n';
	str += '</td></tr>\n';

	if(i == count - 1)
		{
		str += '</table>\n';
		}
	}
var x,y;
x = findPosX(current_partial_edit_obj);
y = findPosY(current_partial_edit_obj);
elem.style.visibility= 'visible';
elem.style.left = x;
elem.style.top = y + 25;
//Elem = document.getElementById('partial_list_body');
elem.innerHTML = str;
setTimeout('show_partial_result_selection(0);', 10);
partial_list_visible = true;
}

function create_partial_fill_ajax_object()
{
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
	{
	browser_type_ie = 1;
	}
else
	{
 	browser_type_ie = 0;
	}
if(browser_type_ie == 1)
	{
	    ro = new ActiveXObject("Microsoft.XMLHTTP");
	}else
	{
	    ro = new XMLHttpRequest();
	}
	return ro;
}

function fetch_partial_result_item(search_str1)
{
	if((search_str1 != previous_partial_search_value) && partial_query_active == false)
		{
		var control_id = (current_partial_edit_obj!=null)?current_partial_edit_obj.id:'';
		var search_str = escape(partial_fill_utf_encode(search_str1));
		var rqst_str = 'http://www.gurulib.com/_rpc1.php?action=fetch_partial_result&table='+current_partial_search_table+'&media='+current_partial_search_media + "&search="+search_str+"&id="+control_id+"&"+Math.random();

		//alert(rqst_str);
		partial_response_http_request = create_partial_fill_ajax_object();
		partial_response_http_request.open('get', rqst_str);
		partial_response_http_request.onreadystatechange = partial_result_handle_response;
		partial_response_http_request.send(null);
		previous_partial_search_value = search_str1;
		partial_query_active = true;
		if(current_partial_edit_obj != null)
			{
			//current_partial_edit_obj.style.border = '1px dashed yellow';
			//current_partial_edit_obj.readOnly = true;
			current_partial_edit_obj.style.background = '#BFDFFF';
			}
		}
}

function get_partial_result_key_code(evnt)
{
if (document.all)
	{
	return evnt.keyCode*1;
	}
 else if (document.getElementById)
	{
	return evnt.which*1;
	}
 else if(document.layers)
	{
	return evnt.which*1;
	}
}

function get_partial_result_selection(index)
{
var count = partial_result_array[1]*1;
for(i = 0; i < count; ++i)
	{
	if(i == index)
		{
		return replace_str(partial_result_array[3 + i],',','');
		}
	}
return null;
}

function show_partial_result_selection(index)
{
	var elem;
	var i = 0;
	var id;
	current_partial_selection_index = index;
	while(1)
		{
		//str += '<span style="text-decoration: underline; background: #AAAA77;" >\n';
		id = 'partial_help_'+i+'_index';
		elem = document.getElementById(id);
		if(elem == null)
			break;
		if(i == index)
			{
			elem.style.textDecoration='underline';
			elem.style.background='#DDDDAA';
			}
		else
			{
			elem.style.textDecoration='none';
			elem.style.background='';
			}
		++i;
		}
}

function handle_partial_fill_arrow_keys(key_code)
{
var not_handled = true;
if(partial_list_visible == true)
	{
	switch(key_code)
		{
		case 40: //DOWN
			if(current_partial_selection_index == partial_result_count-1)
				return;
			show_partial_result_selection(++current_partial_selection_index);
			not_handled = false;
			break;
		case 38: //UP
			if(current_partial_selection_index == 0)
				return;
			show_partial_result_selection(--current_partial_selection_index);
			not_handled = false;
			break;
		case 9:
		case 13:
		case 27:
		//scase 188:
			not_handled = false;
			special_partial_result_selection(key_code);
			break;
		}
	}
return not_handled;
}

function special_partial_result_selection(key_code)
{
var not_handled = true;
if(partial_list_visible == true)
	{
	switch(key_code)
		{
		case 9: //tab
		case 13: //ENTER
			if(current_partial_edit_obj != null)
				{
				var str = get_partial_result_selection(current_partial_selection_index);
				if(str != null)
					{
					set_current_partial_edit_str(str);
					}				
				}
				hide_partial_result_list();
				not_handled = false;
			break;

		case 27:	//ESC
			hide_partial_result_list();
			not_handled = false;
			break;
		
		case 38:
		case 40:
		case 188:
		case 37:
		case 39:
			not_handled = false;
			break;
		}
	}
return not_handled;
}

function hide_partial_result_list()
{
var elem = document.getElementById('partial_list');
if(elem == null)
	{
	return;
	}
elem.style.visibility='hidden';
partial_list_visible = false;
}

function get_current_partial_edit_str()
{
if(current_partial_edit_obj == null)
	return '';
var str = current_partial_edit_obj.value;
var arr = str.split(',')
return ltrim(arr[arr.length-1]);
}

function set_current_partial_edit_str(str)
{
var control_id = partial_result_array[2];
//alert(control_id);
var current_partial_edit_obj = document.getElementById(control_id);
if(current_partial_edit_obj == null)
	return '';
var i;
var str1 = current_partial_edit_obj.value;
var arr = str1.split(',')
str1 = '';
for(i = 0; i < arr.length-1; ++i)
	{
	str1 += arr[i] + ',';
	}
var last_entry = trim(arr[arr.length-1].toLowerCase());
var new_entry = trim(str.toLowerCase());
var index = new_entry.indexOf(last_entry);
//alert(index + "," + new_entry + "," + last_entry);

if(index != -1)
	{
	str1 += str;
	current_partial_edit_obj.value = str1;
	fire_event(current_partial_edit_obj, "change");
	}
var pos = str1.length;
if(current_partial_edit_obj.createTextRange)
	{
	var range = current_partial_edit_obj.createTextRange();
	range.move("character", pos);
	range.select();
  }
else if(current_partial_edit_obj.selectionStart)
	{
  current_partial_edit_obj.focus();
  current_partial_edit_obj.setSelectionRange(pos, pos);
	
	var keyCode = 32;
	var charCode = 32;
	var evt = document.createEvent('KeyboardEvent');
  evt.initKeyboardEvent('keypress',true,true,null,false,false,false,false,keyCode,charCode);
  /*if(typeof(evt.initKeyboardEvent) != 'undefined') 
  	{ 
  	evt.initKeyboardEvent('keypress', true, true, null, false, false, false, false, keyCode, charCode); 
  	} 
  else 
  	{ 
  	evt.initKeyEvent('keypress', true, true, null, false, false, false, false, keyCode, charCode); 
  	}
  */
  current_partial_edit_obj.dispatchEvent(evt);
  //alert(current_partial_edit_obj.scrollLeft);
  }
  
}

function handle_partial_result_key(obj, evnt)
{
if(obj != current_partial_edit_obj)
	{
	current_partial_edit_obj = obj;
	current_partial_edit_obj.setAttribute("autocomplete", "off"); 
	}
current_key_code = get_partial_result_key_code(evnt);
return handle_partial_fill_arrow_keys(current_key_code);
//var key_code = get_partial_result_key_code(evnt);
//alert(key_code);
//return special_partial_result_selection(key_code);
}

function fetch_partial_results(obj,media, table)
{
	//alert(key_code);
	var ret = special_partial_result_selection(current_key_code);
	if(ret == true)
		{
		if(partial_fetch_timer != null)
			{
			clearTimeout(partial_fetch_timer);
			partial_fetch_timer = null;
			}
		current_partial_edit_obj = obj;
		current_partial_search_media = media;
		current_partial_search_table = table;
		
		partial_fetch_timer = setTimeout("fetch_partial_results_timeout()", 500);
		}
	return ret;		
}

function fetch_partial_results_timeout()
{
	var str = get_current_partial_edit_str();
	if(str.length >= 3)
		{
		fetch_partial_result_item(str);
		}
	else
		{
		hide_partial_result_list();
		}
}

function init_partial_result()
{
//hide_partial_result_list();
current_partial_edit_obj = null;
//previous_partial_search_value = '';
partial_result_count = 0;
//partial_result_array= new Array();
current_partial_selection_index = 0;
partial_list_visible = false;
current_partial_search_media = 1;
current_partial_search_table = 'author';
}

function fire_event(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}