/*
 *  1. 화일이름		: xajax.js
 *  2. 작성자	    : 신영진
 *  3. 작성일자		: 2008. 01. 02
 *  4. 파일설명		: ajax관련 스크립트 파일
 *  5. 프로그램 변경 내역
 *
 */
xajax = function () {
};

xajax.version = "1.0";
xajax.waitMessage = "잠시만 기다려 주세요! 데이터 수신중입니다..."; // 잠시만 기다려 주세요!
xajax.fatalErrorMessage = "예기치 않은 오류가 발생하였습니다!"; // 예기치 않은 오류가 발생하였습니다!
xajax.defaultErrorMessage = "요청이 실패하였습니다!"; // 요청이 실패하였습니다!
xajax.url = "";
xajax.execute = "true";
xajax.message = "";
xajax.movePage = "";
xajax.openDialog = "true";
xajax.queryString = "";
xajax.receivedData = "";
xajax.async = true;
xajax.type = "POST";
xajax.timeout = 2000000;
xajax.blockUI = true;
xajax.dataType = "html";
xajax.debugMode = true;

xajax.setUrl = function (url) {
	xajax.url = url;
};
xajax.setAsync = function (bool) {
	xajax.async = bool;
};
xajax.setType = function (method) {
	xajax.type = method;
};
xajax.setTimeout = function (time) {
	xajax.timeout = time;
};
xajax.setBlockUI = function (bool) {
	xajax.blockUI = bool;
};
/*
 * "xml": Returns a XML document that can be processed via jQuery.
 * "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
 * "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
 * "json": Evaluates the response as JSON and returns a JavaScript Object.
 * "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)
 * "text": A plain text string.
 */
xajax.setDataType = function (type) {
	xajax.dataType;
};
/**
  * 기존에 담겨진 parameter 정보를 초기화 한다.
  */
xajax.initParameter = function () {
	  xajax.queryString = "";
};

xajax.findFrm = function (name) {
	var frmArray = $("form");
	for (var i = 0; i < frmArray.length; i++) {
		if (frmArray[i].name == name || frmArray[i].id == name) {
			return frmArray[i];
		}
	}
	return null;
};
xajax.addParameter = function (strKey, strValue) {
	if (xajax.queryString != "") {
		xajax.queryString += "&";
	}
	xajax.queryString += strKey + "=" + encodeURIComponent(strValue);
};
/**
  * 객체 자체를 받아 해당 객체의 이름과 값을 읽어 온다. 그리고 parameter에 해당 값을 넣는다.
  * 객체가 null이 아니여야 하지만 객체의 이름 값과 객체의 값도 null이나 빈문자열이 아니여야 한다.
  */
xajax.addParameterObj = function (obj) {
	if (obj != null) {
		if (obj.length == null) {
			if (obj.name != "" && obj.value != "") {
				if (xajax.queryString != "") {
					xajax.queryString += "&";
				}
				xajax.queryString += obj.name + "=" + encodeURIComponent(obj.value);
			}
		} else {
			if (obj.length > 0) {
				for (var i = 0; i < obj.length; i++) {
					if (obj[i].name != "" && obj[i].value != "") {
						if (obj[i].type == "checkbox") {
							if (obj[i].checked == false) {
								continue;
							}
						}
						if (xajax.queryString != "") {
							xajax.queryString += "&";
						}
						xajax.queryString += obj[i].name + "=" + encodeURIComponent(obj[i].value);
					}
				}
			}
		}
	}
};
/**
  * 해당 폼객체 안의 전체 input, select, textarea, checkbox, radio의 값을 파라미터로 셋팅한다.
  * 하지만 jquery serialize()로 한방에 처리.ㅋ
  */
xajax.addParameterForm = function (frm) {
	if (xajax.findFrm(frm) != null) {
		if (xajax.queryString != "") {
			xajax.queryString += "&";
		}
		xajax.queryString += $(xajax.findFrm(frm)).serialize();
	}
};


xajax.simpleSend = function (url, funcSuccess) {
	xajax.setUrl(url);
	xajax.realSendForm(funcSuccess);
};

/*
 * XecureWeb으로 보낸다.
 */
xajax.simpleSendXecure = function (url, funcSuccess) {

	var qs ;
	var path ;
	var cipher;

	qs_begin_index = url.indexOf('?');

	// if action is relative url, get base url from window location
	path = getPath(url)
	// get path info & query string & hash from action url
	if ( qs_begin_index < 0 ) {
		qs = "";
	}
	else {
		qs = url.substring(qs_begin_index + 1, url.length );
	}

	// encrypt QueryString of action field
	if( gIsContinue == 0 ) {
		gIsContinue = 1;
		if( IsNetscape60() )		// Netscape 6.0
			cipher = document.XecureWeb.nsIXecurePluginInstance.BlockEnc(xgate_addr, path, XecureEscape(qs),"GET");
		else {
			cipher = document.XecureWeb.BlockEnc(xgate_addr, path, XecureEscape(qs),"GET");
		}
		gIsContinue = 0;
	}
	else {
		alert(busy_info);
		return false;
	}


	if( cipher == "" )	return XecureWebError() ;

	xajax.url = path + "?q=" + escape_url(cipher);

	// adding character set information
	if(usePageCharset)
		xajax.url += "&charset=" + document.charset;

	if( xajax.queryString != ""){

		var newQueryStr = xajax.queryString;
		newQueryStr = newQueryStr.replace(/[+]/g,"%20");

		if( gIsContinue == 0 ) {
			gIsContinue = 1;
			if( IsNetscape60() )		// Netscape 6.0
				cipher = document.XecureWeb.nsIXecurePluginInstance.BlockEnc ( xgate_addr, path, XecureEscape(newQueryStr), "POST" );
			else{
				cipher = document.XecureWeb.BlockEnc ( xgate_addr, path, XecureEscape(newQueryStr), "POST" );
			}
			gIsContinue = 0;
		}
		else {
			alert(busy_info);
			return false;
		}

		if( cipher == "" )	return XecureWebError() ;

		xajax.queryString = "p="+escape_url(cipher);
	}

	xajax.realSendForm(funcSuccess);
};

/*
 * XecureWeb으로 보낸다.(Form)
 */
xajax.sendFormXecure = function (frmName, url, funcSuccess) {
	xajax.queryString = "";
	xajax.addParameterForm(frmName);
	xajax.simpleSendXecure(url, funcSuccess);
};


xajax.sendForm = function (frmName, url, funcSuccess) {
	xajax.queryString = "";
	xajax.addParameterForm(frmName);
	xajax.setUrl(url);
	xajax.realSendForm(funcSuccess);
};




xajax.fSuccess = function (data, funcSuccess) {
	try {
		var execute = xajax.execute;
		var message = xajax.message;
		var movePage = xajax.movePage;
		var openDialog = xajax.openDialog;
		var body = data;

        var bExecute = (execute == "true" && funcSuccess != "" && funcSuccess != null && funcSuccess != "null");
        var bMessage = (message != null && message != "" && message != "null");

        if(bExecute && bMessage){
          if (openDialog == "true") {
                alertDialog("알림", message, true, body, funcSuccess);
          } else {
            alert(message);
            funcSuccess(body);
          }
        }else if(!bExecute && bMessage){
          if (openDialog == "true") {
                alertDialog("알림", message, true);
          } else {
            alert(message);
          }
        }else if(bExecute && !bMessage){
          funcSuccess(body);
        }

		if (movePage != null && movePage != "" && movePage != "null") {
			document.location = movePage;
		}

	}
	catch (e) {
		var strTmp = xajax.fatalErrorMessage + "<br/>";
		strTmp += e + "<br/>";
		strTmp += e.description + "<br/>";
        alert("fSuccess ajax error dialog"+strTmp);
        if (openDialog == "true") {
                alertDialog("오류발생", strTmp, true);
        } else {
          alert(message);
        }

		if (xajax.blockUI) {
			$.unblockUI();
		}
	}

    $.unblockUI();
};
xajax.fError = function (request, textStatus, error) {
	try {
		if (xajax.blockUI) {
			$.unblockUI();
		}
		if (request.status == 404) {
			alert("\uc694\uccad\ud558\uc2e0 " + xajax.url + " \ud398\uc774\uc9c0\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.");
		} else {

            if (xajax.debugMode) {
              var strTmp = request.responseText;
              try{
                   $.unblockUI();
                openWindow("장애발생", "", 560, 310, false, true, strTmp);
              }catch(e){
                alert(xajax.fatalErrorMessage);
              }

            }else{
              alert(xajax.fatalErrorMessage);
            }
		}
		if (xajax.blockUI) {
			$.unblockUI();
		}
	}
	catch (e) {
		var strTmp = xajax.fatalErrorMessage + "\n";
		strTmp += e + "\n";
		strTmp += e.description + "\n";
		//xmsgbox.show(xmsgbox.ICON_ERROR, "ajax error dialog", strTmp);
        alert("fError ajax error dialog" + strTmp);
		if (xajax.blockUI) {
			$.unblobkcUI();
		}
	}
};
xajax.realSendForm = function (funcSuccess) {
	try {
        ajaxBlockUI();
		$.ajax({
			async:xajax.async,
			type:xajax.type,
			//dataType: xajax.dataType,
			timeout:xajax.timeout,
			data:xajax.queryString,
			url:xajax.url,
			success:function (data) {
				xajax.receivedData = data;
			},
			error:xajax.fError,
			beforeSend:function (xhr) {
                xhr.setRequestHeader("requestKind", "ajax");
			},
			complete:function (xhr, status) {
				if (status == "success") {
					xajax.message = decodeURIComponent(xhr.getResponseHeader("message")).replace(/\+/g, " ");
                    if(xhr.getResponseHeader("execute") != "")
					 xajax.execute = xhr.getResponseHeader("execute");
					xajax.movePage = decodeURIComponent(xhr.getResponseHeader("movePage"));
                    if(xhr.getResponseHeader("openDialog") != null && xhr.getResponseHeader("openDialog") != "")
					   xajax.openDialog = xhr.getResponseHeader("openDialog");

					xajax.fSuccess(xajax.receivedData, funcSuccess);
				}
			}
		});
	}
	catch (e) {
		var strTmp = xajax.defaultErrorMessage + "<br/>";
		strTmp += e + "<br/>";
		strTmp += e.description + "<br/>";
        alert("realSendForm ajax error dialog" + strTmp);
		if (openDialog == "true") {
                alertDialog("오류발생", strTmp, true);
        } else {
          alert(strTmp);
        }
        $.unblockUI();
	}
};

function ajaxBlockUI(){
      $.blockUI(
              {
                message: $('<div class=\"bold_font02\" style=\"font-size:9pt;background:none;\"><img src=\"/images/spinner3-bluey.gif\" align=\"absmiddle\"/>'+xajax.waitMessage+'</div>')
                ,css: {border:'none', width: '320px', height:'36px'}
                    ,overlayCSS:{backgroundColor:'#CCC',opacity:'0.3'}
              }
            );
}
