/*
	cocode_stoarge : hidden input for storing cocode value
	input : user text input
	change_btn : in tweet page, user can change company which he/she writes about.
	drop_box : auto completion list box.
*/

function search(cocode_storage_id, input_id, change_btn_id, drop_box_id, on_select_company) {
	this.fst_companyname = "";
	this.fst_companycode = "";

	this.cocode_storage = $(cocode_storage_id);
	this.input = $(input_id);
	this.change_btn = $(change_btn_id);
	this.drop_box = $(drop_box_id);
	if(on_select_company != null){
		this.on_select_company = on_select_company;
	} else {
		this.on_select_company = this.setRecentlyCompany;
	}

	this.selected_index = -1;
}

search.prototype.enableBox = function()
{
	//set value
	this.cocode_storage.value = "";
	this.input.value = "";

	//set display
	this.input.readOnly = false;
	this.input.disabled = false;
	this.input.setStyle({border:'1px solid #cccccc'});
	this.input.style.backgroundImage = "url('/assets/images/bbs_tweet/text_cpcode_default.gif')";

	if(this.change_btn) this.change_btn.hide();
	this.drop_box.hide();
};

search.prototype.disableBox = function()
{
	//set value
	this.cocode_storage.value = "";
	this.input.value = "";

	//set display
	this.input.readOnly = false;
	this.input.disabled = false;
	this.input.setStyle({border:'1px solid #cccccc'});
	this.input.style.backgroundImage = "url('/assets/images/bbs_tweet/text_cpcode_default.gif')";

	if(this.change_btn) this.change_btn.hide();
	this.drop_box.hide();
};

search.prototype.inifocus = function()
{
	//this.input.style.backgroundImage = "none";
	if( !this.cocode_storage.value.empty() )
	{
		this.cocode_storage.value = "";
		this.input.value = "";
	}
};

//초기화
search.prototype.initTable = function()
{
	this.drop_box.innerHTML = "";
	this.selected_index = -1;
};

//데이터 없을 경우
search.prototype.showNoData = function()
{
	this.initTable();


	var y = document.createElement('div');
	y.className = "suggestion_div";
	y.style.textAlign = "center";
	y.style.height = "20px";
	y.style.backgroundColor = "#FFFFFF";
	y.style.fontSize = "12px";
	y.style.color = "#999999";
	y.innerHTML = '검색 결과가 없습니다.';
	this.drop_box.appendChild(y);
};

search.prototype.getRecentlyCompany = function()
{
	if(this.drop_box.getStyle('display') != "none") return;

	var URL = "/company/getRecentlySearch/";
	var params = $H();
	var search_instance = this;

	var myAjax = new Ajax.Request( URL,
		{
			asynchronous: true,
			method: "post",
			parameters: params,
			onSuccess: function(xmlHttp)
			{
				try {
					var data = eval("(" + xmlHttp.responseText + ")");
				} catch(e) {
					alert('AjaxCall : ' + e + ' - ' + xmlHttp.responseText);
					return;
				}
				search_instance.resultGetRecentlyCompany(data, null);
			},

			onFailure : function (request)
			{
				alert("FAIL");
				return;
			}
		});
};

search.prototype.resultGetRecentlyCompany = function(data, keyword)
{
	//검색 결과가 없는 경우
	if(data.resultCode == "NODATA")
	{
		this.showNoData();
		return;
	}
	if(data.resultCode == "FAIL")
	{
		alert(data.message);
		return;
	}

	this.initTable();

	var list = data.result.list;
	var loop = list.length;
	var search_instance = this;

	$R(0, loop, true).each(function(i){
		//enter키 클릭시 처리
		if(i == 0)
		{
			search_instance.fst_companyname = list[i].name;
			search_instance.fst_companycode = list[i].cocode;
		}
		
		var div = document.createElement('div');
		var name = list[i].name;
		var code = list[i].cocode;
		var highlighted_name;
		var highlighted_code;

		if(keyword != undefined){
			var name_index = name.toUpperCase().indexOf(keyword.toUpperCase());
			var code_index = code.indexOf(keyword);
			if(name_index >= 0){
				highlighted_name = name.substr(0, name_index);
				highlighted_name += "<span style='font-weight:bold; color:#ff6600'>" + name.substr(name_index, keyword.length) + "</span>";
				highlighted_name += name.substr(name_index + keyword.length);
			} else {
				highlighted_name = name;
			}
			if(code_index >= 0){
				highlighted_code = code.substr(0, code_index);
				highlighted_code += "<span style='font-weight:bold; color:#ff6600'>" + code.substr(code_index, keyword.length) + "</span>";
				highlighted_code += code.substr(code_index + keyword.length);
			} else {
				highlighted_code = code;
			}

		} else {
			highlighted_code = code;
			highlighted_name = name;
		}
	
		div.className = 'suggestion_div company_list_elem';
		div.onmouseup = function() { search_instance.on_select_company(name, code, search_instance); };
		div.onmouseover = function() { div.style.backgroundColor = '#ffe770'; };
		div.onmouseout = function() { div.style.backgroundColor = '#ffffff'; };
		div.innerHTML = highlighted_name + '(' + highlighted_code + ')';

		var input_code = document.createElement('input');
		input_code.type = 'hidden';
		input_code.name = 'code';
		input_code.value = code;

		var input_name = document.createElement('input');
		input_name.type = 'hidden';
		input_name.name = 'name';
		input_name.value = name;

		div.appendChild(input_name);
		div.appendChild(input_code);

		search_instance.drop_box.appendChild(div);
	});
	this.drop_box.show();
};

search.prototype.setRecentlyCompany = function(name, code)
{
	this.inifocus();

	//set display
	this.input.readOnly = true;
	this.input.disabled = true;
	this.input.setStyle({border:'0px solid #cccccc'});
	if(this.change_btn) this.change_btn.show();

	//set value
	this.cocode_storage.value = code;
	this.input.value = name+"("+code+")";

	this.drop_box.hide();
};

search.prototype.setSearch = function()
{
	//set display
	this.input.readOnly = false;
	this.input.disabled = false;
	this.input.setStyle({border:'1px solid #cccccc'});
	if(this.change_btn) this.change_btn.hide();
};

search.prototype.getCompany = function()
{
	if( this.input.value.empty() ) return;
	if( this.input.disabled )
	{
		this.drop_box.hide();
		return;
	}

	var URL = "/company/getSearch/";
	var keyword = this.input.value;
	var params = $H({'keyword' : keyword});
	var search_instance = this;
	var myAjax = new Ajax.Request( URL,
		{
			asynchronous: true,
			method: "post",
			parameters: params,

			onSuccess: function(xmlHttp)
			{
				try {
					var data = eval("(" + xmlHttp.responseText + ")");
				} catch(e) {
					alert('AjaxCall : ' + e + ' - ' + xmlHttp.responseText);
					return;
				}
				search_instance.resultGetRecentlyCompany(data, keyword);
			},

			onFailure : function (request)
			{
				alert("FAIL");
				return;
			}
		}
	);
};

search.prototype.keyUp = function(event)
{
	switch(event.keyCode)
	{
		case Event.KEY_RETURN:
			if( this.fst_companyname.empty() ) return;
			this.on_select_company(this.fst_companyname, this.fst_companycode, this);
		return;
		case Event.KEY_UP:
			Event.stop(event);
		return;
		case Event.KEY_DOWN:
			Event.stop(event);
		return;
		case 229: // in FF, mouse click event cause keyup event whose keycode is 229.
		return;
		default:
		break;
	}

	this.getCompany();
};

search.prototype.keyDown = function(event)
{
	switch(event.keyCode)
	{
		case Event.KEY_RETURN:
		// don't submit
			Event.stop(event);
		break;
		case Event.KEY_UP:
			var list = $$('#' + this.drop_box.id + ' .company_list_elem');
			if(!list){
				return;
			}
			if(this.selected_index > 0){ 
				this.selected_index--;
				list[this.selected_index].style.backgroundColor = '#ffe770';
				this.fst_companyname = $$('#' + this.drop_box.id + ' .company_list_elem' + ' input[name="name"]')[this.selected_index].value;
				this.fst_companycode = $$('#' + this.drop_box.id + ' .company_list_elem' + ' input[name="code"]')[this.selected_index].value;
				if(this.selected_index + 1 < list.length) list[this.selected_index + 1].style.backgroundColor = '#ffffff';

				var div = list[this.selected_index];
				var drop_box_height = this.drop_box.getHeight();
				var top = div.offsetTop - div.offsetParent.scrollTop;
				if(top < 0) {
					div.offsetParent.scrollTop = div.offsetTop;
				}
				if((top + div.offsetHeight) > drop_box_height){
					div.offsetParent.scrollTop = div.offsetTop - ( drop_box_height - div.offsetHeight);
				}

			}
		return;
		case Event.KEY_DOWN:
			var list = $$('#' + this.drop_box.id + ' .company_list_elem');
			if(!list){
				return;
			}
			if(this.selected_index < list.length - 1){ 
				this.selected_index++;
				list[this.selected_index].style.backgroundColor = '#ffe770';
				this.fst_companyname = $$('#' + this.drop_box.id + ' .company_list_elem' + ' input[name="name"]')[this.selected_index].value;
				this.fst_companycode = $$('#' + this.drop_box.id + ' .company_list_elem' + ' input[name="code"]')[this.selected_index].value;
				if(this.selected_index - 1 >= 0) list[this.selected_index - 1].style.backgroundColor = '#ffffff';
				var div = list[this.selected_index];
				var drop_box_height = this.drop_box.getHeight();
				var top = div.offsetTop - div.offsetParent.scrollTop;
				if(top < 0) {
					div.offsetParent.scrollTop = div.offsetTop;
				}
				if((top + div.offsetHeight) > drop_box_height){
					div.offsetParent.scrollTop = div.offsetTop - ( drop_box_height - div.offsetHeight);
				}
			}
		return;
		default:
		break;
	}
};

search.prototype.keyPress = function(event) {
	switch(event.keyCode) {
		case Event.KEY_RETURN:
			// if IE, enter keypress event causes form submit. so stop it.
			Event.stop(event);
		break;
		default:
		break;
	}
};

search.prototype.focusOut = function() {
	this.drop_box.hide();
	return;
};
