////////////////////////////////////////////////////////////////////////////////////////
// This JavaScript file provides generic functions for usage in AJAX transactions.
// Author: Sascha Kalinowski - s.k.rj.br@gmail.com
// Version: 1.4
////////////////////////////////////////////////////////////////////////////////////////
function AjaxUtil() {}

var req;
var callback;
var js;

// 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
//
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=ISO-8859-1");

	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":
           	    if (form.elements[i].selectedIndex >= 0)
                    str += form.elements[i].name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
                break;
            case "radio": 
            case "checkbox":
                if(form.elements[i].checked)
                    str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
                break;
       }
   }
   str = str.substr(0,(str.length - 1));

   return str;
}

// Clear all form Values that are visible, useful to reset an input form
//
function clearFormValues(pFormId)
{
    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":
                form.elements[i].value = "";
                break;
            case "select-one":
                form.elements[i].selectedIndex = 0;
                break;
            case "checkbox":
                form.elements[i].checked = false;
                break;
        }
    }
}

// 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(parseJavascript(req.responseText));
                		if (js != '')
                    			eval(js);
            		}
		}
		else if (req.status == 401) // náo autorizado
		{
			document.location.href = "index.jsp";
		}
	}
}

// Internal funciont:
// Parse inner javascript of the responseText and put it in the variable "js",
// it will be interpreted after the callbacj function, with that the javascirpt 
// functions will be available
//
function parseJavascript(responseText)
{
	var returnText = "";
	var javascript = "";

	scriptEnd = 0;
	scriptBegin = responseText.indexOf("<script");
	if (scriptBegin == -1)
		return responseText;
	while (scriptBegin >= 0)
	{
		returnText += responseText.substring(scriptEnd, scriptBegin);

		scriptBeginEnd = responseText.indexOf(">", scriptBegin) + 1;
		scriptEnd = responseText.indexOf("</script>", scriptBeginEnd);
		scriptSrc = responseText.indexOf("src", scriptBegin);

		if (scriptSrc >= 0 && scriptSrc < scriptEnd)
		{
			srcBegin = responseText.indexOf('"', scriptSrc) + 1;
			srcEnd = responseText.indexOf('"', srcBegin);
			src = responseText.substring(srcBegin, srcEnd);
			AjaxUtil.includeJavaScript(src, 1);
		}
		else
		{
			javascript += responseText.substring(scriptBeginEnd, scriptEnd);
		}

		scriptEnd += 9;
		scriptBegin = responseText.indexOf("<script", scriptEnd);
	}
	js = javascript;

	return returnText + responseText.substring(scriptEnd, responseText.length);
}

var includedJavaScripts = new Array();
// This function includes a remote JavaScript into the current opened page
//
AjaxUtil.includeJavaScript = function (pJavaScriptsURL, pForceLoad)
{
    if (!in_array(pJavaScriptsURL, includedJavaScripts) || pForceLoad == 1)
	{
        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;
}

// Pega uma pagina de determinada URL e coloca no Target DIV
//
function getAjax(pURL, divTarget)
{
    zoomOut();
    document.body.scrollTop = 0;
    $('divMsgCarregando').style.display = "block";
	AjaxUtil.exec('', 'GET', pURL , function(str)
	{
		$(divTarget).innerHTML = str;
		$('divMsgCarregando').style.display = "none";
	});
	
	if (pURL.indexOf('comentario') > -1)
	{
	   numComentariosAdicionados = 0;
	   numComentariosLugarAdicionados = 0;
    }
	//reloadGoogleAd();
}

function getAjaxFotos(pURL, divTarget)
{
    zoomOut();
    document.body.scrollTop = 0;
    $('divMsgCarregando').style.display = "block";
	AjaxUtil.exec('', 'GET', pURL , function(str)
	{
		$(divTarget).innerHTML = str;
		$('divMsgCarregando').style.display = "none";
	});

	//reloadGoogleAd();
}

function getAjaxWithMsg(pURL, divTarget)
{
    zoomOut();
    showPopupDiv('divPopupMsgLoading');
	AjaxUtil.exec('', 'GET', pURL , function(str)
	{
		$(divTarget).innerHTML = str;
		closePopupDiv('divPopupMsgLoading');
	});

	if (pURL.indexOf('comentario') > -1)
	{
	   numComentariosAdicionados = 0;
	   numComentariosLugarAdicionados = 0;
    }
	//reloadGoogleAd();
}

