// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject(); 
var input;
var _input;
var input_start;
var input_end;
var caret_position;
var show_position=0;
var encode_type;
var update_flag = 0;
var hzcy_mode=0;
var _hzcy_mode=0;

var infoTimeout=300;

var zwarea='zwinput';
var zwmode='hmode';

// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() 
{	
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // if running Internet Explorer
  if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try 
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
 
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

// make asynchronous HTTP request using the XMLHttpRequest object 
function process(inputStr)
{
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // retrieve the input typed by the user on the form
    //input = encodeURIComponent( current_input() );

	checked_flag=false;
	for (i=0; i<document.encode_form.encode.length; i++){
		if(document.encode_form.encode[i].checked) {
			encode_type = document.encode_form.encode[i].value;
			checked_flag=true;
		}
	}
	if( checked_flag==false ) {
		document.encode_form.encode[0].checked=true;
		encode_type = "J";
	}

	if(encode_type == "J") {
		setTimeout(function() {
			document.getElementById("div_td").bgColor="silver";
		}, 1);
	}
	else if(encode_type == 'F') {
		setTimeout(function() {
			document.getElementById("div_td").bgColor="steelblue";
		}, 1);
	}
	else if(encode_type == 'R') {
		setTimeout(function() {
			document.getElementById("div_td").bgColor="#BDC6DE";
		}, 1);
	}

    // execute the php page from the server
    xmlHttp.open("GET", zwarea + ".php?encode=" + encode_type + "\&input=" + inputStr, true);  
	input = inputStr;

    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;

    // make the server request
    xmlHttp.send(null);
  }
  else {
    // if the connection is busy, try again after one second  
    setTimeout('process(inputStr)', 100);
  }
}

// executed automatically when a message is received from the server
function handleServerResponse() 
{
	// move forward only if the transaction has completed
	if (xmlHttp.readyState == 4) {
		// status of 200 indicates the transaction completed successfully

		if (xmlHttp.status == 200) {
			// extract the XML retrieved from the server
			xmlResponse = xmlHttp.responseXML;
			// obtain the document element (the root element) of the XML structure
			xmlDocumentElement = xmlResponse.documentElement;
			// get the text message, which is in the first child of
			// the the document element
			compList = xmlDocumentElement.firstChild.data;

			// update the client display using the data received from the server
			if( update_flag != 0 ) {
				document.getElementById("divMessage").innerHTML = "<div height=360>" + parseList( compList ) + "</div>";
			}

			for (i=0; i<document.encode_form.encode.length; i++){
				if(document.encode_form.encode[i].checked) {
					_encode_type = document.encode_form.encode[i].value;
					break;
				}
			}

			_input = encodeURIComponent( current_input() );

			document.getElementById("inputIndicator").value = current_input();

			if( _input.length == 0 ) {
				update_flag = 0;
				setTimeout('handleServerResponse()', 100);
				document.getElementById("divMessage").innerHTML = "";

			}
			else if( _input != input || _encode_type != encode_type ) {
				update_flag = 1;

				_input = encodeURIComponent( current_input() );
				setTimeout('process(_input)', 30);
			}
			else {
				update_flag = -1;
				setTimeout('handleServerResponse()', infoTimeout);
			}
		}
		// a HTTP status different than 200 signals an error
		else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

function insertStr(str) {

	hzcy_mode = 0;

	//IE support
	if (document.selection) {
		//document.getElementById(zwarea).focus();

		var cursor = document.getElementById("cursor").value;

		whole_text = document.getElementById(zwarea).value;
		text_len = whole_text.length;

		first_half = whole_text.substr(0, input_start);
		second_half = whole_text.substr(cursor, text_len-cursor);

		textarea = document.getElementById(zwarea);
		textarea.value = first_half + str; 

		rt_count=0;
		for(i=0; i<textarea.value.length; i++) {
			// the count of "\r"s
			if(textarea.value.charCodeAt(i)==13) rt_count++;
		}

		caret_position = document.getElementById("cursor").value - input_str.length - rt_count + str.length;

		textarea.value += second_half;
		setCaretPosition(textarea, caret_position);

		return;
	}

	var cursor = document.getElementById("cursor").value;

	whole_text = document.getElementById(zwarea).value;
	text_len = document.getElementById(zwarea).value.length;

	first_half = whole_text.substr(0, input_start);
	second_half = whole_text.substr(cursor, text_len-cursor);

	textarea = document.getElementById(zwarea);
	textarea.value = first_half + str;

	/*
		nl_count=0;
		for(i=0; i<textarea.value.length; i++) {
			// the count of "\n"s
			if(textarea.value.charCodeAt(i)==10) nl_count++;
		}
	*/

	caret_position = textarea.value.length;
	document.getElementById("cursor").value = caret_position;

	show_position = textarea.scrollHeight;
	textarea.value += second_half;

	setCaretPosition(textarea, caret_position);

	if( show_position < 240 ) {
		textarea.scrollTop = 0;
	}
	else {
		textarea.scrollTop = show_position - 120;
	}

//document.getElementById("p").value = encodeURIComponent( document.getElementById("p1").value );
}

function parseList(compList)
{
	var status_char;

	status_char = compList.charAt(2);

	if(status_char=='!') {

		var entrySet = compList.split("\ ");

		if( update_flag > 0 ) {
			insertStr( entrySet[3] );

			setTimeout(function() {
   	 	    	populate();
    		}, 5);
		}
		return(compList);
	}
	else if(status_char=='^') {

		var j, j1, j2, w;
		var output;
		var start, seq_width, show_width, end_flag;

		var entryList = compList.split("|");
		var listCount = entryList.length-2;
		var entry;

		if( listCount<10 ) {
			start = 0;
			seq_width = 1;
		}
		else if( listCount<90 ) {
			start = 10;
			seq_width = 2;
		}
		else {
			start = 110;
			seq_width = 3;
		}

		show_width = 36;

		j=1; end_flag=0;
		output = "";
		while(j<entryList.length-1) {

			j1=0; w=0;
			output += "<table><tr>";
			while(w<show_width && (seq_width*j1*9)<(show_width*20) ) {

				entry = encodeURIComponent( entryList[j+j1] );
				output += "<td nowrap=nowrap class=entryList><a STYLE=text-decoration:none href=\"/ZWD/showDict.php?item=" + 
						entry + "\" target=hzArea bgcolor=silver>" + entryList[j+j1] + "</a></td>";

				j1++; w+=entryList[j+j1].length;
				if( (j+j1)==(entryList.length-1) ) {
					break;
				}
			}
			output +=  "</tr><tr>";

			j2=0; w=0;
			while(w<show_width && (seq_width*j2*9)<(show_width*20) ) {
				seq = start + j + j2; 
				output += "<td class=entrySeq>" + seq + "</td>";

				j2++; w+=entryList[j+j2].length;
				if( (j+j2)==(entryList.length-1) ) {
					end_flag=1;
					break;
				}
			}
			if(end_flag==0) {
				output +=  "</tr><tr>";
			}
			output +=  "</tr></table>";

			j+=j2;
		}
	
		return (output);
	}
}

//================================================
var is_gecko = /gecko/i.test(navigator.userAgent);
var is_ie    = /MSIE/.test(navigator.userAgent);

function setSelectionRange(input, start, end) {
	if (is_gecko) {
		input.setSelectionRange(start, end);
	} else {
		// assumed IE
		var range = input.createTextRange();
		range.collapse(true);
		range.moveStart("character", start);
		range.moveEnd("character", end - start);
		range.select();
	}
};

function setCaretPosition(ctrl, pos)
{

	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function current_input() {
	var cursor = document.getElementById("cursor").value;
	var tv = document.getElementById(zwarea).value;

	if(cursor==0) return "";
	else {
		var flag = 0;
		for(i=cursor-1; i>=0; i--) {
			/*
			if( (tv.charAt(i).charCodeAt(0)>=48&&tv.charAt(i).charCodeAt(0)<=57) || 
				(tv.charAt(i).charCodeAt(0)>=97&&tv.charAt(i).charCodeAt(0)<=122)|| 
				(tv.charAt(i).charCodeAt(0)>=65&&tv.charAt(i).charCodeAt(0)<=90) ) {
			}
			*/
			if( (tv.charCodeAt(i)>=48&&tv.charCodeAt(i)<=57) || 
				(tv.charCodeAt(i)>=97&&tv.charCodeAt(i)<=122)|| 
				(tv.charCodeAt(i)>=65&&tv.charCodeAt(i)<=90) ) {
			}
			else {
				if( hzcy_mode == 1 ) input_start = i;
				else input_start = i+1;
				flag = 1;
				break;
			}
		}
		if( flag == 0 ) {
			input_start = 0;
		}
	}

	input_end = cursor-1;
	
	input_str = tv.substr(input_start, cursor-input_start);

	return input_str;
}

function get_search_start(inputArea) {

	zwarea = inputArea.id;

	if (is_gecko)
		return inputArea.selectionStart;
	var range = document.selection.createRange();
	var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
	if (!isCollapsed)
		range.collapse(true);
	var b = range.getBookmark();
	return b.charCodeAt(2) - 2;
};

function invoke_search(inputArea, ev) {

	infoTimeout=100;

	setTimeout(function() {
		document.getElementById("cursor").value = get_search_start(inputArea)
		populate();
	}, 5);
}

function resetInfoTimeout() {
	infoTimeout=2000;
}

function populate() {
		document.getElementById("q").value = document.getElementById("zwsearch").value;
		document.getElementById("p").value = document.getElementById("zwsearch").value;
		document.getElementById("searchInput").value = document.getElementById("zwsearch").value;
		document.getElementById("wd").value = document.getElementById("zwsearch").value;
}

function get_zwinput_start(input) {

	zwarea='zwinput';

	if (is_gecko)
		return input.selectionStart;
	var range = document.selection.createRange();
	
	rangeCopy = range.duplicate();

	textArea = document.getElementById(zwarea);

	// Select all text
	rangeCopy.moveToElementText(textArea);

	// Now move 'dummy' end point to end point of original range
	rangeCopy.setEndPoint( 'EndToEnd', range );
	// Now we can calculate start and end points
	return rangeCopy.text.length - range.text.length;
};

function invoke_zwinput(input, ev) {

	infoTimeout = 100;

	setTimeout(function() {
		document.getElementById("cursor").value = get_zwinput_start(input)
	}, 5);
}

