/**********************************************************/
/* Ãß    °¡		  : 2010-02-24(»óÇ°)					  */
/* °³ ¹ß ÀÚ       : ¼³°æÃ¢								  */
/* È¸ »ç ¸í		  : (ÁÖ)ÆäÀÌ½ºµå¸²						  */
/* ÆÄ ÀÏ ¸í		  : suggest.js							  */
/* ¿ë    µµ		  : ÀÚµ¿ ¿Ï¼º °Ë»ö¾î »öÃâ ¹× °£´Ü»óÇ° °Ë»ö*/
/**********************************************************/

document.write("<style type='text/css'>");
//document.write("span{font-size:9pt;}");
document.write(".span_match_text{text-decoration:underline;font-weight:bold;color:#FF6600;}");
document.write(".span_normal{background:#FFFFFF;}");
document.write(".span_highlight{background:#CEE7FF;color:#5A7D98; cursor:pointer; padding:2px 1px -2px 1px; font-weight:bold;}");
/* ½ºÅ©·Ñ¹Ú½º & ½ºÅ©·Ñ¹Ù */ 
document.write(".span_result_box {");
document.write("POSITION:absolute;");
document.write("Z-INDEX:9999999;");
document.write("BACKGROUND-color:#FFFFFF;");
document.write("BORDER:1px solid #555555;");
document.write("PADDING:0px 5px 0px 5px;");
document.write("OVERFLOW:visible;");
document.write("DISPLAY:none;");
document.write("TEXT-ALIGN:left;");
document.write("FONT-SIZE: 9pt;");
document.write("FONT-FAMILY: ±¼¸²;");
document.write("SCROLLBAR-FACE-COLOR: #ededed;");
document.write("SCROLLBAR-HIGHLIGHT-COLOR: #fafafa;");
document.write("SCROLLBAR-SHADOW-COLOR: #bdbdbd; COLOR: black;");
document.write("SCROLLBAR-3DLIGHT-COLOR: #ffffff;");
document.write("SCROLLBAR-ARROW-COLOR: #89a0bc;");
document.write("SCROLLBAR-TRACK-COLOR: #F7FFFF;");
document.write("SCROLLBAR-DARKSHADOW-COLOR: #ffffff;");
document.write("}");
document.write(".item_result_box {");
document.write("POSITION:absolute;");
document.write("Z-INDEX:9999998;");
document.write("BACKGROUND-color:#FFFFFF;");
document.write("BORDER:1px solid #555555;");
document.write("PADDING:0px 5px 0px 5px;");
document.write("OVERFLOW:visible;");
document.write("DISPLAY:none;");
document.write("margin-top:260px;");
document.write("TEXT-ALIGN:left;");
document.write("FONT-SIZE: 9pt;");
document.write("FONT-FAMILY: ±¼¸²;");
document.write("margin:3px 0;");
document.write("}");

document.write("#span_output {width:265px; height:120px; overflow-y:auto; overflow-x:hidden;  } ");
document.write("</style>");

document.write("<div><div id='span_output' class='span_result_box'></div>"); 
document.write("<div id='item_output' class='item_result_box'></div></div>"); 
//document.write("<div id='msg' ></div>"); 


var req;
var result_js_object; // ¼­¹ö¿¡¼­ ³Ñ¾î¿Â ÀÚ·á eval
var save_js_object; // ½ÇÁ¦ Ãâ·ÂµÈ ÀÚ·á¸¸ º¸°üÇÏ´Â º¯¼ö

var textbox;
var save_textbox;	// È­»ìÇ¥°¡ ÀÌµ¿ÇÏ±âÀü¿¡ ÅØ½ºÆ®¹Ú½ºÀÇ ³»¿ëÀ» ÀúÀåÇÏ°í ´Ù½Ã È­»ìÇ¥°¡ µ¹¾Æ¿À¸é ¿ø·¡°ªÀ» º¹¿ø
var before_textbox; // ¹Ù·ÎÀü ÅØ½ºÆ®¹Ú½º ³»¿ë
var current_line = -1; // °á°ú¿¡¼­ ÇöÀç ¼±ÅÃµÈ ¶óÀÎ
var count_for_id;

var is_timer;
var auto_request = false; // ÀÚµ¿ ¿äÃ» (ÇÑ±ÛÃ³¸®½Ã »ç¿ë)

var msg = document.getElementById('msg');

function sug_set_properties(xelement, xserver_url, xignore_case, xany_where, xresult_box_width) {
    var props={
        element: xelement,
        server_url: xserver_url,
        ignore_case: ((xignore_case) ? "i" : ""),
        any_where: ((xany_where) ? "" : "^"), // Áß°£¿¡ ÀÖ´Â ±ÛÀÚ¸¦ °Ë»öµÇ°Ô ÇÒ°ÍÀÎÁö?
        like: ((xany_where) ? 1 : 0), // SQL QUERY LIKE ¾Õ %
        result_box_width: xresult_box_width // °á°ú ¹Ú½º¸¦ textbox ÀÇ Æø°ú °°°Ô ÇÒ°ÍÀÎÁö?
    };

    if (textbox == null)
        textbox = xelement;
    sug_add_handler(xelement);
    return props;
}

//var isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
function sug_add_handler(objText){
    objText.onkeydown = sug_textbox_keydown;
    objText.onfocus = sug_textbox_focus;
    //if (isOpera) objText.onkeypress = sug_textbox_keydown;
}

function sug_textbox_keydown(e) {
    if(window.event){
      key = event.keyCode;
      textbox = event.srcElement;
      _event = event;
    }
    else{
      key = e.which;
      textbox = e.target;
      _event = e;
    }

    auto_request = false;

    if (key == 13) { // ¿£ÅÍÅ°
        if (current_line >= 0)
            textbox.value = save_js_object[current_line];
        return;
    } else if (key == 38) { // À§ È­»ìÇ¥
        sug_move_key(-1);
        return;
    } else if (key == 40) { // ¾Æ·¡ È­»ìÇ¥
        if (current_line < 0) {
            // È­»ìÇ¥°¡ ¾Æ·¡·Î ÀÌµ¿ÇÏ±â Àü¿¡ ÅØ½ºÆ®¹Ú½ºÀÇ °ªÀ» ÀúÀå
            save_textbox = textbox.value;
        }
        sug_move_key(1);
        return;
    } else if (key == 219 || key == 220 || key == 221 || key == 222) {
        cancel_event(_event);
        return;
    } else if (key == 229) { //  ÇÑ±Û
        auto_request = true;
        is_timer = setTimeout("sug_request_han();", 100);
    }

  //msg.innerHTML += ","+key;

    is_timer = setTimeout("sug_request_eng()", 100);
}

function sug_textbox_focus() {
    textbox = this;
    current_line = -1;
    count_for_id = -1;
    sug_send_server(textbox.value,'word');
}

function sug_make_matches(xcompare_str){
    count_for_id = 0;
    save_js_object = new Array();
    var match_array = new Array();

    var reg_exp = new RegExp(textbox.obj.any_where + hangulToJaso(xcompare_str), textbox.obj.ignore_case);

    for (i=0;i<result_js_object.length;i++) {

        var is_match = hangulToJaso(result_js_object[i]).match(reg_exp);

        if(is_match){
            match_array[match_array.length] = sug_create_underline(result_js_object[i], xcompare_str, count_for_id);
            save_js_object[count_for_id] = result_js_object[i];
            count_for_id++;
        }
    }
    return match_array;
}

var underline_head = "<span class='span_match_text'>";
var underline_tail = "</span>";
var select_span_head = "<span style='width:100%;display:block;' class='span_normal' onmouseover='sug_set_color(this)' onmouseout='current_line=-1; sug_set_color(null);'";
var select_span_tail ="</span>";

function sug_create_underline(xstr, xtextmatch, xindex){
    select_span_mid = " onclick='sug_set_text(" + xindex + ")'" + "id='options_list_" + xindex + "' index_no='" + xindex + "'>";

	var reg_exp = new RegExp(textbox.obj.any_where + xtextmatch, textbox.obj.ignore_case);
    var start_pos = xstr.search(reg_exp);

	var matched_text = xstr.substring(start_pos, start_pos + xtextmatch.length);
    return select_span_head + select_span_mid + xstr.replace(reg_exp, underline_head + matched_text + underline_tail) + select_span_tail;
}

function sug_set_color(xtextbox){
    if(xtextbox){
        //current_line = xtextbox.id.slice(xtextbox.id.indexOf("_") + 1, xtextbox.id.length);
        //xtextbox.id.slice(xtextbox.id.indexOf("_") + 1, xtextbox.id.length);
        current_line = xtextbox.getAttribute("index_no");
    }

    var opt;
    for(i=0; i<count_for_id; i++){
        opt = document.getElementById('options_list_' + i);

        if (opt)
            opt.className = 'span_normal';
    }

    var opt = document.getElementById('options_list_' + current_line);
    if (opt)
        opt.className = 'span_highlight';
}

function sug_set_text(xindex){
    textbox.value = save_js_object[xindex]; //set text value

    current_line = -1; //remove the selected index
	//alert(textbox.form.action);
	parent.textbox.form.submit(); 
}

// À§ ¾Æ·¡ È­»ìÇ¥ ÀÌµ¿
function sug_move_key(number) {
    current_line = parseInt(current_line);
    if (number < 0) {
        if (current_line < 0) {
            return;
        }
    } else {
        if (current_line >= count_for_id - 1) {
            return;
        }
    }

    current_line = parseInt(current_line) + parseInt(number);
    if (current_line < 0) {
 
		document.getElementById('options_list_' + 0).className = 'span_normal';
		// È­»ìÇ¥°¡ ÀÌµ¿ÇÏ±â Àü¿¡ ÀúÀåµÈ °ªÀ» ÅØ½ºÆ®¹Ú½º °ªÀ¸·Î ³Ñ±è
        textbox.value = save_textbox;

    } else if (current_line < count_for_id) {
        sug_set_color(null);
        textbox.value = save_js_object[current_line];
    }
}

// request »ý¼º
function create_request() {
    var request = null;
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml12.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = null;
            }
        }
    }
    if (request == null)
        alert("Error creating request object!");
    else
        return request;
}

// ¼­¹ö·Î º¸³½´Ù
function sug_send_server(query_string,word) {
	if(word == 'word')
	{
		req = create_request();

		link = "q=" + query_string + "&like=" + textbox.obj.like + "&what=" + word;
		req.onreadystatechange = sug_result_server;
		req.open("POST", textbox.obj.server_url, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		req.send(link);
	}
	else if(word == 'item')
	{
		i_req = create_request();

		link = "q=" + query_string + "&like=" + textbox.obj.like + "&what=" + word;
		i_req.onreadystatechange = sug_iresult_server;
		i_req.open("POST", textbox.obj.server_url, true);
		i_req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		i_req.send(link);
	}
}

// ³Ñ¾î¿Â °á°ú°¡ Á¤»óÀÌ¶ó¸é Ãâ·ÂÇÑ´Ù
function sug_result_server() {
    if (req.readyState == 4) {
        if (req.status == 200) {

			sug_result_box_position(textbox);

            // »õ·Î¿î °á°ú°¡ ³ª¿À¸é ÇöÀç ¶óÀÎÀ» -1 ·Î ¼³Á¤
            current_line = -1;
            count_for_id = -1;

            document.getElementById('span_output').style.display = "none";
            document.getElementById('span_output').innerHTML = "";
            document.getElementById('item_output').style.display = "none";
            document.getElementById('item_output').innerHTML = "";

            var str = "";

            result_js_object = eval(req.responseText);

			if (result_js_object) {
                // ¸ÅÄ¡µÈ °á°ú¿¡ ¾ð´õ¶óÀÎÀ» Ãâ·Â
                var result = sug_make_matches(textbox.value);

                for(i=0;i<count_for_id;i++) {
                    str += "<div style='width:100%;padding:0px 0 0 0px;height:18px;cursor:pointer;' id='f"+i+"'>" + result[i] + "</div>";
                }
            }

            if (count_for_id > 0) {
                document.getElementById('span_output').innerHTML = str;
                document.getElementById('span_output').style.display = "block";
				//sug_send_server(textbox.value,'item');
            }
        }
    }
}

function sug_iresult_server() {
    if (i_req.readyState == 4) {
        if (i_req.status == 200) {

            var i_str = "";

            result_iobj = eval(i_req.responseText);
			
		   if (result_iobj.length > 0)
			{
				for (i=0;i<result_iobj.length;i++)
				{
					var resultArr = result_iobj[i].split("||"); 
					// resultArr[0] = > »óÇ° ¸í
					// resultArr[1] = > ºê·£µå ¹øÈ£
					// resultArr[2] = > »óÇ° ¹øÈ£
					// resultArr[3] = > ºê·£µå ¸í
					// resultArr[4] = > 160 ÀÌ¹ÌÁö
					// resultArr[5] = > ÆÇ¸Å °¡°Ý

					i_str += "<div id='i_f"+i+"'><span id='no" + i + "' onMouseOver='javascript:change(" + i + ","+ result_iobj.length +")'>" + eval(i+1) + "</span><span id='img_i" + i + "' style='display:none;'><a href='' cursor:pointer;><img src='http://images.facedream.co.kr/items/" + resultArr[1] + "/" + resultArr[2] + "/" + resultArr[4] + "' alt=' " + resultArr[0] +" ' /></a>["+ resultArr[3] + "] " + resultArr[0] +"</span></div>";
				}

				document.getElementById('item_output').innerHTML = i_str;
                document.getElementById('item_output').style.display = "block";
                document.getElementById('img_i0').style.display = "block";
            }

		}
    }
}

function change(sw,length) {
	for (var i = 0; i < length; i++) {
		if (sw == i) {
			document.getElementById('img_i'+i).style.display='block';
		} else {
			document.getElementById('img_i'+i).style.display='none';
		}
	}
}

// °á°ú¹Ú½ºÀÇ Æ÷Áö¼Ç ¼³Á¤
function sug_result_box_position(xelement){
    var el_width = xelement.offsetWidth;
    var el_height = xelement.offsetHeight + 5;

    var el_x = el_y = 0;
    var obj = xelement;
    while (obj.offsetParent) {
        el_x += obj.offsetLeft;
        el_y += obj.offsetTop;
        obj = obj.offsetParent;
    }

    span_el = document.getElementById("span_output");
    span_el.style.left = el_x;
    span_el.style.top = el_y + el_height;
    if (xelement.obj.result_box_width) 
        span_el.style.width = el_width;
    span_el.style.display = "block";
}

// ÇÑ±Û Å°º¸µå ÀÔ·Â Ã³¸®
function sug_request_han() {
    if (before_textbox != textbox.value && auto_request) {
        before_textbox = textbox.value;
        try {
            sug_send_server(textbox.value,'word');
        } catch (e) {
            if (auto_request)
                is_timer = setTimeout("sug_request_han();", 100);
            return 0;
        }
    }

    if (auto_request)
        is_timer = setTimeout("sug_request_han();", 100);
}

// ¿µ¹®+±âÅ¸ Å°º¸µå ÀÔ·Â Ã³¸®
function sug_request_eng() {
    // °Ë»ö¾î°¡ 20±ÛÀÚ ¹Ì¸¸ÀÌ¶ó¸é
    if(textbox.value.length < 20) {
        sug_send_server(textbox.value,'word');
    }

    if (!auto_request)
        clearTimeout(is_timer);
}

function cancel_event(e) { 
  e.returnValue = false;
  if (e && e.preventDefault) 
      e.preventDefault();
}

/* ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ  ÀÚ¼Ò Ã¼Å·  ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ */

function hangulToJaso(text)   
{   
	var ChoSeong = new Array (    
		0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,    
		0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147,    
		0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e    
	);   
	var JungSeong = new Array (    
		0x314f, 0x3150, 0x3151, 0x3152, 0x3153, 0x3154,    
		0x3155, 0x3156, 0x3157, 0x3158, 0x3159, 0x315a,    
		0x315b,0x315c, 0x315d, 0x315e, 0x315f, 0x3160,    
		0x3161, 0x3162, 0x3163    
	);   
	var JongSeong = new Array (    
		0x0000, 0x3131, 0x3132, 0x3133, 0x3134,0x3135,    
		0x3136, 0x3137, 0x3139, 0x313a, 0x313b, 0x313c,    
		0x313d, 0x313e, 0x313f, 0x3140, 0x3141, 0x3142,    
		0x3144, 0x3145, 0x3146, 0x3147, 0x3148, 0x314a,    
		0x314b, 0x314c, 0x314d, 0x314e    
	);   
	var chars = new Array()   
	var v ='';   
	for (var i = 0; i < text.length; i++)    
	{   
		chars[i] = text.charCodeAt(i);   
		if (chars[i] >= 0xAC00 && chars[i] <= 0xD7A3)    
		{   
			var i1, i2, i3;   
			i3 = chars[i] - 0xAC00;   
			i1 = i3 / (21 * 28);   
			i3 = i3 % (21 * 28);   
			i2 = i3 / 28;   
			i3 = i3 % 28;   
			v += String.fromCharCode(ChoSeong[parseInt(i1)]);   
			v += String.fromCharCode(JungSeong[parseInt(i2)]);   
			if (i3 != 0x0000)   
				v += String.fromCharCode(JongSeong[parseInt(i3)]);   
		}   
		else {   
			v += String.fromCharCode(chars[i]);   
		}   
	}
	//var result = v.replace(/\,+/g,"");

	return v;
}
/* ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ  ÀÚ¼Ò Ã¼Å·  ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ¢Æ */
