/**
 * create requests to remote script
 *
 * @param callBackObject opjects's variable name, to make cllback to this object
 * @param cUrl - url to open - can be any remote url (optional)
 * @param afterLoadFunction after data loaded, call this function to operata data with (optional). this function have one object parameter 
 * ctime parameter reserved - to make unique link, for no caching
 * callback parameter reserved - to send to data file callback function
 * charset parameter reserved - to send opened document's charset
 *
 * EXAMPLE
 * oJSreq = new json("oJSreq", "http://localhost//data.js", "testFunction");
 *
 * @author uldis@lursoft.lv
 * @copyright 2009
 */

function json(callBackObject, cUrl, afterLoadFunction)
{
  this.nNextID = 1;
  this.cCurrentID = null;
  this.callBackObject = callBackObject;
  this.callBackFunction = callBackObject + ".onDataLoad";
  this.lLoaded = false;
  this.afterLoadFunction = null;

  // request new script
  // dont make much requests without interval, or be sure, the previous load was succesfull. or for each request make new object..
  this.request = function (cUrl, afterLoadFunction)
  {
    this.lLoaded = false;
    
    if (afterLoadFunction)
      this.afterLoadFunction = afterLoadFunction;
    
    this.newScript (cUrl);
  }
  
  // create script tag for loading data
  this.newScript = function (cUrl)
  {
    this.cCurrentID = this.callBackObject + "_ukjson_" + this.nNextID;
    
    if (cUrl.indexOf("?")==-1)
        cUrl += "?";
        
    cUrl += "&ctime=" + (new Date()).getTime();
    cUrl += "&callback=" + this.callBackFunction;
    cUrl += "&charset=" + this.getCharset();
  
    var oScript = document.createElement("script");
    
    oScript.setAttribute("src", cUrl);
    oScript.setAttribute("type", "text/javascript");
    oScript.setAttribute("id", this.cCurrentID);
    
    oHead = document.getElementsByTagName("head")[0];
    oHead.appendChild(oScript);
    
    this.nNextID += 1;
  }
  
  // remove script tag
  this.removeScript = function(cScriptID)
  {
    oClose = document.getElementById(cScriptID);
    oClose.parentNode.removeChild(oClose); 
  }
  
  // get loaded data
  // close script tag and set loaded
  // @param object - data
  this.onDataLoad = function (oData)
  {
    this.removeScript(this.cCurrentID);
    this.lLoaded = true;
    if (this.afterLoadFunction)
        eval(this.afterLoadFunction + "(oData);");
  }
  
  // is loaded?
  // @return boolean
  this.isLoaded = function()
  {
    return this.lLoaded;
  }
  
  // get opened page's charset
  // @return string
  this.getCharset = function()
  {
    if (document.characterSet)
        return document.characterSet;
    return document.charset;
  }

  
  // firs request
  if (cUrl)
    this.request(cUrl, afterLoadFunction);
}
