/*
	XMLHttpRequest 사용법 정리
	
	-속성

	onreadystatechange	: XMLHttpRequest 객체의 상태가 변할때 실행할 핸들러를 지정한다.
	
	readyState			: XMLHttpRequest 객체의 상태가 변할때 각 상태값을 변환한다.
						  0 = uninitialized 개체가 생성되었지만 초기화되지는 못했다.(open 메소드를 호출하지 않은 상태)
						  1 = loading		개체가 생성되었고 초기화되었지만 send 메서드를 호출하지 않은 상태
						  2 = loaded		send 메서드가 호출되었지만 아직 응답단계는 아님
						  3 = interactive	부분 데이터가 전송. responseBody 나 responseText 를 사용하여 이부분 데이터를 가져올 수 있다.
						  4 = complete		모든 데이터가 전송. responseBody 나 responseText 를 사용한 모든 데이터 전송완료.
	
	responseText		: HTTP 요청 결과를 문자열 형태로 반환한다.
	
	responseXML			: HTTP 요청 결과를 XML Document 오브젝트로 반환한다
	
	status				: HTTP 응답코드를 반환한다. 성공인 경우 200
	
	statusText			: HTTP 응답 문자열을 반환한다. 성공인 경우 OK


	XMLHttpRequest 객체 가져오기
		
		인터넷 익스플로러
		this.commInterface = new ActiveXObject("Microsoft.XMLHTTP");

		기타 부라우저
		this.commInterface = new XMLHttpRequest();

	
	-메서드

	abort					: 현재의 HTTP request 를 취소한다.
 
	getAllResponseHeaders	: Retrieves the values of all the HTTP headers.
 
	getResponseHeader		: Retrieves the value of an HTTP header from the response body.
	
	open					: Initializes an MSXML2.XMLHTTP request, and specifies the method, URL, 
							  and authentication information for the request.
 
	send					: Sends an HTTP request to the server and receives a response.
 
	setRequestHeader		: Specifies the name of an HTTP header.
 
	
	oXMLHttpRequest.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);
	
	bstrMethod
		The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND. For XMLHTTP, this parameter is not case-sensitive.

	bstrUrl 
		The requested URL. This can be either an absolute URL, such as "http://Myserver/Mypath/Myfile.asp", or a relative URL, 
		such as "../MyPath/MyFile.asp".

	varAsync[optional]
		boolean 타입
		true 일경우 비동기식, false 일 경우 동기식으로 작동한다.
		디폴트는 true 이고 생략가능하다.

	bstrUser[optional] 
		The name of the user for authentication. If this parameter is Null ("") or missing and the site requires authentication, 
		the component displays a logon window.

	bstrPassword[optional] 
		The password for authentication. This parameter is ignored if the user parameter is Null ("") or missing.



*/

/*
	XMLHttpRequest 객체 생성 및 초기화
	ex) var requester = new Requester();
*/
function Requester(){
	this.action = null;
	this.XML = null;
	this.commInterface = null;	//XMLHttpRequest 객체 초기화

	//XMLHttpRequest 객체를 받아온다.
	this.resetXMLHR();

	return true;
}


//XMLHttpRequest 객체가 존재하는지 체크한다.
Requester.prototype.isAvailable = function(){
	if (this.commInterface == null){

		return false;

	}
	
	return true;
}


//XMLHttpRequest 객체의 상태가 변할때 실행할 핸들러를 지정한다.
Requester.prototype.executeAction = function(){
	
	//alert(this.commInterface.readyState);
	
	//XMLHR object 데이터 전송완료.
	if (this.commInterface.readyState == 4){
		
		window.status = "";
		
		// 데이터 전송 성공
		try{
			//XMLHttpRequest 객체의 응답코드가 200(성공) 이라면...
			if (this.commInterface.status == 200){

				//전송받은 데이타를 문자열로 치환한다.
				this.responseText = this.commInterface.requestXML;
				this.action();
			}
			// 응답코드가 0이 아닌 다른 코드나 무시되었다면
			else if (this.commInterface.status != 0){
				alert("에러!! 해당 URL로부터 응답코드를 받지 못했습니다. 에러사유 : " + this.commInterface.statusText);
			}
		}catch (error){

		}
	}else{
		window.status = "로딩중입니다 잠시만 기다려 주세요.....";
	}

	return true;
}

/* 
	responseText로 받은 데이타를 가져온다. 
	한글출력문제로 인해 responseBody로 변경
	음 이게 바이너리로 받아오는거라는데...

	다시 바이너리를 아스키로 변환
	<script language="vbscript">
		Public Function BinDecode(byVal binData)
			Dim i, byteChr, strV
			For i = 1 to LenB(binData)
				byteChr = AscB(MidB(binData,i,2))
				If byteChr > 127 Then
					i = i + 1
					strV = strV & Chr("&H" & Hex(byteChr) & Hex(AscB(MidB(binData,i,2))))
				Else
					strV = strV & Chr(byteChr)
				End if
			Next
			BinDecode = strV
		End Function
	</script>

	val = requester.getBody();
	document.getElementById("output").innerHTML = BinDecode(val);

	이런식으로...

	이것도 된다는데 안됨..
	iconv("EUC-KR","UTF-8","결과값");
	
	responseText => responseBody

*/
Requester.prototype.getText = function(){

	return this.commInterface.responseText;

}

Requester.prototype.getBody = function(){

	return this.commInterface.responseBody;

}


/* responseXML로 받은 데이타를 가져온다. */
Requester.prototype.getXML = function(){

	return this.commInterface.responseXML;

}


/* 
	XMLHR object 초기화 load URL 
	해당 URL로 질의 데이타를 보낸다.
	비동기식으로 보낸다. 
	open("GET",URL,true) default(Boolean 형) 가 true 이다. 동기식을 사용하려면 false 를 준다.

	var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
	xmlhttp.open("GET","http://localhost/books.xml", false);
	xmlhttp.send();
	var book = xmlhttp.responseXML.selectSingleNode("//book[@id='bk101']");
	WScript.Echo(book.xml);

*/
Requester.prototype.loadURL = function(URL, CGI){

	requester.resetXMLHR();
	requester.commInterface.open("GET", URL + "?" + CGI);
	requester.commInterface.send(null);

	return true;
}

Requester.prototype.loadDATA = function(URL, CGI){

	requester.resetXMLHR();
	requester.commInterface.open("POST", URL);
	requester.commInterface.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	requester.commInterface.send(CGI);  

	return true;
}


/* 존재하는 XMLHttpRequest 객체를 삭제하고 새로운 XMLHttpRequest 객체를 받아온다. */
Requester.prototype.resetXMLHR = function(){
	var self = this;

	if (this.commInterface != null && this.commInterface.readyState != 0 && this.commInterface.readyState != 4){
		this.commInterface.abort();
	}

	//기타 부라우저(모질라, 파이어폭스,IE 7.0 등)
	try{
		this.commInterface = new XMLHttpRequest();

	}catch (error){

		//익스플로러
		try{

			this.commInterface = new ActiveXObject("Microsoft.XMLHTTP");

		}catch (error){
			
			try{

				this.commInterface = new ActiveXObject("Msxml2.XMLHTTP");

			}catch (error){
				
				return false;
			
			}
		
		}
	}

	//XMLHttpRequest 객체의 상태가 변할때 실행할 핸들러를 지정한다.
	this.commInterface.onreadystatechange = function(){
		self.executeAction();
		return true;
	};

	return true;
}

/* 함수 콜 */
Requester.prototype.setAction = function(actionFunction){

	this.action = actionFunction;

	return true;
}

