////////////////////////////////////////////////////////////////////////////////////////
// This JavaScript file provides generic functions for usage in AJAX transactions.
// Author: Sascha Kalinowski - s.k.rj.br@gmail.com
// Version: 1.1
////////////////////////////////////////////////////////////////////////////////////////
function AjaxUtil() {}

var req;
var callback;

// This function is responsable to begin the procesing request, the parameter are
// pRequestFormId  	--> the form that will be submited in case of POST
// pGetPost			    --> or GET or POST, default is GET
// pURL             --> the URL to be called by the function with AJAX
// pCallback        --> the function that receives the return of AJAX, if empty the default function name is processResponse
// pTargetFieldId	--> the field that will receive the response text data in the innerHTML
// pFocusFieldId	--> the field that will receive the focus after the processing, can be empty
//
AjaxUtil.exec = function (pRequestFormId, pGetPost, pURL, pCallback)
{
    callback = pCallback;
   
	var queryString = null;
	if (pGetPost == "POST" && pRequestFormId != "")
		queryString = getFormValues(pRequestFormId);

	if (window.ActiveXObject) // IE
	{
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest) // not IE
	{
		req = new XMLHttpRequest();
	}
	req.onreadystatechange = processResponse;
	req.open(pGetPost, pURL, true);
	if (pGetPost == "POST")
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

	req.send(queryString);
}

// Internal function: 
// Create the QueryString in case a POST is to be executed via AJAX
//
function getFormValues(pFormId)
{
	var str = "";

	var form = document.getElementById(pFormId);

   	for(var i = 0;i < form.elements.length;i++)
    {
    	switch(form.elements[i].type)
       	{
        	case "text":
			case "textarea":
			case "password":
			case "hidden":
				str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
                break;
           	case "select-one":
                str += form.elements[i].name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
                break;
       }
   }
   str = str.substr(0,(str.length - 1));

   return str;
}

// Internal function:
// Response function, waits until response available and then calls the callback function passing the 
// responseText as parameter if the callback function was specified in the submitAjax
//
function processResponse()
{
	if (req.readyState == 4)
	{
		if(req.status == 200)
		{
            if (callback != '')
                callback(req.responseText);
		}
		else if (req.status == 401) // náo autorizado
		{
			document.location.href = "index.html";
			document.location.reload();
		}
	}
}

var includedJavaScripts = new Array();
// This function includes a remote JavaScript into the current opened page
//
AjaxUtil.includeJavaScript = function (pJavaScriptsURL)
{
    if (!in_array(pJavaScriptsURL, includedJavaScripts))
	{
        includedJavaScripts[includedJavaScripts.length] = pJavaScriptsURL;

        var html_doc = document.getElementsByTagName('head').item(0);
        var js = document.createElement('script');
        js.setAttribute('language', 'javascript');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', pJavaScriptsURL);
        html_doc.appendChild(js);
    }
}

// Internal function:
// Auxiliar funtion to include every remote JavaScript only once
//
function in_array(needle, haystack)
{
    for (var i = 0; i < haystack.length; i++)
	{
        if (haystack[i] == needle)
		{
            return true;
        }
    }
    return false;
}
