/**
 *******************************************
 * $Id: jsonRequest.js 112 2006-08-12 23:21:54Z gregbrown $
 * 
 * REVVER
 * Copyright 2006 REVVER, Inc.
 *
 * Author: Greg Brown, greg@onfocus.net
 * 
 * Description:
 *  The json request is an object that 
 *  other components can create and then
 *  use to make calls to the revver api.
 *******************************************
 */

REVVER.util.jsonRequest = Class.create();
REVVER.util.jsonRequest.prototype = {

    initialize:function(requestor)
    {
        REVVER.log("requestor params: " + requestor.params, "info");
        REVVER.log("requestor elementId: " + requestor.elementId, "info");
        
        // keep browser from caching the script tag by adding the time in the querystring
        this.noCache =  "&noCache=" + (new Date()).getTime();
        
        // assemble the complete url
        this.fullUrl = REVVER.wsApiURL + "?" + requestor.params + this.noCache;
        REVVER.log(this.fullUrl);
        
        // get a handle on the head element so we can append/remove scripts from it.
        this.headElement = document.getElementsByTagName("head").item(0);
        
        // create the id that we'll use on the new script tag
        this.scriptId = 'revverScript-' + requestor.elementId;
        
        // Fetch the element pointed to by the id.
        this.scriptElement = $(this.scriptId);
        
        REVVER.log("intialize completed", "info");
    },
    
    send:function()
    {
        this.removeScriptTag(); // we remove the tag if it already exists
        this.buildScriptTag(); // this create the script tag
        this.addScriptTag(); // the adds the script tag to the page (which in turn executes it)
    },

    buildScriptTag:function()
    {
        // Create the new script tag
        this.scriptElement = document.createElement("script");

        // Setup the src attribute of the script tag
        this.scriptElement.setAttribute("src", this.fullUrl);

        // Set the id attribute of the script tag
        this.scriptElement.setAttribute("id", this.scriptId);

        REVVER.log("buildScriptTag completed", "info");
    },
    
    addScriptTag:function()
    {
        // Create the new script tag which causes the request to occur
        this.headElement.appendChild(this.scriptElement);

        REVVER.log("addScriptTag completed", "info");
    },

    removeScriptTag:function()
    {
        // Destroy the tag, if it exists
        if (this.scriptElement) {
            this.headElement.removeChild(this.scriptElement);
        }

        REVVER.log("removeScriptTag completed", "info");
    }

};
