/*-------------------------------------------------------------------
 * 프로젝트		: X2 Extended Project
 * 프로그램명	: Ajax 기본 함수
 * 설명			: 

	-- 샘플1 --
        new sendQuery2("<%=x2map.getString("_X2UrlWSS")%>/Index?x2start=SendTestZone","",function(req){
            alert(req.responseText);
        });

	-- 샘플2 --
		function setHandler(){
			if ( xmlhttp.readyState == 4 )
			{
				if ( xmlhttp.status == 200 )
				{
					var txt = xmlhttp.responseText;
					
					if(parseInt(txt)!=0) 
						vote_span.innerHTML=txt+"%";
				}
				else
				{
					//alert(xmlhttp.responseText);
				}
			}
			else
			{
				//alert(xmlhttp.responseText);
			}
		}

		sendQuery("url", "han=1", setHandler);

 * Version		: 1.0
 * 작성일자		: 2008/01/23    작성자 : 한상협
 * 수정일자		: 2009/03/30	수정자 : 김형석 
 * 수정내용		:
 --------------------------------------------------------------------*/
var xmlhttp;

function getXmlHttpRequest()
{
	var xmlhttp = false;

	if ( window.ActiveXObject ){
		try{
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e){
			try{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e2){
				return null;
			}
		}
	}
	else if ( window.XMLHttpRequest )
		return new XMLHttpRequest();
	else
		return null;

	return xmlhttp;
}

// ajax 호출 ver 1.0
function sendQuery( url, query, func )
{
	xmlhttp = getXmlHttpRequest();

	xmlhttp.open( "POST", url, true );
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
	xmlhttp.onreadystatechange = func;
	xmlhttp.send( query );
}

// ajax 호출 ver 2.0
function sendQuery2( url, query, func ){
    var thisObj=this;
    
	this.req = getXmlHttpRequest();
	this.req.open( "POST", url, true );
	this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
	
	this.req.onreadystatechange = function(){
		if ( thisObj.req.readyState == 4 ){
			if ( thisObj.req.status == 200 || thisObj.req.status == 304){
			    var callfunc=eval(func);
			    callfunc(thisObj.req);
			}
			else alert("서버와 통신이 지연되고 있습니다. 다시 시도해 주세요.");
		}
	}
	
	this.req.send( query );
}

function sendQueryMultipart( url, query, func ){
    var thisObj=this;
    
	this.req = getXmlHttpRequest();
	this.req.open( "POST", url, true );
	this.req.setRequestHeader("Content-Type", "multipart/text-message;boundary=x2-message");
	
	this.req.onreadystatechange = function(){
		if ( thisObj.req.readyState == 4 ){
			if ( thisObj.req.status == 200 || thisObj.req.status == 304){
			    var callfunc=eval(func);
			    callfunc(thisObj.req);
			}
			else alert("서버와 통신이 지연되고 있습니다. 다시 시도해 주세요.");
		}
	}
	
	this.req.send( query );
}

function startsWith (str, pattern) {
	return str.indexOf(pattern) === 0;
}

function endsWith (str, pattern) {
    var d = str.length - pattern.length;
    return d >= 0 && str.lastIndexOf(pattern) === d;
}



function getJSON(text){
	text = decodeURL(text);
	try{
		if(!text) {
			return false;
		}
		
		if(text == '{\"list\":[]}') {
			return false;
		}
		
		if(!startsWith(text, "(")) text = "(" + text;
		if(endsWith(text, "\"}]}")) { text = text + ")" ; }//alert('0'); 
		else if(endsWith(text, "}}")) { text = text + ")" ; }
		else if(endsWith(text, "}")) {text = text + "\"}]})" ; }
		else if(endsWith(text, "}]")){ text = text + "\"}]})"; } 
		else if(endsWith(text, "}]}")) { text = text + "\"}]})";}
		else if(endsWith(text, "}]})")) { text = text + "\"}]})"} 
		else if(endsWith(text, "\"")) { text = text + "}]})";}
		else if(endsWith(text, "\"}")) { text = text + "]})";} 
		else if(endsWith(text, "\"}]")) { text = text + "})";} 
		else if(!endsWith(text, "\"}]})")) { text = text + "\"}]})";}
		
		
		if(!startsWith(text, "(")) text = "(" + text;
		if(!endsWith(text, ")")) text = text + ")";
		
		var obj = eval(text);

		// 에러가 발생했다면 "error"라는 key 이름으로 object에 value가 입력되어 있다고 가정한다.
		if(obj.error) {
			alert("비동기 통신에 문제가 생겼습니다. ["+obj.error+"]");
			return;
		}
		
		if(typeof obj == "object") return obj;
	}
	catch(e){ alert(e); return false; }
}


function getJSON2(text){
	text = decodeURL(text);
	try{
		if(!text) {
			return false;
		}
		
		if(text == '{\"list\":[]}') {
			return false;
		}
		
		if(!startsWith(text, "(")) text = "(" + text;
		if(!endsWith(text, ")")) text = text + ")";
		
		var obj = eval(text);

		// 에러가 발생했다면 "error"라는 key 이름으로 object에 value가 입력되어 있다고 가정한다.
		if(obj.error) {
			alert("비동기 통신에 문제가 생겼습니다. ["+obj.error+"]");
			return;
		}
		
		if(typeof obj == "object") return obj;
	}
	catch(e){ alert(e); return false; }
}

function decodeURL(str){
    var s0, i, j, s, ss, u, n, f;
    s0 = "";                // decoded str
    for (i = 0; i < str.length; i++){   // scan the source str
        s = str.charAt(i);
        if (s == "+"){s0 += " ";}       // "+" should be changed to SP
        else {
            if (s != "%"){s0 += s;}     // add an unescaped char
            else{               // escape sequence decoding
                u = 0;          // unicode of the character
                f = 1;          // escape flag, zero means end of this sequence
                while (true) {
                    ss = "";        // local str to parse as int
                        for (j = 0; j < 2; j++ ) {  // get two maximum hex characters for parse
                            sss = str.charAt(++i);
                            if (((sss >= "0") && (sss <= "9")) || ((sss >= "a") && (sss <= "f"))  || ((sss >= "A") && (sss <= "F"))) {
                                ss += sss;      // if hex, add the hex character
                            } else {--i; break;}    // not a hex char., exit the loop
                        }
                    n = parseInt(ss, 16);           // parse the hex str as byte
                    if (n <= 0x7f){u = n; f = 1;}   // single byte format
                    if ((n >= 0xc0) && (n <= 0xdf)){u = n & 0x1f; f = 2;}   // double byte format
                    if ((n >= 0xe0) && (n <= 0xef)){u = n & 0x0f; f = 3;}   // triple byte format
                    if ((n >= 0xf0) && (n <= 0xf7)){u = n & 0x07; f = 4;}   // quaternary byte format (extended)
                    if ((n >= 0x80) && (n <= 0xbf)){u = (u << 6) + (n & 0x3f); --f;}         // not a first, shift and add 6 lower bits
                    if (f <= 1){break;}         // end of the utf byte sequence
                    if (str.charAt(i + 1) == "%"){ i++ ;}                   // test for the next shift byte
                    else {break;}                   // abnormal, format error
                }
            s0 += String.fromCharCode(u);           // add the escaped character
            }
        }
    }
    return s0;
}