var waitElement;

// wait element 

if (window.addEventListener) {
	window.addEventListener('scroll', MoveWaitElement, false);
	window.addEventListener('resize', MoveWaitElement, false);
}
else if (window.attachEvent) {
	window.attachEvent('onscroll', MoveWaitElement);
	window.attachEvent('onresize', MoveWaitElement);
}


var scrollX, scrollY = -1;
function MoveWaitElement() {
	var scrollYT, scrollXT;
	if (!waitElement)
		CreateWaitElement();
	if (typeof(window.pageYOffset) == "number") { 
		scrollYT = window.pageYOffset; 
		scrollXT = window.pageXOffset; 
	} 
	else if (document.body && document.documentElement && document.documentElement.scrollTop) { 
		scrollYT = document.documentElement.scrollTop; 
		scrollXT = document.body.scrollLeft;
	}
	else if (document.body && typeof(document.body.scrollTop) == "number") { 
		scrollYT = document.body.scrollTop; 
		scrollXT = document.body.scrollLeft; 
	} 
	if (scrollX != scrollXT || scrollY != scrollYT) {
		scrollX = scrollXT;
		scrollY = scrollYT;
		var width = document.body.clientWidth;
		waitElement.style.top = scrollYT + "px";
		waitElement.style.right = -scrollXT +  "px";
	}
}


function createXMLHTTP() 
{
	var ajax;
	try
	{  
		ajax=new XMLHttpRequest();  
	}
	catch (e)
	{  
		try
		{
			// Internet Explorer    
			ajax=new ActiveXObject("Msxml2.XMLHTTP");    
		}
		catch (e)
		{    
			try
			{      
				ajax=new ActiveXObject("Microsoft.XMLHTTP");      
			}
			catch (e)
			{
				alert("Problemas para encerrar a sessão, incompatibilidade de versão!");      
				return false;      
			}    
		}
	}
	return ajax;
}

function PreencheArea(p_area, p_pagina, p_Semparam)
{
	if (p_pagina!="igual")
		paginaCache = p_pagina;
	
	var oHTTPRequest = createXMLHTTP();
	
	if (waitElement)
	{
		waitElement.style.visibility = 'visible';
		MoveWaitElement();
	}
	
	var parameters = "";
	oHTTPRequest.open("POST", paginaCache, true);
	oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	oHTTPRequest.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	oHTTPRequest.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	oHTTPRequest.setRequestHeader("Pragma", "no-cache");
	oHTTPRequest.onreadystatechange=function()
	{
		if (oHTTPRequest.readyState==4)
		{
			if (document.getElementById(p_area))
				document.getElementById(p_area).innerHTML = oHTTPRequest.responseText;
			else
				alert("Objeto não encontrador :" + p_area);
				
			if (waitElement)		
				waitElement.style.visibility = 'hidden'; 
			
			extraiScript(oHTTPRequest.responseText);
		}
	}
	
	if (document.forms[0])
	{
		parameters = camposForm();
		oHTTPRequest.send(parameters);	
	}
	else
		oHTTPRequest.send("xptp=0");
	
	/*
	if (p_Semparam == true)
		oHTTPRequest.send(null);
	else if (document.forms[0])
	{
		parameters = camposForm();
		oHTTPRequest.send(parameters);	
	}
	else
		oHTTPRequest.send(null);
	*/	
}



function camposForm()
{
	var buff = [];
	var contador = 0; //viabiliza a contagem de laços do for,  
					  //pois sem ele dá "undefined" nos checkboxes
					  //ou radiobuttons que não estão marcados

	for (i=0;i<document.forms[0].length;i++) 
	{
		campo = document.forms[0].elements[i];
		if(campo.type=="checkbox" || campo.type=="radio")
		{
			if(campo.checked)
			{
				buff[contador] = campo.name + "=" + escape(campo.value);
				contador ++; //incrementa 1 ao contador
			}
		}
		else
		{
			buff[contador] = document.forms[0].elements[i].name + "=" + escape(document.forms[0].elements[i].value);
			contador++;
		}
	}
	return buff.join("&");
}

function extraiScript(texto){
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<SCRIPT', ini);
        
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</SCRIPT>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function CreateWaitElement() 
{
    var elem = document.getElementById('__AjaxCall_Wait');
    var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	if (!elem) {
        elem = document.createElement("div");
        elem.id = '__AjaxCall_Wait';
        elem.style.position = 'absolute';
        elem.style.height = 17;
        elem.style.paddingLeft = "3px";
        elem.style.paddingRight = "3px";
        elem.style.fontSize = "11px";
        elem.style.fontFamily = 'Arial, Verdana, Tahoma';
        elem.style.border = "#000000 1px solid";
        elem.style.backgroundColor = "DimGray";
        elem.style.color = "#ffffff";
        elem.innerHTML = 'Carregando ...';
        elem.style.visibility = 'hidden';
        document.body.insertBefore(elem, document.body.firstChild);
    }
    waitElement = elem;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}




