/*
 * Cellblock general-purpose management console, a component of
 * the Gloto Platform.  See www.gloto.com for more information,
 * terms, and licensing.
 *
 * Copyright (C) 2005-2010, Gloto Corp.
 * http://www.cellblock.com/terms.htm
 */
 
var Gloto = {};

Gloto.Api = function( apiKey ) {
  Gloto.api = this;
  this.apiKey = apiKey;
  var prefix = config.getContext() + "/ugc/api/rest/";

  function JSONscriptRequest( fullUrl, callback, errorCallback )
  {
    this.fullUrl = fullUrl;
    this.callback = callback;
    this.errorCallback = errorCallback;
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.baseUrl = config.getContextDisplay(true) + "/ugc";
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
  }

  JSONscriptRequest.scriptCounter = 1;
  JSONscriptRequest.callbacks = {};
  JSONscriptRequest.prototype.buildScriptTag = function ()
  {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE +
                                "&scriptId=" + this.scriptId +
                                "&callback=Gloto.api.dataHandler" +
				"&baseUrl=" + this.baseUrl );
    this.scriptObj.setAttribute("id", this.scriptId);
  };

  JSONscriptRequest.prototype.removeScriptTag = function ()
  {
    this.headLoc.removeChild(this.scriptObj);
  };

  JSONscriptRequest.prototype.addScriptTag = function ()
  {
    this.headLoc.appendChild(this.scriptObj);
  };

  this.dataHandler = function( data )
  {
    var scriptId = data.scriptId;
    var request = JSONscriptRequest.callbacks[scriptId];
    delete JSONscriptRequest.callbacks[scriptId];

    if( request.errorCallback instanceof Function && data.status != "ok" )
	    request.errorCallback( data );
    else if( request.callback instanceof Function )
      request.callback( data );

    request.removeScriptTag();
  };

  this.call = function( method, parameters, callback, errorCallback )
  {
    var url = prefix + "?method=" + encodeURIComponent( method ) + "&apiKey=" + encodeURI( Gloto.api.apiKey );
    for( param in parameters )
    {
      url += "&" + encodeURIComponent( param ) + "=" + encodeURIComponent( parameters[param] );
    }
    var request = new JSONscriptRequest( url, callback, errorCallback );
    JSONscriptRequest.callbacks[ request.scriptId ] = request;
    request.buildScriptTag();
    request.addScriptTag();
  };
};
