/**
 * Ajax(Asynchronous JavaScript + XML)
 * XmlHttpRequest를 이용해 WAS와 통신할 수 있는 기능을 제공
 */

/**
 * Debug 활성화
 */
var xmlhttp_debug = false;

/**
 * XmlHttpRequest 객체 생성
 */
function createXmlHttpRequest() {

	var xmlHttpRequest = null;
	try {

		if (window.XMLHttpRequest) {
			// If IE7, Mozilla, Safari, and so on: Use native object
			xmlHttpRequest = new XMLHttpRequest();
		} else {
			xmlHttpRequest = getXxmlHttpRequest();

		}
		return xmlHttpRequest;
	} catch (errorObject) {
		showErrorDlg('createXmlHttpRequest()', errorObject);
	}
}

/**
 * XmlHttpRequest 객체 생성
 */
function getXxmlHttpRequest() {
	var xmlhttps = new Array("Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0",
			"Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0",
			"Msxml2.XMLHTTP", "Microsoft.XMLHTTP");
	for (var i = 0; i < xmlhttps.length; i++) {
		try {
			var obj = new ActiveXObject(xmlhttps[i]);
			return obj;
		} catch (errorObject) {
		}

	}
	alert("귀하에 PC에는 XmlHttp Objec가 설치되어 있지 않습니다.\n\n자세한 내용은 전산실로 문의하시기 바랍니다.");
	return null;
}

/**
 * 데이터를 WAS로 전송 actionUrl : 데이터가 전송 되어질 URL or URI event : 전달 Event formObject :
 * 전달될 데이터(Form element of HTML)
 */
function submitXmlRequest(actionUrl, event, formObject, resultType, isLockForm) {
	if (isLockForm == null)
		isLockForm = true;

	if (formObject == null)
		return false;

	if (formObject.isSubmit == true || formObject.isSubmit == "true") {
		return false;
	}

	if (formObject != null && isLockForm == true)
		formObject.isSubmit = true;

	var xmlHttpRequest = createXmlHttpRequest();
	try {
		xmlHttpRequest.open('POST', actionUrl, true);
		xmlHttpRequest.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded;');
		xmlHttpRequest.setRequestHeader('Request-Type', 'XmlHttpRequest');
		xmlHttpRequest.onreadystatechange = function() {
			if (xmlHttpRequest.readyState == 4) {

				hideLoadingBar(); //중복 요청을 막기 위하여 로딩바 추가 2019.08.23

				switch (xmlHttpRequest.status) {
				case 200:
					if (xmlhttp_debug)
						alert(xmlHttpRequest.responseText);
					parseXml(xmlHttpRequest.responseXML,
							xmlHttpRequest.responseText);
					break;
				default:
					var msg = "";
					msg += "URL    : " + actionUrl + "\n\n";
					msg += "Status : " + xmlHttpRequest.status + "\n\n";
					msg += "Text   : " + xmlHttpRequest.statusText + "\n\n";
					alert(msg);
					break;
				}
			}
		};
		var data = formData2QueryString(formObject);

		if (resultType != null)
			data += "&result_type=" + resultType;
		if (xmlhttp_debug)
			alert("fevent=" + URLEncode(event) + "&" + data);
		xmlHttpRequest.send("fevent=" + URLEncode(event) + "&" + data);

		showLoadingBar(); //중복 요청을 막기 위하여 로딩바 추가 2019.08.23

		return true;
	} catch (errorObject) {
		showErrorDlg("submitXmlRequest()", errorObject);
		formObject.isSubmit = false;
		return false;
	}
}

/**
 * Form Object의 데이터값을 추출하여 리턴 (application/x-www-form-urlencoded MIME 형식으로 변환)
 */
function formData2QueryString(formObject) {

	if (formObject == null)
		return "";

	var submitString = '';
	var formElement = '';
	//var lastElementName = '';

	try {

		for (var i = 0; i < formObject.elements.length; i++) {
			formElement = formObject.elements[i];

			if (formElement.name == "fevent")
				continue;

			if (formElement.is_html_editor == "true") {
				formElement.value = getHTMLValue(formElement.name);
			}
			switch (formElement.type) {
			case 'text':
			case 'select-one':
			case 'hidden':
			case 'password':
			case 'textarea':
				submitString += formElement.name + '='
						+ URLEncode(formElement.value) + '&';
				break;
			case 'radio':
				if (formElement.checked) {
					submitString += formElement.name + '='
							+ URLEncode(formElement.value) + '&';
				}
				break;
			case 'checkbox':
				if (formElement.checked) {
					// if(formElement.name = lastElementName) {
					// if(submitString.lastIndexOf('&') == submitString.length -
					// 1) {
					// submitString = submitString.substring(0,
					// submitString.length - 1);
					// }
					// submitString += ',' + URLEncode(formElement.value);
					// }
					// else {
					submitString += formElement.name + '='
							+ URLEncode(formElement.value);
					// }
					submitString += '&';
					// lastElementName = formElement.name;
				}
				break;
			case 'select-multiple':
				for (var j = 0; j < formElement.length; j++) {
					if (formElement.options[j].selected == true) {
						submitString += formElement.name + '='
								+ URLEncode(formElement.options[j].value) + '&';
					}
				}
				break;
			}
		}
		submitString = submitString.substring(0, submitString.length - 1);

		return submitString;
	} catch (errorObject) {
		showErrorDlg("formData2QueryString()", errorObject);
	}
}

/**
 * String을 application/x-www-form-urlencoded MIME 형식으로 변환
 */
function URLEncode(str) {
	return encodeURIComponent(str);
}

/**
 * 결과메세지를 Parsing 처리 return : Result(result.js 참조)
 */
function parseXml(responseXML, responseText, resultType) {

	try {
		var resultNodeList = responseXML.getElementsByTagName("RESULT");
		var rootNode = resultNodeList.item(0);
		var resultType = rootNode.getAttribute("type");

		var requestNodeList = rootNode.getElementsByTagName("REQUEST");
		var requestNode = requestNodeList.item(0);
		var requestUri = requestNode.getAttribute("uri");
		var requestEvent = requestNode.getAttribute("event");
		var requestParameter = rootNode.getElementsByTagName("REQUEST").item(0).text;

		var success = rootNode.getElementsByTagName("SUCCESS").item(0).getAttribute("value");
		//var message = rootNode.getElementsByTagName("SUCCESS").item(0).text;
		var message = rootNode.getElementsByTagName("SUCCESS").item(0).childNodes[0].nodeValue;

		var detailMessage = "";
		if (rootNode.getElementsByTagName("DETAIL-MESSAGE").item(0) != null)
			detailMessage = rootNode.getElementsByTagName("DETAIL-MESSAGE").item(0).childNodes[0].nodeValue;
			//detailMessage = rootNode.getElementsByTagName("DETAIL-MESSAGE").item(0).text;

		var resultObject = new Result(resultType, requestUri, requestEvent);

		resultObject.setRequestParameter(requestParameter);

		if (success.toLowerCase() == "true") {
			success = true;
		} else if (success.toLowerCase() == "false") {
			success = false;
		}

		resultObject.setSuccess(success);
		resultObject.setMessage(message);
		resultObject.setDetailMessage(detailMessage);

		if (resultType.toLowerCase() == "success") {
			// 추가 Parsing 없음
		} else if (resultType.toLowerCase() == "select") {

			var voNode = rootNode.getElementsByTagName("VALUE-OBJECT").item(0);

			var vo = new ValueObject();
			var size = voNode.getAttribute("size");

			for (var i = 0; i < size; i++) {
				var key = voNode.getElementsByTagName("VALUE").item(i)
						.getAttribute("name");
				var value = voNode.getElementsByTagName("VALUE").item(i).text;
				vo.set(key, value);
			}
			resultObject.setSelect(vo);
		} else if (resultType.toLowerCase() == "valueobject") {

			var voNode = rootNode.getElementsByTagName("VALUE-OBJECT").item(0);

			var vo = new ValueObject();
			var size = voNode.getAttribute("size");

			for (var i = 0; i < size; i++) {
				var key = voNode.getElementsByTagName("VALUE").item(i)
						.getAttribute("name");
				var value = voNode.getElementsByTagName("VALUE").item(i).childNodes[0].nodeValue;
				vo.set(key, value);
			}
			resultObject.setValueObject(vo);
		} else if (resultType.toLowerCase() == "rowset") {
			var rowSetNode = rootNode.getElementsByTagName("ROW-SET").item(0);
			var colSize = rowSetNode.getAttribute("cols");
			var rowSize = rowSetNode.getAttribute("rows");

			var rowSet = new RowSet();
			for (var i = 0; i < rowSize; i++) {

				var rowNode = rowSetNode.getElementsByTagName("ROW").item(i);
				//var rowIndex = rowNode.getAttribute("index");
				var row = new Row();
				for (var j = 0; j < colSize; j++) {

					var columnNode = rowNode.getElementsByTagName("COLUMN")
							.item(j);
					var name = columnNode.getAttribute("name");
					var value = columnNode.childNodes[0].nodeValue;
					row.set(name, value);
				}
				rowSet.setRow(row);
			}
			resultObject.setRowSet(rowSet);
		} else if (resultType.toLowerCase() == "xml") {

			var xml = rootNode.getElementsByTagName("XML").item(0).xml;
			resultObject.setXml(xml);
		} else {
			alert("알수 없는 메세지 타입 입니다.\n\ntype : " + resultType);
		}
		try {
			if (doResult != null) {
				doResult(resultObject);
			} else {
				alert("doResult() 함수가 없습니다.");
			}
		} catch (errorObject) {
			showErrorDlg("doResult()", errorObject);
		}
	} catch (errorObject) {
		alert("XML을 분석할 수없습니다.\n\nXML :\n" + responseText);
		showErrorDlg("parseXml()", errorObject);
	}
}

/**
 * 데이터를 WAS로 전송 actionUrl : 데이터가 전송 되어질 URL or URI event : 전달 Event formObject :
 * 전달될 데이터(Form element of HTML)
 */
function submitXmlHttpRequest(actionUrl, event, formObject, isLockForm,
		resultType) {

	if (isLockForm == null)
		isLockForm = true;

	if (formObject == null)
		return false;

	if (formObject.isSubmit == true || formObject.isSubmit == "true") {
		return false;
	}

	if (formObject != null && isLockForm == true)
		formObject.isSubmit = true;

	try {
		xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e2) {
			xmlHttpRequest = false;
		}
	}
	if (!xmlHttpRequest && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlHttpRequest = new XMLHttpRequest();
		} catch (failed) {
			xmlHttpRequest = false;
		}
	}
	if (!xmlHttpRequest)
		alert("Error initializing XMLHttpRequest!");

	try {
		xmlHttpRequest.open('POST', actionUrl, true);
		xmlHttpRequest.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded;');
		xmlHttpRequest.setRequestHeader('Request-Type', 'XmlHttpRequest');
		xmlHttpRequest.onreadystatechange = function() {
			if (xmlHttpRequest.readyState == 4) {
				
				hideLoadingBar(); //중복 요청을 막기 위하여 로딩바 추가 2019.08.23
				
				switch (xmlHttpRequest.status) {
				case 200:
					var responseText = xmlHttpRequest.responseText.replace(
							/^\s\s*/, '').replace(/\s\s*$/, '');
					var resultObject = new Result(resultType, actionUrl, event);
					resultObject.setXml(responseText);
					resultObject.setSuccess(true);
					doResult(resultObject);
					break;
				default:
					var msg = "";
					msg += "URL    : " + actionUrl + "\n\n";
					msg += "Status : " + xmlHttpRequest.status + "\n\n";
					msg += "Text   : " + xmlHttpRequest.statusText + "\n\n";
					alert(msg);
					break;
				}
			}
		};

		var data = formData2QueryString(formObject);

		if (resultType != null)
			data += "&result_type=" + resultType;
		if (xmlhttp_debug)
			alert("fevent=" + URLEncode(event) + "&" + data);
		xmlHttpRequest.send("fevent=" + URLEncode(event) + "&" + data);

		showLoadingBar(); //중복 요청을 막기 위하여 로딩바 추가 2019.08.23

		return true;
	} catch (errorObject) {
		showErrorDlg("submitXmlRequest()", errorObject);
		formObject.isSubmit = false;
		return false;
	}
}