/*
    Object to encapsulate dojo request
*/


function DojoRequest (inUrl, acceptMimeType)
{
    this.acceptMimeType = acceptMimeType;
    this.urlSeparator = "?";
    this.parameterSeparator = "&";
    this.valueSeparator = "=";
    this.loadFunction = null;
    this.isUploadRequest = false;
    this.formNodeId = null; //Form upload
    this.errorFunction = function(type, data, evt){};
    this.map = new Array();
    var index = inUrl.indexOf(this.urlSeparator);
    if (index >= 0)
    {
	    this.url = inUrl.substring(0, index);
	    var params = inUrl.substring(index+1);
	    var tokenizer = new StringTokenizer(params, this.parameterSeparator);
	    var token = null;
	    while (tokenizer.hasMoreTokens())
	    {
	        token = tokenizer.nextToken();
	        var nameIndex = token.indexOf(this.valueSeparator);
	        if (nameIndex >= 0)
	        {
	            this.putParameter(token.substring(0, nameIndex), token.substring(nameIndex+1));
	        }
	        else
	        {
	            this.putParameter(token, null);
	        }
	    }
	}
	else
	{
	    this.url = inUrl;
	}
}


var stProt = DojoRequest.prototype;

/*
   Put a parameter to request, name value pairs.
*/
stProt.putParameter=function(name, value)
{
    this.map[name] = value;
}


/*
   Get a parameter.

   Return      - int number of tokens in material.
*/
stProt.getParameter=function(name)
{
    return this.map[name];
}

/*
   Put a form to request.
*/


stProt.putForm = function(formNode, encoding, formFilter)
{

	if ((!formNode)||(!formNode.tagName)||(!formNode.tagName.toLowerCase() == "form"))
	{
	    dojo.raise("Attempted to encode a non-form element.");
	}
	if (!formFilter)
	{
	    formFilter = dojo.io.formFilter;
	}
	//var enc = /utf/elmIndex.test(encoding||"") ? encodeURIComponent : dojo.string.encodeAscii;
	var enc = function(str) {return str;}
	
	var values = [];

	for (var elmIndex = 0; elmIndex < formNode.elements.length; elmIndex++)
	{
	    var elm = formNode.elements[elmIndex];
	    if (!elm || elm.tagName.toLowerCase() == "fieldset" || !formFilter(elm))
	    {
	        continue;
	    }
	    var name = enc(elm.name);
	    var type = elm.type.toLowerCase();

        if (type == "select-multiple")
        {
			for (var optIndex = 0; optIndex < elm.options.length; optIndex++)
			{
				if (elm.options[optIndex].selected)
				{
					this.putParameter(name, enc(elm.options[optIndex].value));
				}
			}
		}
		else if (dojo.lang.inArray(type, ["radio", "checkbox"]))
		{
			if(elm.checked)
			{
				this.putParameter(name, enc(elm.value));
			}
		}
		else
		{
			this.putParameter(name, enc(elm.value));
		}
	}

	// now collect input type="image", which doesn't show up in the elements array
	var inputs = formNode.getElementsByTagName("input");
	for (var inpIndex = 0; inpIndex < inputs.length; inpIndex++)
	{
		var input = inputs[inpIndex];
		if (input.type.toLowerCase() == "image" && input.form == formNode
			&& formFilter(input))
		{
			var name = enc(input.name);
			this.putParameter(name, enc(input.value));
			this.putParameter(name + ".x", "0");
			this.putParameter(name + ".y", "0");
		}
	}
}

stProt.putFormShort = function(formNode)
{

	var enc = function(str) {return str;}
	
	var values = [];

	for (var elmIndex = 0; elmIndex < formNode.elements.length; elmIndex++)
	{
	    var elm = formNode.elements[elmIndex];
	    if (!elm || elm.tagName.toLowerCase() == "fieldset")
	    {
	        continue;
	    }
	    var name = enc(elm.name);
	    var type = elm.type.toLowerCase();

        if (type == "select-multiple")
        {
			for (var optIndex = 0; optIndex < elm.options.length; optIndex++)
			{
				if (elm.options[optIndex].selected)
				{
					this.putParameter(name, enc(elm.options[optIndex].value));
				}
			}
		}
		else if (dojo.lang.inArray(type, ["radio", "checkbox"]))
		{
			if(elm.checked)
			{
				this.putParameter(name, enc(elm.value));
			}
		}
		else
		{
			this.putParameter(name, enc(elm.value));
		}
	}

	// now collect input type="image", which doesn't show up in the elements array
	var inputs = formNode.getElementsByTagName("input");
	for (var inpIndex = 0; inpIndex < inputs.length; inpIndex++)
	{
		var input = inputs[inpIndex];
		if (input.type.toLowerCase() == "image" && input.form == formNode)
		{
			var name = enc(input.name);
			this.putParameter(name, enc(input.value));
			this.putParameter(name + ".x", "0");
			this.putParameter(name + ".y", "0");
		}
	}
}

/*
   Build the request to use with dojo.
*/


stProt.buildRequest=function(inMethod, loadFunction, errorFunction)
{
    if (typeof inMethod != "string" || inMethod.toLowerCase() != "get")
    {
        inMethod = "post";
    }
    var context = this.loadFunctionContext;

		var request = {
		url: this.url,
		method: inMethod,
		content: this.buildContent(),
		handleAs: "json",
		load: function(data)
				{
					if (typeof loadFunction != "undefined" && loadFunction != null)
					{
						if (context != null)
						{
						loadFunction.apply(context, arguments);
						}
						else
						{
						loadFunction.apply(this, arguments);
						}
					}
				},
	         
/*
	       encoding: 'utf-8',    
	       mimetype: this.acceptMimeType*/
	      headers:
	       {
	           Accept: this.acceptMimeType
	       }
		}
	
	var sb = new js_stringBuffer();
	//sb.append('HEADERS:<br />');
	for(var b in request.content)
	{
	//sb.append(b + "/" + request.content[b] + "<br />");
	}
	
	dojo.xhrPost(request);
    
}

stProt.buildUploadRequest=function(loadFunction, errorFunction)
{

	    var context = this.loadFunctionContext;

    	//dojo.io.IframeTransport.setUpIframe();
		dojo.require("dojo.io.iframe");
    	dojo.require("dojox.io.xhrMultiPart");
    	
	   	var request =
	    {
      	   url: this.url,    
      	   //transport: "IframeTransport",  	   
	       form: dojo.byId(this.formNodeId),
	       method: "POST",
//	       preventCache: true,
	       handleAs: "json",
		   load: function(data, evt){

                 if (typeof loadFunction != "undefined" && loadFunction != null)
                 {
                     if (context != null)
                     {
                      loadFunction.apply(context, arguments);
                  }
                  else
                  {
                      loadFunction.apply(this, arguments);
                  }
                 }

			}

	     }
	     
	     dojo.io.iframe.send(request);

	 //return request;
    
}

/*
   Build the request to use with dojo.
*/
stProt.buildGetRequest=function(loadFunction, errorFunction)
{
    return this.buildRequest("get", loadFunction, errorFunction);
}

/*
   Build the request to use with dojo.
*/
stProt.buildPostRequest=function(loadFunction, errorFunction)
{
    return this.buildRequest("post", loadFunction, errorFunction);
}

/*
   Build full url.
*/
stProt.buildUrl=function()
{
    var sep = this.urlSeparator;
    var urlResult = this.url;
    for (var name in this.map)
    {
        urlResult += sep + name + "=" + this.getParameter(name);
        sep = this.parameterSeparator;
    }
    return urlResult;
}

stProt.buildContent=function()
{
    var first = true;
    var contentResult = {};
    for (var name in this.map)
    {
        contentResult[name] = this.getParameter(name);
    }
    return contentResult;
}
/*
   Load function.
*/
stProt.setLoadFunction=function(loadFunction, inContext)
{
    if (typeof inContext == "object")
    {
        this.loadFunctionContext = inContext;
    }
    else
    {
        this.loadFunctionContext = null;
    }
    this.loadFunction = loadFunction;
}

/*
   Error function.
*/
stProt.setErrorFunction=function(errorFunction)
{
    this.errorFunction = errorFunction;
}

/*
   Bind.
*/
stProt.execute=function(inMethod, loadFunction, errorFunction)
{
    if (typeof loadFunction == "undefined" || loadFunction == null)
    {
        loadFunction = this.loadFunction;
    }
    if (typeof errorFunction == "undefined" || errorFunction == null)
    {
        errorFunction = this.errorFunction;
    }
       
    if(this.isUploadRequest == true)
    {
   	this.buildUploadRequest(loadFunction, errorFunction);
    }
    else
    {
    this.buildRequest(inMethod, loadFunction, errorFunction);
    }

}


