// JSONscriptRequest -- a simple class for accessing Yahoo! Web Services
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function showCMS(s,divId)
{
    //alert(s);
    var sResponse = s; //parseRespHeader(s, '||~');
    var obj = document.getElementById(divId);
    if(obj != null)
        obj.innerHTML = sResponse;
}

function addScript(url,version,passkey,cmsid) {
        var par = "?urlpath=" + url + "&ver=" + version + "&pk=" + passkey + "&id=" + cmsid;
        //alert(par);
        var ajaxURL= rootDir + 'CMS/AjaxCMS.aspx' + par;
            //request = 'http://localhost:1694/TestAjax/testJSON.aspx?0=0';
            var obj = new JSONscriptRequest(ajaxURL);
            obj.buildScriptTag(); // Build the script tag               
            obj.addScriptTag(); // Execute (add) the script tag
        } //end addScript
        
function addScript2(url,version,passkey,cmsid)
{
    var par = "?unique=" + AJAXUniqueID() + "&urlpath=" + url + "&ver=" + version + "&pk=" + passkey + "&id=" + cmsid;
    //alert(par);
    var ajaxURL= rootDir + 'CMS/AjaxCMS2.aspx';
    //alert(ajaxURL);
    // addScript();    
    AJAX_POST(ajaxURL,'showCMS(s,"' + divid + '")',par); 
}


/**********************************************************
*JAVASCRIPT PAGE TO HANDLE STANDARD AJAX CALLS
***********************************************************/
var xmlHttp = null;

function GetXmlHttpObject(handler)
{ 
   

	var objXmlHttp=null;
    //alert('in ajax');
	if (navigator.userAgent.indexOf("Opera")>=0)
	{
		alert("This example doesn't work in Opera") ;
		return;
	}
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP";
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler ;
			return objXmlHttp;
		} 
		catch(e)
		{ 
		alert("Error. Scripting for ActiveX might be disabled"); 
		return;
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler;
		return objXmlHttp;
	}
}

function setErrorTimer(iTicks)
{
    var requestDone = false;
    setTimeout(function(){
         requestDone = true;
    }, iTicks);
}


//***********************************************************************************
//AJAX GET METHODS
function AJAX_GET(sUrl, retFunction)
{
    if (sUrl.length > 0)
    { 
         asyncCall(
    	{
			type         : "html",
			post_type    : "GET",
			url          : sUrl,
			onSuccess   : function(s) { eval(retFunction); }           
		});
    } 
    else
        alert('Bad URL For AJAX GET Request.');
}



//***********************************************************************************
//AJAX POST METHODS
function AJAX_POST(sUrl, retFunction, para)
{
     if (sUrl.length > 0)
     {  
         asyncCall(
    	{
			type         : "html",
			post_type    : "POST",
			url          : sUrl,
			onSuccess    : function(s) { eval(retFunction)},
			data         : para            
		}); 
    }
    else
        alert('Bad URL For AJAX POST Request.');    
} 
 
 
//**************************************************************************************** 
//AJAX RESPONSE FORMATTING
function parseResponseHeader(parseStr)
{
    return xmlHttp.responseText.substr(0,xmlHttp.responseText.indexOf(parseStr));
}
		
function parseResponseHeaderArray(parseStr)
{
    return xmlHttp.responseText.split(parseStr);
}

function parseRespHeader(sResp, parseStr)
{
    return sResp.substr(0,sResp.indexOf(parseStr));
}
		
function parseRespArray(sResp,parseStr)
{
    return sResp.split(parseStr);
}

function AJAXUniqueID()
{
    day = new Date();
    id = day.getTime();
    return id;
}





//****************************************
//ASYNC STUFF
//****************************************
if (typeof XMLHttpRequest === "undefined") {
	XMLHttpRequest = function() {
		return new ActiveXObject(navigator.userAgent.indexOf("MSIE 5") >= 0? "Microsoft.XMLHTTP": "Msxml2.XMLHTTP");
	};
}

function asyncCall(options) {
    // Load the options object with defaults, if no
    // values were provided by the user
    options = {
        // The type of HTTP Request
        post_type: options.post_type || "GET",
        type: options.type || "html",

        // 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 || 15000,

        // 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(){},

        // 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 || "",
        lastError: options.lastError || ""
    };

    // Create the request object
    var xml = new XMLHttpRequest();
    //alert('new ajax ' + options.url);
    // Open the asynchronous POST request

try
{
    xml.open(options.post_type, options.url, true);
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xml.setRequestHeader("Content-length", options.data.length);
    xml.setRequestHeader("Connection", "close");
} catch(err)
    {alert(err);}
	//xml.send(options.data);

    // We're going to wait for a request for 5 seconds, before giving up
    var timeoutLength = 10000;

    // 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;
         options.lastError = 'Request Timed Out.';
    }, 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
        //alert(xml.readyState);
        if ( xml.readyState == 4 && !requestDone ) {
//alert(xml.responseText);
            // Check to see if the request was successful
            if ( httpSuccess( xml ) ) {
                // Execute the success callback with the data returned from the server
                options.onSuccess( httpData( xml, options.type ) );
                // Otherwise, an error occurred, so execute the error callback
            } else {
                if(httpData( xml, options.type ).indexOf('The resource cannot be found') != -1)
                {
                    options.lastError = ' [' + options.url + '] is an invalid URL.';
                }else
            	    options.lastError = 'Unknown Error.';
                options.onError();
            }
            // Call the completion callback
            options.onComplete();

            // Clean up after ourselves, to avoid memory leaks
            xml = null;
        }
    };
    

    // Establish the connection to the server
    try
    {
        xml.send(options.data);
    } catch(err)
    {alert(err);}
    // 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;
    }
}



