/**
 * Fun��es para o suporte a AJAX com JSON.
 */

//Exemplo de uso: formAJAX('form_dados', testarSubmit, processarOk, processarErro);

var _ultimoPost = false;

function reenviarPost()
{
   if (_ultimoPost)
		postAJAX(_ultimoPost.url, _ultimoPost.campos, _ultimoPost.funcaoSubmit, _ultimoPost.funcaoOk, _ultimoPost.funcaoErro, _ultimoPost.idDiv);
}

function carregarDiv(pagina, local)
{
   $(local).innerHTML = local;
} 

function formAJAX(idForm, funcaoSubmit, funcaoOk, funcaoErro, idDiv)
{
	if (funcaoSubmit)
	{
		if (!funcaoSubmit())
			return false;
	}

	ajax = newXmlHttp();
	if (ajax)
	{
		var hdDiv = '';
		if (idDiv)
			hdDiv = '&hdDiv=' + idDiv;

		var hdAbas = '';
		if (_hdAbas)
			hdAbas = '&hdAbas=' + _hdAbas;

		ajax._funcaoOk = funcaoOk;
		ajax._funcaoErro = funcaoErro;
		ajax._idDiv = idDiv;

		ajax.requisicao.open("POST", $(idForm).action, true);
		ajax.requisicao.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
		ajax.requisicao.onreadystatechange = function() { _verificaEstado(ajax); }
		ajax.requisicao.send(_criarQueryForm(idForm) + '&hdAjax=sim' + hdDiv + hdAbas);
	}
	else
	{	alert('O seu navegador n�o � capaz de processar a requisi��o do servidor por n�o suportar AJAX. Por favor, atualize a vers�o do seu navegador e repita esta opera��o.');
	}
}

//Exemplo de uso: postAJAX('/portal/Principal', { campo: $('campo').value }, testarSubmit, processarOk, processarErro);
function postAJAX(url, campos, funcaoSubmit, funcaoOk, funcaoErro, idDiv)
{
	if (funcaoSubmit)
	{
		if (!funcaoSubmit())
			return false;
	}

	ajax = newXmlHttp();
	if (ajax)
	{
		var hdDiv = '';
		if (idDiv)
			hdDiv = '&hdDiv=' + idDiv;

		var hdAbas = '';
		if (_hdAbas)
			hdAbas = '&hdAbas=' + _hdAbas;

		ajax._funcaoOk = funcaoOk;
		ajax._funcaoErro = funcaoErro;
		ajax._idDiv = idDiv;

		_ultimoPost = new Object();
		_ultimoPost.url = url;
		_ultimoPost.campos = campos;
		_ultimoPost.funcaoSubmit = funcaoSubmit;
		_ultimoPost._funcaoOk = funcaoOk;
		_ultimoPost._funcaoErro = funcaoErro;
		_ultimoPost._idDiv = idDiv;

		ajax.requisicao.open("POST", url, true);
		ajax.requisicao.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
		ajax.requisicao.onreadystatechange = function() { _verificaEstado(ajax); }
		ajax.requisicao.send(_criarHTTPCampos(campos) + '&hdAjax=sim' + hdDiv + hdAbas);
	}
	else
	{	alert('O seu navegador n�o � capaz de processar a requisi��o do servidor por n�o suportar AJAX. Por favor, atualize a vers�o do seu navegador e repita esta opera��o.');
	}
}

//Exemplo de uso: formAJAX('form_dados', 'divDados');
function formAJAXDiv(idForm, idDiv)
{
	var funcaoOk = function(resposta) { if (resposta.isSucesso) setConteudo(idDiv, eval('resposta.' + idDiv)); else { if(resposta.alert) alert(resposta.alert); setConteudo(idDiv, resposta.alert); } };
	var funcaoErro = function(resposta, xmlHttp, erro) { setConteudo(idDiv, '<b>Erro no servidor: ' + erro + '</b>') };

	formAJAX(idForm, null, funcaoOk, funcaoErro, idDiv);
	setAguarde(idDiv);
}

//Exemplo de uso: postAJAXDiv('/portal/Principal', { campo: $('campo').value }, 'divDados');
function postAJAXDiv(url, campos, idDiv)
{
	var funcaoOk = function(resposta) { if (resposta.isSucesso) setConteudo(idDiv, eval('resposta.' + idDiv)); else { if(resposta.alert) alert(resposta.alert); setConteudo(idDiv, resposta.alert); } };
	var funcaoErro = function(resposta, xmlHttp, erro) { setConteudo(idDiv, '<b>Erro no servidor: ' + erro + '</b>') };

	postAJAX(url, campos, null, funcaoOk, funcaoErro, idDiv);
	setAguarde(idDiv);
}

//Exemplo de uso: getAJAXDiv('pagina.html', 'divConteudo');
function getAJAXDiv(url, idDiv)
{
	ajax = newXmlHttp();
	if (ajax)
	{
		ajax._idDiv = idDiv;

		//ajax.requisicao.open("GET", url, true);
		ajax.requisicao.open("POST", url, true);
		ajax.requisicao.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
		ajax.requisicao.onreadystatechange = function() { 
	         var resposta = unescape(ajax.requisicao.responseText); // Desfaz o que a fun��o URLEncoder.encode() fez
	         resposta = resposta.replace(/\+/g,' '); // Substitue o "+" por um espa�o.
				setConteudo(ajax._idDiv, resposta);
				}
		ajax.requisicao.send('');
	}
	else
	{	alert('O seu navegador n�o � capaz de processar a requisi��o do servidor por n�o suportar AJAX. Por favor, atualize a vers�o do seu navegador e repita esta opera��o.');
	}
}

function getAJAX(url, funcao)
{
	ajax = newXmlHttp();
	if (ajax)
	{
		ajax.requisicao.open("GET", url, true);
		ajax.requisicao.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
		if (funcao)
			ajax.requisicao.onreadystatechange = funcao;
		ajax.requisicao.send('');
	}
	else
	{	alert('O seu navegador n�o � capaz de processar a requisi��o do servidor por n�o suportar AJAX. Por favor, atualize a vers�o do seu navegador e repita esta opera��o.');
	}
}

function _verificaEstado(ajax)
{
	try
	{
	   if (ajax.requisicao.readyState == 4)
	   {
	   	if (ajax.requisicao.status == 200)
	   	{
	   		//l� o texto da resposta e desfaz o escape dos acentos
	         var resposta = unescape(ajax.requisicao.responseText); // Desfaz o que a fun��o URLEncoder.encode() fez
	         resposta = resposta.replace(/\+/g,' '); // Substitue o "+" por um espa�o.

	         //transforma o texto com a nota��o JSON em um objeto JavaScript
	         resposta = JSON.parse(resposta);  // eval('(' + ajax.responseText + ')');

				//se est� Ok e possui divs, deve preencher as divs automaticamente
				if (resposta.isSucesso && resposta._divs)
				{
					try
					{
						var pos = 0;
						var nomeDiv;
		        		for (pos=0; pos < resposta._divs.length; pos++ )
						{	nomeDiv = resposta._divs[pos]
							setConteudo(nomeDiv, eval('resposta.' + nomeDiv));
						}
		        	}  catch(e){}
				}

				//se est� Ok e possui divs a ocultar, deve ocultar as Divs automaticamente
				if (resposta.isSucesso && resposta._ocultarDivs)
				{
					try
					{
						var pos = 0;
						var nomeDiv;
		        		for (pos=0; pos < resposta._ocultarDivs.length; pos++ )
						{	nomeDiv = resposta._ocultarDivs[pos]
							setVisivel(nomeDiv, false);
						}
		        	}  catch(e){}
				}

				//se est� Ok e possui divs a exibir, deve exibir as Divs automaticamente
				if (resposta.isSucesso && resposta._exibirDivs)
				{
					try
					{
						var pos = 0;
						var nomeDiv;
		        		for (pos=0; pos < resposta._exibirDivs.length; pos++ )
						{	nomeDiv = resposta._exibirDivs[pos]
							setVisivel(nomeDiv, true);
						}
		        	}  catch(e){}
				}

				//se est� Ok e possui op��es de sele��o, deve preencher as op��es automaticamente
				if (resposta.isSucesso && resposta._selecao)
				{
					try
					{
						var pos = 0;
						var nomeSelecao;
		        		for (pos=0; pos < resposta._selecao.length; pos++ )
						{	nomeSelecao = resposta._selecao[pos]
							preencherSelect(nomeSelecao, eval('resposta.' + nomeSelecao));
						}
		        	}  catch(e){}
				}

				if (ajax._funcaoOk)
					ajax._funcaoOk(resposta, ajax);
		         //else
		         //   alert('N�o existe fun��o para tratar a resposta do servidor.');
	
	            if (resposta.alert)
	            	alert(resposta.alert)
	      }
	   	else
	   	{
	         if (ajax._funcaoErro)
	            ajax._funcaoErro(resposta, ajax, ajax.requisicao.status + "/" + ajax.requisicao.statusText);
	         else
	            alert('Erro na requisi��o do servidor: ' + ajax.requisicao.status + "/" + ajax.requisicao.statusText);
	      }
	   }
	}
	catch(e)
	{
		alert('Erro na requisi��o do servidor: ' + e);
	}
}

function newXmlHttp()
{
  var xml = null;
  try
  {  xml = new XMLHttpRequest();

     //Se poss�vel, ignora cabecalho usado pelo servidor e forca o padrao "text/xml".
     //Alguns navegadores exigem esse padrao e pode dar erro se o servidor nao utilizar ele
     //if (xmlhttp.overrideMimeType)
     //   xmlhttp.overrideMimeType('text/xml');
  }
  catch(e)
  {
    try {  xml = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch(e1)
    {
       try {  xml = new ActiveXObject("Microsoft.XMLHTTP"); }
       catch(e2) {  return false; }
    }
  }

  var ajax = false;  
  if (xml)
  {  ajax = new Object();
     ajax.requisicao = xml;
  }

  return ajax;
}

function setConteudo(idElemento, conteudo)
{
	var elemento = $(idElemento);
	if (elemento)
	{
		elemento.innerHTML = conteudo;
		setVisivel(idElemento);
		if (conteudo != '')
			execJS(elemento); //executa o JS dentro do arquivo
	}
	else
		alert('Elemento n�o encontrado: ' + idElemento)
}

function setAguarde(idDiv, mensagem)
{
   if (!mensagem)
      mensagem = 'Carregando dados! Aguarde';
	setConteudo(idDiv, '<br><h3><span style="color: #990000;">' + mensagem + '<span style="text-decoration: blink;">...</span></span></h3><br><br>');
}

function execJS(elemento)
{
	var st = elemento.getElementsByTagName('SCRIPT');
	var strExec;
	for (var i=0; i < st.length; i++)
	{
		if (st[i].textContent) {
			strExec = st[i].textContent;
		}
		else if (st[i].text) {
			strExec = st[i].text;
		}
		else if (st[i].innerHTML) {
			strExec = st[i].innerHTML;
		}
		else {
			strExec = false;
		}
		//retira os coment�rios do script p/ n�o dar erro no IExplorer
		strExec = strExec.replace('<!--', '');
		strExec = strExec.replace('-->', '');

		try { if (strExec) eval(strExec); }
		catch(e) { alert('Erro no JS: ' + e); }
	}
}

//Exemplos de uso: setVisivel('divDados');  ou setVisivel('divDados', false);
function setVisivel(idElemento, visivel)
{
	var elemento = $(idElemento);
	if (elemento)
	{
	   if ((arguments.length == 1) || (visivel))
         elemento.style.display = ""; //elemento.style.visibility = "visible";
      else
         elemento.style.display = "none"; //elemento.style.visibility = "hidden";
	}
	else
		alert('Elemento n�o encontrado: ' + idElemento)
}

function limparSelect(idSelect, mensagem)
{
	var select = $(idSelect);
	if (select)
	{
		while (select.options.length > 0)
			select.options[select.options.length - 1] = null;

		if (mensagem)
			select.options[0] = new Option(mensagem, "");
	}
}

function incluirOpcaoSelect(idSelect, chave, valor)
{
	var select = $(idSelect);
	if ((select) && (valor))
		select.options[select.options.length] = new Option(valor, chave);
}

function preencherSelect(idSelect, vetor)
{
	var select = $(idSelect);
	if ((select) && (vetor))
	{
		while (select.options.length > 0)
			select.options[select.options.length - 1] = null;

		for ( indice in vetor )
			select.options[select.options.length] = new Option(vetor[indice]['valor'], vetor[indice]['id']);
   }
}

//Exemplo de uso: $focus('nomeCampo');
function $focus(idElemento)
{
	var elemento = $(idElemento);
	if (elemento)
		try { elemento.focus(); } catch(e){}
}

//Retorna o "value" de qualquer campo pelo seu ID
//Exemplo de uso: $valor('nomeCampo');
function $valor(idElemento)
{
	var elemento = $(idElemento);
	if (elemento)
		try { return elemento.value; } catch(e){ return '' }
}

//Retorna o "value" de qualquer campo pelo seu ID
//Exemplo de uso: $valor('nomeCampo');
function $setValor(idElemento, valor)
{
	var elemento = $(idElemento);
	if (elemento)
		try { elemento.value = valor; } catch(e){ return '' }
}

function $valorRadio(nomeCampo)
{
  try
  {
    var campos = document.getElementsByName(nomeCampo);
    var numero = campos.length;
    var elemento;
    //loop para percorrer todos os elementos
    for (var i=0; i<numero; i++)
    {
        //Pega o elemento
        elemento = campos[i];
        if (elemento.checked)
            return elemento.value;
    }
   }
   catch(e) {}

   return '';
}

function $marcarTodos(nomeCampo, flag)
{
  var marcar = true;
  if (arguments.length > 1 && !flag)
     marcar = false;

  try
  {
    var campos = document.getElementsByName(nomeCampo);
    var numero = campos.length;
    var elemento;
    //loop para percorrer todos os elementos
    for (var i=0; i<numero; i++)
        campos[i].checked = marcar;
   }
   catch(e) {}
}

//Exemplo de uso: $ocultar('nome', 'telefone', 'ddd');
function $ocultar()
{
   for (var i = 0; i < arguments.length; i++)
      setVisivel(arguments[i], false);
}

//Exemplo de uso: $limparOcultar('nome', 'telefone', 'ddd');
function $limparOcultar()
{
   for (var i = 0; i < arguments.length; i++)
   {
      setConteudo(arguments[i], '');
      setVisivel(arguments[i], false);
   }
}

//Exemplo de uso: $exibir('nome', 'telefone', 'ddd');
function $exibir()
{
   for (var i = 0; i < arguments.length; i++)
      setVisivel(arguments[i]);
}

var $;
if (!$ && document.getElementById)
{
  $ = function() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
      var element = arguments[i];
      if (typeof element == 'string') {
        element = document.getElementById(element);
      }
      if (arguments.length == 1) {
        return element;
      }
      elements.push(element);
    }
    return elements;
  }
}
else if (!$ && document.all)
{
  $ = function() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
      var element = arguments[i];
      if (typeof element == 'string') {
        element = document.all[element];
      }
      if (arguments.length == 1) {
        return element;
      }
      elements.push(element);
    }
    return elements;
  }
}
else if (!$)
{	$ = function() { return '' }
}

function $C(elType)
{	return document.createElement(elType);
}

function isEnter(event)
{
	if (!event)
		event = window.event;

	var tecla = 0;
	if (event && event.keyCode)
		tecla = event.keyCode;
	else
	if (event && event.which)
		tecla = event.which;
	else
	if (event && event.charCode)
		tecla = event.charCode;

	if (tecla == 13)
		return true;

	return false;
}

function onEnterExec(event, funcao)
{
	if (isEnter(event))
		funcao();
}

function onEnterFocus(event, idElemento)
{
	if (isEnter(event))
		$focus(idElemento);
}

var _vetorDiv = new Object();
var _hdAbas = '';
var _ultimaDiv = false;

function getAbasVetorDiv()
{
	var abas = '';
	for( chave in _vetorDiv )
		abas = abas + chave + '=' + (_vetorDiv[chave].indice + 1) + ';';

	return abas;
}

function recarregarDiv(idMenuTab, indiceDiv)
{
	var div = _vetorDiv[idMenuTab];
	if (div)
		div.recarregar(indiceDiv);
}

function setTabRecarregar(idDiv)
{
	_ultimaDiv = idDiv;
}

function recarregarUltimaDiv()
{
	if (_ultimaDiv)
	{
		var div = _vetorDiv[_ultimaDiv];
		if (div)
			div.recarregar();
	}
}

/**
 * Formata uma hora em milisegundos para String no formato hh:mm:ss.SSS.
 */
function formatarHora(milisegundos)
{
	var nome = null;
	var retorno = '';

	if (milisegundos < 0)
		milisegundos = milisegundos * -1;

	var valor = Math.floor(milisegundos / (1000 * 60 * 60));

	//verifica se possui as horas
	if (valor > 0)
	{
		retorno = retorno + valor + ":";
		nome = " h.";
	}

	milisegundos = milisegundos % (1000 * 60 * 60);

	valor = Math.floor(milisegundos / (1000 * 60));

	//verifica se possui horas ou minutos
	if ((valor > 0) || (nome != null))
	{
		retorno = retorno + valor + ":";

		if (nome == null)
			nome = " min.";
	}

	milisegundos = Math.floor(milisegundos % (1000 * 60));

	valor = Math.floor(milisegundos / 1000);

	if (valor > 0)
	{
		retorno = retorno + valor + ",";

		if (nome == null)
			nome = " s.";
	}
	else
	{
		retorno = retorno + "0,";
		if (nome == null)
			nome = " s.";
	}

	milisegundos = milisegundos % 1000;
	retorno = retorno + (milisegundos + nome);

	return retorno;
}


function exibirDiv(idMenuTab, indiceDiv)
{
	var div = _vetorDiv[idMenuTab];
	if (div)
		div.exibir(indiceDiv);
}

/**
 * Classe que implementa um vetor de objetos DIV e que mant�m apenas uma vis�vel e as outras ocultas.
 * Usada para implementar um Menu com Tabs.
 */
function VetorDiv(nome)
{
	this.indice = 0;
	this.nomeMenu = nome;
	this.nomes = new Array();
	this.divs = new Array();
	this.cache = true;
	this.incluir = function(idDiv, funcaoCarregar, funcaoOnClick)
	   {
	   	var carregada = true;
	   	if (funcaoCarregar)
	   		carregada = false;
	   	this.divs[this.divs.length] = { _elemento: $(idDiv), _divCarregada: carregada, _funcaoOnClick: funcaoOnClick, _funcaoCarregar: funcaoCarregar };
	   	this.nomes[idDiv] = this.divs.length;
	   };
	this.recarregar = function(indiceDiv)
	   {
	    if (typeof indiceDiv != 'undefined')
	       this.setIndice(indiceDiv);
	   	this.divs[this.indice]._divCarregada = false;
	   	this.exibir(this.indice+1);
	   }
	this.exibir = function(indiceDiv, isFoco)
	   {
	   	this.setIndice(indiceDiv);
	   	for (var i=0; i < this.divs.length; i++)
	   	{
	   		if (i == this.indice)
	   			setVisivel(this.divs[i]._elemento.id);
	   		else
	   			setVisivel(this.divs[i]._elemento.id, false);
	   	}
	   	var _div = this.divs[this.indice];
	   	//se definiu fun��o para carregar
	   	if ((!_div._divCarregada || !this.cache) && _div._funcaoCarregar)
	   	{
	   		_div._funcaoCarregar();
	   		_div._divCarregada = true;
	   	}
	   	//se definiu fun��o onClick
	   	if (_div._funcaoOnClick)
	   		_div._funcaoOnClick();
	   		
	   	_hdAbas = getAbasVetorDiv();

	   	//deve configurar o form_menu para enviar quais s�o as abas escolhidas
	   	var fMenu = $('form_menu');

	   	if ((fMenu) && (fMenu.hdAbas))
	   	{
	   		fMenu.hdAbas.value = _hdAbas;
	   		var fDados = $('form_dados');
	   		if ((fDados) && (fDados.hdAbas))
	   			fDados.hdAbas.value = _hdAbas;
	   	}
	   	if (isFoco)
	   		$focus(this.nomeMenu);

	   	return _div._elemento;
	   };
	this.exibirConteudo = function(indiceDiv, conteudo)
	   {
	   	var div = this.exibir(indiceDiv);
	   	if (div)
	   		setConteudo(div._elemento.id, conteudo);
	   };
	this.setIndice = function(indiceDiv)
	   {
	   	if (typeof indiceDiv == 'number')
	   	{
	   		indiceDiv--;
	   		if (indiceDiv < 0)
	   			this.indice = 0;
	   		else if (indiceDiv >= this.divs.length)
	   			this.indice = this.divs.length;
	   		else
	   			this.indice = indiceDiv;
	   	}
	   	else
	   	{
				//l� a DIV pelo nome
		   	var ind = this.nomes[indiceDiv];
		   	if (ind)
		   		this.indice = ind;
		   	else
		   		alert('Div n�o encontrada: ' + indiceDiv);
		   }
	   };
}

// From prototype library. Try.these(f1, f2, f3);
var Try = {
  these: function() {
    var returnValue;
    for (var i=0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    return returnValue;
  }
}

function getElementsByClassName(classname)
{
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = document.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function extractIFrameBody(iFrameEl)
{
  var doc = null;
  if (iFrameEl.contentDocument) { // For NS6
    doc = iFrameEl.contentDocument; 
  } else if (iFrameEl.contentWindow) { // For IE5.5 and IE6
    doc = iFrameEl.contentWindow.document;
  } else if (iFrameEl.document) { // For IE5
    doc = iFrameEl.document;
  } else {
    alert("Erro: objeto document do IFrame n�o encontrado");
    return null;
  }
  return doc.body;

}

function _criarQueryForm(idForm)
{
    var elementosFormulario = $(idForm).elements;
    var qtdElementos = elementosFormulario.length;
    var queryString = "";
    var elemento;

    //Cria uma funcao interna para concatenar os elementos do form
    this.ConcatenaElemento = function(nome,valor) {
                                if (queryString.length>0) {
                                    queryString += "&";
                                }
                                queryString += escape(nome) + "=" + escape(valor);
                             };

    //Loop para percorrer todos os elementos
    for (var i=0; i<qtdElementos; i++)
    {
        //Pega o elemento
        elemento = elementosFormulario[i];
        if (!elemento.disabled)
        {
            //Trabalha com o elemento caso ele nao esteja desabilitado
            switch(elemento.type)
            {
                //Realiza a acao dependendo do tipo de elemento
                case 'text': case 'password': case 'hidden': case 'textarea':
                    this.ConcatenaElemento(elemento.name,elemento.value);
                    break;
                case 'select-one':
                    if (elemento.selectedIndex>=0) {
                        this.ConcatenaElemento(elemento.name,elemento.options[elemento.selectedIndex].value);
                    }
                    break;
                case 'select-multiple':
                    for (var j=0; j<elemento.options.length; j++) {
                        if (elemento.options[j].selected) {
                            this.ConcatenaElemento(elemento.name,elemento.options[j].value);
                        }
                    }
                    break;
                case 'checkbox': case 'radio':
                    if (elemento.checked) {
                        this.ConcatenaElemento(elemento.name,elemento.value);
                    }
                    break;
            }
        }
    }
    return queryString;
}

function _criarHTTPCampos(vars)
{
   if (vars == null)
      return "";
   var varsString = "";
   for( key in vars ) {
     var value = escape(vars[key]);
     escapePlusRE =  new RegExp("\\\+");
     value = value.replace(escapePlusRE, "%2B");
     if (value == 'undefined') value = '';
     varsString += '&' + key + '=' + value;
   }
   if (varsString.length > 0) {
     varsString = varsString.substring(1); // chomp initial '&'
   }
   return varsString;
}

function _criarHeaderMap(headersText)
{
  extractedHeaders = headersText.split("\n");
  delete extractedHeaders[extractedHeaders.length]; // Del blank line at end
  headerMap = new Array();
  for (i=0; i<extractedHeaders.length-2; i++) {
    head = extractedHeaders[i];
    fieldNameEnding = head.indexOf(":");
    field = head.substring(0, fieldNameEnding);
    value = head.substring(fieldNameEnding + 2, head.length);
    value = value.replace(/\s$/, "");
    headerMap[field] = value;
  }
  return headerMap;
}

//esta parte � um "include" do arquivo "json.js"
/*
    json.js

    The global object JSON contains two methods.

    JSON.stringify(value) takes a JavaScript value and produces a JSON text.
    The value must not be cyclical.

    JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
    return false if there is an error.
*/
var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        if (!x.hasOwnProperty || x.hasOwnProperty(i)) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a.push(s.string(i), ':', v);
                                    b = true;
                                }
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };
    return {
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v === 'string') {
                    return v;
                }
            }
            return;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        parse: function (text) {
            try {
            /*	//express�o retirada devido a extrema lentid�o no IE quando a resposta � muito grande
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                        text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval('(' + text + ')');
			*/
                return eval('(' + text + ')');
            } catch (e) {
                return false;
            }
        }
    };
}();
