function isArray(obj) 
{
    return obj.constructor == Array;
}

function ajaxSuggest()
{
	var current;
	var intervalID;

	this.value;
	this.sourceForm;
	this.targetText;
	this.targetForm;
	this.requestURL;
	this.requestType;
	var thisClass = this;

	var pars;

	this.start = function()
	{	
		intervalID = window.setInterval(this.checkInput, 300);
	}

	this.checkInput = function()
	{
		if(isArray(thisClass.sourceForm))
		{
			this.value = "";
			for(i=0; i< thisClass.sourceForm.length; i++)
			{	
				this.value += thisClass.sourceForm[i].value;
			}
		}
		else
		{
			this.value = thisClass.sourceForm.value;
		}
		
		 //입력되었던 값과 현재 입력 값이 다른 경우
		if(current != this.value)
		{
			pars = "inputValue=" + this.value + "&requestType=" + thisClass.requestType;
			var result = new Ajax.Request
			(
				thisClass.requestURL, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete:thisClass.processJSON
				} 
			);
			
		}
		
		current = this.value;
	}

	this.stop = function()
	{	
		clearInterval(intervalID);
		setTimeout(function(){ this.checkInput; }, 300);
	}

	this.processJSON = function(transport)
	{
		var jsonData = transport.responseText.evalJSON();
		var type = jsonData["type"];
		var result = jsonData["result"];
	
		if(thisClass.targetText.firstChild)
		{
			thisClass.targetText.removeChild(thisClass.targetText.firstChild);
		}
		
		targetTextChild = document.createTextNode(result);
		
		if(type == "error")
		{
			thisClass.targetText.style.color = "#ff3737";
			thisClass.targetForm.value = ""; 
		}
		else
		{
			thisClass.targetText.style.color = "#92ba06"; 
			thisClass.targetForm.value = "1";
		}
		
		thisClass.targetText.style.fontSize = "8pt";
		thisClass.targetText.appendChild(targetTextChild);
		
		if(thisClass.targetForm)
		{
			thisClass.targetForm.setAttribute("exe", result);
		}
	}
}

// Ajax 결과를 DIV로 가져오기
function getAjaxResult(form, target, requestURL, Action)
{
	var target = $(target);
	var pars = $(form).serialize();
	var result = new Ajax.Request(requestURL, {method: 'post', parameters: pars, onComplete: processXML} );  

	function processXML(originalRequest)
	{
		var xmlData = new Array();
		xmlData = originalRequest.responseXML; // XML 파싱
		var dataNode = xmlData.getElementsByTagName("data");

		if(dataNode[0].childNodes[0].childNodes[0])
		{
			if(dataNode[0].childNodes[0].getAttribute("id")=="error")
			{ alert(dataNode[0].childNodes[0].childNodes[0].nodeValue); return false; }
			var containerID = dataNode[0].childNodes[0].getAttribute("id");
			var container = document.createElement("span");
			container.id = dataNode[0].childNodes[0].tagName;
			container.style.fontWeight = "bold";
			container.style.fontSize = "10pt";
			container.style.color = dataNode[0].childNodes[0].getAttribute("color");
			var result = document.createTextNode(dataNode[0].childNodes[0].childNodes[0].nodeValue);
			container.appendChild(result);
			if($(dataNode[0].childNodes[0].tagName)) { target.removeChild($(dataNode[0].childNodes[0].tagName)); }
			target.appendChild(container);
		}
		if(dataNode[0].childNodes[1].childNodes[0])
		{
			var containerID = dataNode[0].childNodes[1].getAttribute("id");
			var container = document.createElement("span");
			container.id = containerID;
			container.style.fontWeight = "bold";
			container.style.fontSize = "10pt";
			container.style.color = dataNode[0].childNodes[1].getAttribute("color");
			var result = document.createTextNode(dataNode[0].childNodes[1].childNodes[0].nodeValue);
			container.appendChild(result);
			if($(containerID)) { target.removeChild($(containerID)); }
			
			target.appendChild(container);
		}
		Action();
	}
}

// AJAX auto request
var autoTimeout = new Object();
function autoAjaxRequest(form, targetURL)
{
	this.form = form;
	this.targetURL = targetURL;

	clearTimeout(autoTimeout.ID);
	autoTimeout.ID = window.setTimeout(sendAjax, 5000);

	function sendAjax()
	{
		sendAjaxRequest(this.form, this.targetURL);
	}
}

// AJAX Form Request
function sendAjaxForm(form, targetURL, url)
{
	if(checkForm(form)) { sendAjaxRequest(form, targetURL, url); }
}

// AJAX Request
function sendAjaxRequest(form, targetURL, url)
{
	var requestURL = targetURL;
	var pars = $(form).serialize();
	var loadurl = url;
	var obj = this;
		
	// JSON 데이터 처리 함수
	function getJSON(originalRequest)
	{
		var jsonData = originalRequest.responseText.evalJSON();
		var jsonInfo = jsonData["Info"];
		var jsonResult = jsonData["Result"];

		if(jsonInfo)
		{
			if(jsonInfo.cols.length>=1)
			{
				for(var i=0; i<jsonInfo["cols"]["length"]; i++)
				{
					var key = jsonInfo["cols"][i].value;
					var limit = jsonInfo.cols.length;

					for(var x=0; x<limit; x++)
					{
						if(jsonResult["key"][x][key]) { var inputKey = jsonResult["key"][x][key]; }
						else { var inputKey = x; }
						
						if(jsonResult["value"][x][key] != 0)
						{
							$(key + "[" + inputKey + "]").value = jsonResult["value"][x][key];
						}
					}
				}
			}
		}

		// result 보여주기
		if(jsonResult["textMsg"])
		{
			showStatLayer(jsonResult["textMsg"], 700, "");
		}

		if(loadurl) { location.href=loadurl; }
	}

	var result = new Ajax.Request(requestURL, {method: 'get', asynchronous: true, parameters: pars, onComplete: getJSON, onFailure: function(){ alert('ajax request error') }});
}

// ajax 자동완성 클래스
function ajaxAutoComplete(rURL, requestType, title)
{
	// this 가 안먹어서 꽁수 쓴거
	thisClass = this; 
	this.rURL = rURL; // 쿼리 전송할 url
	this.requestType = requestType; // 쿼리 유형
	this.rTarget; // 값이 입력될 object
	this.rTarget2 = 0; // 값이 입력될 object
	this.sType = 0; // 검색 구분자
	this.title = title;
	this.allowOther = 0;
	this.nextSel = 0;
	this.lastSel;

	// 자동완성 시작
	thisClass.startAutoComplete = function(e, obj)
	{
		thisClass.rTarget = obj.id;

		// 추가 변수값 받기
		var pars = obj.getAttribute("var");
		pars = pars.split("&");
		thisClass.rTarget2 = pars[0];
		thisClass.sType = pars[1];
		thisClass.allowOther = pars[2];

		// 기존 코드 값 초기화
		$(thisClass.rTarget2).value = 0;

		if(navigator.userAgent.indexOf("MSIE") > 0)
		{
			thisClass.thisEvent = event;
		}
		else
		{
			thisClass.thisEvent = e;
		}
		
		thisClass.checkInput = function()
		{
			this.source = $(thisClass.rTarget).value;
			if(this.current!=this.source)
			{
				var url = thisClass.rURL;
				var pars = "requestType=" + thisClass.requestType + "&searchType=" + thisClass.sType + "&query=" + $(thisClass.rTarget).value;
				new Ajax.Request( url, {asynchronous: true, method: 'get', parameters: pars, onComplete: thisClass.showResult});
			}
			this.current = this.source;
		}

		thisClass.stopAutoComplete();
		thisClass.intervalID = window.setInterval(thisClass.checkInput, 300);

		// 엔터 혹은 탭을 눌렀을 경우
		if(thisClass.thisEvent.keyCode==13 || thisClass.thisEvent.keyCode==9)
		{
			thisClass.stopAutoComplete();
			thisClass.autoInsertValue();
			thisClass.destroyResults();
		}

		// 방향키 눌렀을 경우
		if(thisClass.thisEvent.keyCode==40 || thisClass.thisEvent.keyCode==38)
		{
			// 아래 방향키
			if(thisClass.thisEvent.keyCode==40)
			{
				if(thisClass.direction == "up")
				{
					thisClass.selectedList = thisClass.selectedList + 1;
					thisClass.lastSelected = thisClass.selectedList - 1;
				}
				else
				{
					thisClass.selectedList = 0 + thisClass.nextSelect;
				}

				if(thisClass.selectedList > ($("resultListField").childNodes.length - 1))
				{
					thisClass.selectedList = $("resultListField").childNodes.length - 1;
					thisClass.lastSelected = $("resultListField").childNodes.length - 2;
				}

				$("resultListField").childNodes[thisClass.lastSelected].style.backgroundColor = "#FFFFFF";
				$("resultListField").childNodes[thisClass.selectedList].style.backgroundColor = "#999999";

				thisClass.nextSelect = thisClass.selectedList + 1;
				thisClass.lastSelected = thisClass.selectedList;
				thisClass.direction = "down";
			}
		
			// 위 방향키
			if(thisClass.thisEvent.keyCode==38)
			{
				if(thisClass.direction == "down")
				{
					thisClass.lastSelected = thisClass.selectedList;
					thisClass.selectedList = thisClass.selectedList - 1;
				}
				else
				{
					thisClass.lastSelected = thisClass.selectedList;
					thisClass.selectedList = thisClass.selectedList - 1;
				}

				if(thisClass.selectedList < 0)
				{
					thisClass.selectedList = 0;
					thisClass.lastSelected = 1;
				}

				$("resultListField").childNodes[thisClass.lastSelected].style.backgroundColor = "#FFFFFF";
				$("resultListField").childNodes[thisClass.selectedList].style.backgroundColor = "#999999";

				thisClass.direction = "up";
			}

			// 자동 스크롤링 계산
			thisClass.resultLayerHeight = $("resultLayer").offsetHeight - 2; //(-2는 보더 값 제거)
			thisClass.scrollTopLimit = $("resultLayer").scrollTop;
			thisClass.scrollBottomLimit = $("resultLayer").scrollTop + thisClass.resultLayerHeight;
			thisClass.currentListTop = $("resultListField").childNodes[thisClass.selectedList].offsetTop;
			thisClass.currentListBottom = $("resultListField").childNodes[thisClass.selectedList].offsetTop + $("resultListField").childNodes[thisClass.selectedList].offsetHeight;

			// 아래쪽으로 스크롤할 경우
			if(thisClass.scrollBottomLimit < thisClass.currentListBottom)
			{
				$("resultLayer").scrollTop = $("resultLayer").scrollTop + $("resultListField").childNodes[thisClass.selectedList].offsetHeight;
			}

			// 위쪽으로 스크롤할 경우
			if(thisClass.scrollTopLimit > thisClass.currentListTop)
			{
				$("resultLayer").scrollTop = $("resultListField").childNodes[thisClass.selectedList].offsetTop;
			}

			// 값 설정
			thisClass.stopAutoComplete();
			thisClass.setResult($("resultListField").childNodes[thisClass.selectedList].className, $("resultListField").childNodes[thisClass.selectedList].id);
		}
	}

	// 자동 결과값 입력
	this.autoInsertValue = function()
	{
		if($("resultListField"))
		{
			thisClass.setResult($("resultListField").childNodes[thisClass.selectedList].className, $("resultListField").childNodes[thisClass.selectedList].id);
		}
	}

	// 자동 완성 소멸
	this.stopAutoComplete = function()
	{
		if(thisClass.intervalID)
		{
			window.clearInterval(thisClass.intervalID);
		}
	}

	this.checkResult = function()
	{
		if($(thisClass.rTarget).value!="" && $(thisClass.rTarget2).value==0 && thisClass.allowOther==0)
		{
			var code = "alert('존재하지 않는 ' + thisClass.title + '입니다.'); $(thisClass.rTarget).value=''; $(thisClass.rTarget2).value='';"
			thisClass.chkTimeoutId = setTimeout(code, 500);
		}
	}

	// 결과 layer 삭제
	this.destroyResults = function()
	{
		if($("resultLayer"))
		{
			window.clearTimeout(thisClass.timeoutId);
			thisClass.timeoutId = window.setTimeout("document.body.removeChild($('resultLayer'));", 300);
		}
	}

	// 자동 완성 JSON 데이터 처리 함수
	this.showResult = function(originalRequest)
	{
		if(originalRequest.responseText)
		{
			jsonData = originalRequest.responseText.evalJSON(); // JSON Data 파싱
		}
		else
		{
			jsonData.Result = null
		}

		if($("resultLayer"))
		{
			document.body.removeChild($("resultLayer"));
		}
		if(jsonData.Result)
		{
			var targetOffset = $(thisClass.rTarget).cumulativeOffset();
			var resultLayer = document.createElement("div");
			resultLayer.id = "resultLayer";
			resultLayer.style.position = "absolute";
			resultLayer.style.border = "1px solid #999999";
			resultLayer.style.backgroundColor = "#FFFFFF";
			resultLayer.style.top = targetOffset["top"] + 20 + "px";
			resultLayer.style.left = targetOffset["left"] + "px";
			resultLayer.style.overflow = "auto";
			resultLayer.style.overflowX = "hidden";
			resultLayer.style.maxHeight = "100px";

			var resultListField = document.createElement("ul");
			resultListField.style.listStyleType = "none";
			resultListField.style.margin = "0";
			resultListField.style.padding = "0";
			resultListField.style.position = "relative";
			resultListField.id = "resultListField";

			var dataValue = new Array();
			for(var i=0; i < jsonData.Result.value.length; i++)
			{
				var divider = "|"; // 데이터 사이의 구분 문자
				var iText = null;
				var iValue = null;
				var objNo = null;
				dataValue[i] = new Array();

				for(var x=0; x<jsonData.Info.cols.length; x++)
				{
					var colName = jsonData.Info.cols[x].value;
					dataValue[i][x] = jsonData["Result"]["value"][i][colName];

					if(x==jsonData.Info.cols.length-1) { divider = ""; }

					// 출력되는 내용
					if(jsonData.Info.cols[x].visable == true) { if(!iText) { iText = dataValue[i][x] }
					else { iText += " " + divider + " " + dataValue[i][x] } }

					// target 으로 전달되는 내용
					if(jsonData.Info.cols[x].inputStr == true) { iValue = dataValue[i][x]; }

					// 키값
					if(jsonData.Info.cols[x].isKey == true) { objNo = dataValue[i][x]; }
				}
				
				var resultList = document.createElement("li");
				resultList.style.height = "15px";
				resultList.style.padding = "5px 30px 0 0";
				resultList.style.cursor = "pointer";
				resultList.id = objNo;
				resultList.className = iValue;
				resultList.style.whiteSpace = "nowrap";
				resultList.onclick = function() { clearTimeout(thisClass.chkTimeoutId); thisClass.stopAutoComplete; thisClass.setResult(this.className, this.id); thisClass.destroyResults(); }
				resultList.onmouseover = function() { this.style.backgroundColor = "#999999"; }
				resultList.onmouseout = function() { this.style.backgroundColor = "#FFFFFF"; }

				var resultText = document.createTextNode(iText);
				resultList.appendChild(resultText);
				resultListField.appendChild(resultList);
			}

			resultLayer.appendChild(resultListField);
			document.body.appendChild(resultLayer);
		}

		// 첫번째 검색 결과 자동 선택
		thisClass.selectedList = 0;
		thisClass.nextSelect = 0;
		thisClass.lastSelected = 0;
		thisClass.direction = "down";
	}

	this.setResult = function(input, key)
	{
		if(input && key)
		{
			$(thisClass.rTarget).value = input;
			$(thisClass.rTarget2).value = key;
		}
	}
}

function addNewKeyword()
{

}

// 다중 선택 클래스
function multiSelect(rURL, requestType, sType)
{
	var thisClass = this;
	this.rURL = rURL;
	this.requestType = requestType;
	this.sType = sType;
	this.rTarget;
	this.rTarget2;

	this.startMultiSelect = function(obj, layerTitle, sCat)
	{
		thisClass.rTarget = obj.id;
		
		// 추가 변수값 받기
		var pars = obj.getAttribute("var");
		pars = pars.split("&");
		thisClass.rTarget2 = pars[0];

		var screenX = document.documentElement.clientWidth;
		var screenY = document.documentElement.clientHeight;

		var left = (screenX - 500) / 2;
		var top = (screenY - 300) / 2;

		var multiSelectLayer = document.createElement("div");
		multiSelectLayer.id = "selectLayer";
		multiSelectLayer.style.zIndex = "10";
		multiSelectLayer.style.position = "absolute";
		multiSelectLayer.style.width = "500px";
		multiSelectLayer.style.height = "300px";
		multiSelectLayer.style.left = left + "px";
		multiSelectLayer.style.top = top + "px";
		multiSelectLayer.style.border = "1px solid #000000";
		multiSelectLayer.style.background = "#FFFFFF";

		var selectTable = document.createElement("table");
		selectTable.style.margin = "auto";

		var selectTbody = document.createElement("tbody");
		
		var row1 = document.createElement("tr");
		var selectRow2 = document.createElement("tr");

		// 상단 row 시작
		var topCell = document.createElement("td");
		topCell.colSpan = "3";
		topCell.style.height = "30px"

		var titleTable = document.createElement("table");
		titleTable.style.width = "100%";
		var titleTableBody = document.createElement("tbody");
		var titleTableRow = document.createElement("tr");
		var titleTableCell1 = document.createElement("td");
		titleTableCell1.style.textAlign = "center";
		titleTableCell1.style.fontWeight = "bold";
		var titleTableCell2 = document.createElement("td");
		titleTableCell2.style.width = "20px";

		var title = document.createTextNode(layerTitle);

		var closeButton = document.createElement("input");
		closeButton.type = "button";
		closeButton.value = "x";
		closeButton.style.background = "#FFFFFF"
		closeButton.style.border = "1px solid #333333"
		closeButton.style.fontSize = "8pt";
		closeButton.style.width = "18px";
		closeButton.style.height = "18px";
		closeButton.onclick = function() { document.body.removeChild($('selectLayer')); }
		
		titleTableCell1.appendChild(title);
		titleTableCell2.appendChild(closeButton);
		titleTableRow.appendChild(titleTableCell1);
		titleTableRow.appendChild(titleTableCell2);
		titleTableBody.appendChild(titleTableRow);
		titleTable.appendChild(titleTableBody);

		topCell.appendChild(titleTable);
		// 상단 row 끝

		// 첫번째 column 시작
		var selectCell1 = document.createElement("td");
		selectCell1.style.padding = "10px";
		selectCell1.style.textAlign = "center";
		selectCell1.style.verticalAlign = "top";

		var selectTitle1 = document.createElement("div");
		selectTitle1.id = "selectTitle1";
		selectTitle1.style.background = "#E4E4E4";
		selectTitle1.style.width = "200px"
		selectTitle1.style.padding = "5px"
		var selectTitleText1 = document.createTextNode("1차 분류");

		var selectList1 = document.createElement("div");
		selectList1.id = "selectList1";
		selectList1.style.background = "#FFFFFF";
		selectList1.style.border = "2px solid #E4E4E4";
		selectList1.style.width = "206px"
		selectList1.style.height = "206px";

		selectTitle1.appendChild(selectTitleText1);

		selectCell1.appendChild(selectTitle1);
		selectCell1.appendChild(selectList1);
		// 첫번째 column 끝


		// 두번째 column 시작
		var selectCell2 = document.createElement("td");
		//selectCell2.style.padding = "3px";
		selectCell2.style.textAlign = "center";
		
		var arrowIcon = document.createTextNode("▶");

		selectCell2.appendChild(arrowIcon);
		// 두번째 column 끝

		// 세번째 column 시작
		var selectCell3 = document.createElement("td");
		selectCell3.style.padding = "10px";
		selectCell3.style.textAlign = "center";
		selectCell3.style.verticalAlign = "top";

		var selectTitle2 = document.createElement("div");
		selectTitle2.id = "selectTitle2";
		selectTitle2.style.background = "#E4E4E4";
		selectTitle2.style.width = "200px";
		selectTitle2.style.padding = "5px";
		var selectTitleText2 = document.createTextNode("2차 분류");

		var selectList2 = document.createElement("div");
		selectList2.id = "selectList2";
		selectList2.style.background = "#FFFFFF";
		selectList2.style.border = "2px solid #E4E4E4";
		selectList2.style.width = "206px";
		selectList2.style.height = "206px";
		selectList2.style.overflow = "auto";

		selectTitle2.appendChild(selectTitleText2);

		selectCell3.appendChild(selectTitle2);
		selectCell3.appendChild(selectList2);
		// 세번째 column 끝

		row1.appendChild(topCell);
		selectRow2.appendChild(selectCell1);
		selectRow2.appendChild(selectCell2);
		selectRow2.appendChild(selectCell3);
		selectTbody.appendChild(row1);
		selectTbody.appendChild(selectRow2);
		selectTable.appendChild(selectTbody);
		multiSelectLayer.appendChild(selectTable);

		document.body.appendChild(multiSelectLayer);

		this.sendAjaxRequest(this.sType, sCat);
	}

	this.sendAjaxRequest = function(sType, sCat)
	{
		// Ajax request 보내기
		pars = "requestType=" + thisClass.requestType + "&searchType=" + sType + "&searchCat=" + sCat;
		new Ajax.Request( thisClass.rURL, {asynchronous: true, method: 'get', parameters: pars, onComplete: this.setResult });
	}

	this.setResult = function(originalRequest)
	{
		if(originalRequest.responseText)
		{
			var jsonData = originalRequest.responseText.evalJSON(); // JSON Data 파싱
		}
		else
		{
			jsonData.Result = null;
		}

		if(jsonData.Result != null)
		{
			var maxRows = jsonData.Result.value.length;
			var divider = "|"; // 데이터 사이의 구분 문자
			var iText = null;
			var dataValue = new Array();

			thisClass.optionList = document.createElement("div");

			for(var i=0; i<maxRows; i++)
			{
				dataValue[i] = new Array();
				
				for(var z=0; z<jsonData.Info.cols.length; z++)
				{
					var colName = jsonData.Info.cols[z].value;

					dataValue[i][z] = jsonData["Result"]["value"][i][colName];

					if(z==jsonData.Info.cols.length-1) { divider = ""; }
					
					if(jsonData.Info.cols[z].visable == true) { iText = dataValue[i][z]; }

					if(jsonData.Info.cols[z].level == true) { level = dataValue[i][z]; }

					if(jsonData.Info.cols[z].isKey == true) { objNo = dataValue[i][z]; }
					
					if(jsonData.Info.cols[z].inputStr == true) { iValue = dataValue[i][z]; }
				}

				thisClass.makeSelect(iText, level, objNo, iValue, i); // 출력 object 생성
			}
		}
	}

	this.makeSelect = function(iText, level, objNo, iValue, i)
	{
		var selectLayer = "selectList" + level;
		if($(selectLayer).childNodes[0])
		{
			$(selectLayer).removeChild($(selectLayer).childNodes[0]);
		}

		var option = document.createElement("div");
		option.style.padding = "2px 2px 2px 10px";
		option.style.textAlign = "left";
		
		var link = document.createElement("a");
		link.href = "javascript:return true";
		link.rel = "";

		if(level>=2)
		{
			link.onclick = function()
			{
				$(thisClass.rTarget).value = iText;
				$(thisClass.rTarget2).value = objNo;
				document.body.removeChild($('selectLayer'));
				return false;
			}
		}
		else
		{
			link.onclick = function() { thisClass.sendAjaxRequest(thisClass.sType, objNo); }
		}

		var vText = document.createTextNode(iText);
		link.appendChild(vText);
		option.appendChild(link);
		thisClass.optionList.appendChild(option);

		$(selectLayer).appendChild(thisClass.optionList);
	}
}