﻿var token_id;
var localizacao_destino;

function set_token(id)
{
    token_id = id;
}

function ligacao(envia)
{
	if (!localizacao_destino)
	{
//		localizacao_destino = document.location.href;
		localizacao_destino = "usr.php";
	}

	if (localizacao_destino.substring(localizacao_destino.length - 1, localizacao_destino.length) == "#")
	{
		localizacao_destino = localizacao_destino.substring(0, localizacao_destino.length - 1);
	}
	return ligacao_destino(envia, localizacao_destino)
}

function ligacao_usr(envia)
{
	if (!localizacao_destino)
	{
//		localizacao_destino = document.location.href;
		localizacao_destino = "usr.php";
	}
	if (localizacao_destino.substring(localizacao_destino.length - 1, localizacao_destino.length) == "#")
	{
		localizacao_destino = localizacao_destino.substring(0, localizacao_destino.length - 1);
	}
	return ligacao_destino(envia, localizacao_destino)
}

function ligacao_destino(envia, destino){

	http_req = newXMLHttpRequest();
         if(http_req) {
		
		mostra_div_bloqueio();
	       document.getElementById("indicador").style.visibility = "visible";
		

               http_req.open("POST", destino);

               http_req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	       if (token_id)
		{
			envia = envia + "&token=" + token_id;
		}
//		alert(envia);

               http_req.setRequestHeader('Connection','Close');
			   http_req.setRequestHeader('Content-Lenght',envia.length);

               http_req.onreadystatechange = function(){


//            if (http_req.status == 500)
//    		{
//    			alert("Erro no servidor");
//    		}

                     if (http_req.readyState == 4) {
                         document.getElementById("indicador").style.visibility = "hidden";
			 esconde_div_bloqueio();
					 if (http_req.status == 200)
                     {
                     var resposta = http_req.responseText;
			   var arrayRespostas;
			   var arrayResposta;
//                                 alert(resposta);
              if(resposta != ""){
//                                   alert(resposta);
//                alert(escape(resposta));
				while (escape(resposta.substring(0,1)) == "%uFEFF")
				{
					resposta = resposta.substring(1,resposta.length);
                    while (escape(resposta.substring(0,1)) == "%0D")
                    {
                        resposta = resposta.substring(2,resposta.length);
                    }
				}
//                alert(escape(resposta));

				arrayRespostas = resposta.split(String.fromCharCode(14));
				for (i = 0; i < arrayRespostas.length; i++)
				{



					if (arrayRespostas[i].length > 0)
					{


						arrayResposta = arrayRespostas[i].split(String.fromCharCode(15));
//						alert(escape(arrayResposta[0]));
						if (escape(arrayResposta[0]) == "%01")
						{
							set_token(arrayResposta[1]);
//							alert(token_id);
						}
						else if (escape(arrayResposta[0]) == "%02")
						{
//                          alert(arrayResposta[1]);
  						    document.getElementById(arrayResposta[1]).innerHTML = arrayResposta[2];					
						}
						else if (escape(arrayResposta[0]) == "%03")
						{
							document.getElementById('download_ifrm').src = arrayResposta[1];
						}
						else if (escape(arrayResposta[0]) == "%04")
						{
							alert(arrayResposta[1]);
						}
                        else if (escape(arrayResposta[0]) == "%05")
						{
							document.getElementById("debug").innerHTML += arrayResposta[1];
						}
					}
				}


			   }

                     }
                  }

               }
               http_req.send(envia);
         }
	 else
	 {
		alert("Seu navegador não é suportado pelo sistema de administração");
	 }


      return false;

}

function validaFormulario()
{
  if (document.form_requisicao.id.value == "")
  {
        alert("É necessário inserir um identificador");
          document.form_requisicao.id.focus();
          return false;
  }
  if (document.form_requisicao.placa.value == "")
  {
        alert("É necessário inserir uma placa");
          document.form_requisicao.placa.focus();
          return false;
  }
  if (document.form_requisicao.nota.value == "")
  {
        alert("É necessário inserir o número da nota");
         document.form_requisicao.placa.focus();
         return false;
  }

  if (!validaCNPJ(document.form_requisicao.cedente.value))
  {
     alert("CNPJ inválido");
     return false;
  }
  return ligacao_usr('acao=insere_requisicao&identificador=' + document.form_requisicao.id.value + '&placa=' + document.form_requisicao.placa.value + '&nota=' + document.form_requisicao.nota.value + '&cedente=' + document.form_requisicao.cedente.value);
}


function FiltrarLogin_cadastro(objeto, evento)
{
        if(window.event) // for IE
        {
                tecla = window.event.keyCode;
        }
        else
        {
	       	tecla = evento.which;
        }
	if (tecla == 13)
	{
		if (objeto.value.length == 18 || objeto.value.length == 14)
		{
			ligacao('acao=busca_empresa&cnpj=' + document.frm_cadastro_empresa.cnpj.value);
		}
		return false;
	}
	else
	{
        if (objeto.value.length < 14)
        {
            return FormataCPF(objeto, evento);
        }
        else
        {
            return FormataCNPJ(objeto, evento);
        }
	}
}

function FiltrarLogin(objeto, evento)
{
        if(window.event) // for IE
        {
                tecla = window.event.keyCode;
        }
        else
        {
	       	tecla = evento.which;
        }
/*	if (tecla == 13)
	{
		if (objeto.value.length == 18 || objeto.value.length == 14)
		{
			ligacao('acao=busca_empresa&cnpj=' + document.frm_cadastro_empresa.cnpj.value);
		}
		return false;
	}
	else
	{   */
        if (objeto.value.length < 14)
        {
            return FormataCPF(objeto, evento);
        }
        else
        {
            return FormataCNPJ(objeto, evento);
        }
//	}
}

function FiltrarPlaca_wizard(objeto, evento)
{

        if(window.event) // for IE
        {
                tecla = window.event.keyCode;
        }
        else
        {
	       	tecla = evento.which;
        }
	if (tecla == 13)
	{
		if (objeto.value.length == 7)
		{
			ligacao('acao=wizard_busca_entidade&identificador=' + objeto.value + '&wizard=2');
		}
		return false;
	}
	else
	{
          return FormataPLACA(objeto, evento);
	}

}

function FiltrarLogin_wizard(objeto, evento)
{
        if(window.event) // for IE
        {
                tecla = window.event.keyCode;
        }
        else
        {
	       	tecla = evento.which;
        }
	if (tecla == 13)
	{
		if (objeto.value.length == 18 || objeto.value.length == 14)
		{
			ligacao('acao=wizard_busca_entidade&identificador=' + document.frm_cadastro_empresa.cnpj.value + '&wizard=1');
		}
		return false;
	}
	else
	{
        return FormataCNPJ(objeto, evento);
	}
}

function FiltrarCPF_wizard(objeto, evento)
{
   if(window.event) // for IE
   {
           tecla = window.event.keyCode;
   }
   else
   {
   	tecla = evento.which;
   }
	if (tecla == 13)
	{
		if (objeto.value.length == 14)
		{
			ligacao('acao=wizard_busca_entidade&identificador=' + document.frm_cadastro_pessoa.cpf.value + '&wizard=8');
		}
		return false;
	}
	else
	{
        return FormataCPF(objeto, evento);
	}
}





function monta_string_checkbox(inicio_id)
{
	var check;
	var ret_str = '';
	var count = 1;


	while (check = document.getElementById(inicio_id + count))
	{
		if (check.checked)
		{
			ret_str += "1";
		}
		else
		{
			ret_str += "0";

		}
		count++;
	}
	return ret_str;
}


function login_usr(login, senha)
{
    if (!validaCNPJ(login) && !validaCPF(login))
    {
        alert("CPF/CNPJ inválido");
        return false;
    }

    return ligacao_usr('acao=login_usr&login=' + login + '&senha=' + senha);
}

function efetua_ligacao_emissao_ap(form)
{
     var emite;
     for (i = 0; i < form.emitir.length; i++)
     {
          if (form.emitir[i].checked)
          {
               emite = form.emitir[i].value;
          }
     }

     return ligacao('acao=emite_ap&emitir=' + emite + '&placa=' + form.placa.value + '&data_ida=' + form.data_ida.value + '&data_volta=' + form.data_volta.value + '&sentido=' + form.sentido.value + '&tipo=' + form.tipo.value + '&cnpj_cedente=' + form.cnpj_cedente.value);
}


function mostra_div_bloqueio()
{
        var body = document.getElementsByTagName ('BODY')[0];	
		        
        
        // cria o painel que cobre toda a tela
        this.overlay = document.getElementById('LoadingBoxOverlay');

        // se não existe		
        if(!this.overlay) {

                // cria o elemento e o configura
                this.overlay = document.createElement("div");
                this.overlay.id = 'LoadingBoxOverlay';
                this.overlay.style.display = 'none';
                body.appendChild(this.overlay);

        }//fim se	
    	        
        

    var pageScroll = getPageScroll();
    var pageSize = getPageSize();

        // posiciona e mostra o fundo que bloqueia a ação do usuário
     this.overlay.style.height = pageSize[1]+'px';
     this.overlay.style.display = 'block';
    
      
}

function esconde_div_bloqueio()
{  
  this.overlay.style.display = 'none';
}

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;
	}

	return new Array('',yScroll)
}


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;
	}

	return new Array(pageWidth,pageHeight,windowWidth,windowHeight);
}