/* **********************************************************************/
//	Eoneo Inc. AJAX Framework
//
//	@version		2.0.1
//	@copyright		Eoneo inc.
//	@history
//		2.0.1	this.asyncHttp(); 호출을 결과수신 후 다시하여 콜백을 잃어버리는 현상 잡음.
//		2.0.0	비동기방식 통신에서 Que 모드 추가됨 (caoy, 2008.04.06)
//	@usage
//		var obj = new PostBackPrototype;
//		
//		(1) 동기방식
//		if (doSubmit("XML URL"))
//		{
//			// 성공적으로 통신을 마친 경우
//			// oMessage 를 통해 XML 데이터 수신 가능
//			alert(obj.oMessage.xml);
//		}
//
//		(2) 비동기방식
//		obj.doSubmit("XML URL", callBackFunction, callBackErrorFunction);
//			- 통신이 끝나면, callBackFunction 을 호출합니다.
//			- 통신 중에 오류가 발생하면, callBackErrorFunction 을 호출합니다.
//
//		(3) 비동기방식 큐형
//		obj.doSubmitByQue("XML URL", callBackFunction, callBackErrorFunction);
//			- 통신이 끝나면, callBackFunction 이 호출되며,
//			- 다음 Que가 실행됩니다.
//			- 통신 중에 오류가 발생하면, callBackErrorFunction 을 호출합니다.
// **********************************************************************/

// NOTICE : 이 파일은 UTF-8 로 인코딩되어야 합니다.

if (gDebug == undefined)
	var gDebug = false;

//gDebug = true;
function PostBackPrototype()
{
	this.asyncHttp();
	this.bProc = false;
	this.submitQue = [];
	this.lastResult = null;

	this.init();
}

PostBackPrototype.prototype = {
	init:function()
	{
		this.async = false;
		this.callback = null;
		this.currentStatus = false;
		this.oMessage = null;
		this.querystring = [];

		this.rule = null;

		this._visible = [];
		this._hide = [];
	},
	clearValue:function()
	{
		this.querystring = [];
	},
	setValue:function(name, value)
	{
		this.querystring.push(name + "=" + escape(value));
	},
	getValue:function()
	{
		data = this.querystring.join("&");
		this.querystring.length = 0;
		return data;
	},
	getLastObject:function()
	{
		return this.lastResult;
	},
	getLastXML:function()
	{
		return this.lastResult.responseXML;
	},
	getLastText:function()
	{
		return this.lastResult.responseText;
	},
	setValueFromObject:function(obj)
	{
		for (var key in obj)
		{
			this.setValue(key, obj[key]);
		}
		this.setValue('_rnd', Math.random());
	},
	initRule:function(oRuleData)
	{
		this.rule = oRuleData;
	},
	asyncHttp:function(bAsync)
	{
		var _this = this.asyncHttp;
		var _obj = this;

		if (bAsync != undefined)
			_obj.async = bAsync;

		_this.xmlhttp = null;

		try {
			_this.xmlhttp = new XMLHttpRequest();
		} catch (trymicrosoft) {
			try {
				_this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (othermicrosoft) {
				try {
					_this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (failed) {
					_this.xmlhttp = false;
				}  
			}
		}

		_this.post = function(url, query)
		{
			if (_obj.async)
			{ // 비동기 방식
				_this.xmlhttp.open('POST', url, true); 
				_this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				_this.xmlhttp.send(query); 

				_this.xmlhttp.onreadystatechange = function()
				{
					if (_this.xmlhttp.readyState != 4 || _this.xmlhttp.status != 200)
						return false;

					_obj.bProc = false;

					window.status = "";
				
					_obj.lastResult = _this.xmlhttp;

					if(_obj.callBack)
					{
						if (gDebug != undefined && gDebug == true)
						{
							alert(_this.xmlhttp.responseText);
						}

						_obj.callBack(_obj.lastResult.responseXML);
					}

					_obj.init();

					if (_obj.isQueMode())
						_obj.nextQueExecute();
				}

				return true;
			}
			else
			{ // 동기 방식
				_this.xmlhttp.open('POST', url, false); 
				_this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				_this.xmlhttp.send(query); 
				
				window.status = "";

				if (gDebug != undefined && gDebug == true)
				{
					alert(_this.xmlhttp.responseText);
				}

				_obj.lastResult = _this.xmlhttp;

				_obj.init();

				return _obj.lastResult.responseXML;
			}
		}

		return _this;
	},
	isQueMode:function()
	{
		return this.submitQue.length > 0;
	},
	queOptimize:function()
	{
		var dat = [];
		for (var i = 1; i < this.submitQue.length ; i++ )
		{
			dat.push(this.submitQue[i]);
		}
		this.submitQue = dat;
		dat = [];
	},
	firstQueExecute:function()
	{
		if (this.isQueMode())
		{
			this.doSubmit(this.submitQue[0].url, this.submitQue[0].func, this.submitQue[0].errFunc);
		}
	},
	nextQueExecute:function()
	{
		this.queOptimize();
		this.firstQueExecute();
	},
	doSubmitByQue:function(targetURL, callBack, callBackError)
	{
		if (callBack == undefined || callBack == "")
			callBack = function(oXML) {};

		if (callBackError == undefined || callBackError == "")
			callBackError = function(oXML) {};

		this.submitQue.push({url:targetURL, func:callBack, errFunc:callBackError});

		if (this.bProc != true)
		{
			this.firstQueExecute();
		}
	},
	doSubmit:function(targetURL, callBack, callBackError)
	{
		if (targetURL == undefined)
			var targetURL = (gSelf == undefined) ? '/' : gSelf;

		if (this.bProc == true)
		{
			//alert(getMsg("ALREADY_CONNECTION"));
			return false;
		}

		this.bProc = true;

		if (callBack != undefined)
		{
			this.callBack = callBack;

			this.async = true;

			window.status = "서버와 통신 중입니다...";
		}

		var obj = this.asyncHttp(this.async);
		var oXML = obj.post(targetURL, this.getValue());

		if (oXML == undefined)
		{
			alert("서버와의 통신 상태가 고르지 않습니다.");
			return false;
		}

		if (this.async == true)
		{
			return true;
		}

		this.bProc = false;

		try
		{
			var oError = oXML.selectSingleNode("//response/error");
			this.oMessage = oXML.selectSingleNode("//response/message");
		}
		catch (e)
		{
			callBackError(oXML);
		}
	
		if (oError == undefined)
		{
			alert("서버로 부터 정상적인 데이터를 수신하지 못하였습니다. [ERR-1]");
			return false;
		}

		if (parseInt(oError.text) == 1)
		{
			if (this.oMessage != undefined)
			{
				alert("서버로 부터 정상적인 데이터를 수신하지 못하였습니다.\n\n오류 내용 : " + this.oMessage.text);
			}
			else
			{
				alert("서버로 부터 정상적인 데이터를 수신하지 못하였습니다. [ERR-2]");
			}
			return false;
		}

		return true;
	},
	getErrorMsg:function(msg)
	{
		return ('<span style="color:#FF0000"><strong>오류</strong></span> : ' + msg + '<br/><div style="margin:0;padding:10px;background:#EFEFEF;border:1px solid #DEDEDE;line-height:150%;font-family:tahoma;">'+this.textData+'</div>');
	}
}
