// A generic function for performming AJAX requests
// It takes one argument, which is an object that contains a set of options
// All of which are outline in the comments, below
function ajax( options ) {

    // Load the options object with defaults, if no
    // values were provided by the user
    options = {
        // The type of HTTP Request
        type: options.type || "POST",

        // The URL the request will be made to
        url: options.url || "",

        // How long to wait before considering the request to be a timeout
        timeout: options.timeout || 5000,

        // Functions to call when the request fails, succeeds,
        // or completes (either fail or succeed)
        onComplete: options.onComplete || function(){},
        onError: options.onError || function(){},
        //onSuccess: options.onSuccess || function(){},
		onSuccess: options.onSuccess || null,

        // The data type that'll be returned from the server
        // the default is simply to determine what data was returned from the
        // and act accordingly.
        data: options.data || ""
    };

    // Create the request object
    //var xml = new XMLHttpRequest();
	/*--추가 내용---------------------------------------------------------------------------*/
	if(window.XMLHttpRequest){
		var xml = new XMLHttpRequest();	
	}else{
		try {
			var xml = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			var xml = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	/*--------------------------------------------------------------------------------------*/

    // Open the asynchronous POST request
    //xml.open("GET", "/some/url.cgi", true);
	var params = (options.data.indexOf("=") > -1) ? options.data : serialize( options.data );			// serialize되지 않은 포맷만 serialize 실행
	if(options.type == "POST") {
		xml.open("POST", options.url, true);
	} else {
		xml.open("GET", options.url + "?" + params, true);
	}

    // We're going to wait for a request for 5 seconds, before giving up
    var timeoutLength = 5000;

    // Keep track of when the request has been succesfully completed
    var requestDone = false;

    // Initalize a callback which will fire 5 seconds from now, cancelling
    // the request (if it has not already occurred).
    setTimeout(function(){
         requestDone = true;
    }, timeoutLength);

    // Watch for when the state of the document gets updated
    xml.onreadystatechange = function(){

		// Wait until the data is fully loaded,
        // and make sure that the request hasn't already timed out
        if ( xml.readyState == 4 && !requestDone ) {

            // Check to see if the request was successful
            if ( httpSuccess( xml ) ) {

                // Execute the success callback with the data returned from the server
				// 성공후 콜백함수가 설정되지 않으면 기본적으로 id가 results인 div를 생성하여 결과를 innerHTML하게 처리
				// 페이징클래스함수에서(pageNavi.class.php) ajax모드일 경우 getAjaxPage() 메소드를 사용하게 되어 있음.
				if(options.onSuccess === null) {
					drawResultPage( httpData( xml, options.type ) );
				} else {
	                options.onSuccess( httpData( xml, options.type ) );
				}

            // Otherwise, an error occurred, so execute the error callback
            } else {
                options.onError();
            }

            // Call the completion callback
            options.onComplete();

            // Clean up after ourselves, to avoid memory leaks
            xml = null;
        }
    };

    // Establish the connection to the server
    if(options.type == "POST") {
		/* 추가 내용---------------------------------------------------------------------------------------*/
		xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xml.setRequestHeader("Content-length", params.length);
		if(xml.overrideMimeType) xml.setRequestHeader("Connection", "close");

		xml.send(params);
		/*--------------------------------------------------------------------------------------------------*/
	} else {
	    xml.send(null);
	}

    // Determine the success of the HTTP response
    function httpSuccess(r) {
        try {
            // If no server status is provided, and we're actually 
            // requesting a local file, then it was successful
            return !r.status && location.protocol == "file:" ||

                // Any status in the 200 range is good
                ( r.status >= 200 && r.status < 300 ) ||

                // Successful if the document has not been modified
                r.status == 304 ||

                // Safari returns an empty status if the file has not been modified
                navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined";
        } catch(e){}

        // If checking the status failed, then assume that the request failed too
        return false;
    }

    // Extract the correct data from the HTTP response
    function httpData(r,type) {
        // Get the content-type header
        var ct = r.getResponseHeader("content-type");

        // If no default type was provided, determine if some
        // form of XML was returned from the server
        var data = !type && ct && ct.indexOf("xml") >= 0;

        // Get the XML Document object if XML was returned from
        // the server, otherwise return the text contents returned by the server
        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the specified type is "script", execute the returned text
        // response as if it was JavaScript
        if ( type == "script" )
            eval.call( window, data );

        // Return the response data (either an XML Document or a text string)
        return data;
    }

	// parameter 생성
	function serialize(pData) {
		
		var sResult = [];

		// 배열 형태면 Form Elements의 배열로 간주
		if(pData.contructor == Array) {
			
			for (var i=0; i < pData.length; i++) {
				var data = pData[i];
				sResult.push(data.name + "=" + encodeURIComponent(data.value));
			}

		} else {						// 그 외에는 key/value 형태의 객체로 간주
			
			for (var data in pData) {
				sResult.push(data + "=" + encodeURIComponent(pData[data]));
			}

		}

		return sResult.join("&");

	}

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// @ 기본적으로 실행될 ajax 실행 함수
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getAjaxPage(ajaxURL, ajaxData) {
	ajax({
		url : ajaxURL
//		,	type : "xml"
		,	data : ajaxData
//		,	onSuccess : function(result) {
//				alert(result);
//			}
	});
}

// 결과를 받아 id가 results인 DIV에 innerHTML하는 메소드
function drawResultPage(result) {
	if(document.getElementById("results")) {
		document.body.removeChild(document.getElementById("results"));
	} 

	// div 태그 생성
	var divEmt = document.createElement('div');
	divEmt.id = 'results';
	document.body.appendChild(divEmt);

	var tDiv = document.getElementById("results");	

	if(document.documentElement.scrollTop < 380) {
		targetYPos = "440";
	} else {
		targetYPos = document.documentElement.scrollTop * 1.3;
	}

	// 위치값 지정
	tDiv.style.position = 'absolute';
	tDiv.style.top = targetYPos + "px";
	tDiv.style.left = '30%';
	tDiv.zIndex = 10000;	

    tDiv.innerHTML += result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////