var req;

//Funcionando
function loadXMLDoc(url,onde) {
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari/IE7)
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        //req.onde = onde;
        //req.onreadystatechange = processReqChange;
        req.onreadystatechange = function() { processReqChange( onde ); };
        req.open("GET", url, true);
        req.send(null);
    // Procura por uma versao ActiveX (IE até 6)
    } else if (window.ActiveXObject) {
        //req = new ActiveXObject("Microsoft.XMLHTTP");
        req = new ActiveXObject("Msxml2.XMLHTTP");
        if (req) {
	        //req.onde = onde;
		    //req.onreadystatechange = processReqChange;
            req.onreadystatechange = function() { processReqChange( onde ); };
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processReqChange(onde) {
    if (req.readyState == 4) { // apenas quando o estado for "completado"
        if (req.status == 200) { // apenas se o servidor retornar "OK"
            //document.getElementById(req.onde).innerHTML = req.responseText;
            document.getElementById(onde).innerHTML = req.responseText;
        } else {
            alert("Houve um problema ao obter os dados:n" + req.statusText);
        }
    }
}

function ver_help(arquivo) {
	url = arquivo;
	openWindow( url, 850, 600 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
}

//**********************

function fecha(valor) {
	mensagem(false,'pesquisa','');
	mensagem(false,'resultado','');
}

function gera_parcelas(contrato) {
	confirma = confirm("Deseja realmente gerar as parcelas do contrato "+contrato+"?");
	if (confirma == 1) {
		mensagem(true,'processa','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"><br>Gerando Parcelas...</td></tr></table>');
		url = "cadastros_contratos_geraparcelas.php?contrato="+contrato+"&oper=G";
		loadXMLDoc(url,'processa');
	}
}

function aceite_tecnico(visita) {
	encerra = confirm("Deseja ACEITAR TECNICAMENTE esta visita?");
	if (encerra==1) {
		url = "atendimento_visitas_aceite_gravar.php?tipo=T&id="+visita;
		openWindow( url, 10, 10 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
		//openWindow( url, 850, 600 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
	}
}

function aceite_cliente(visita) {
	encerra = confirm("Deseja ACEITAR esta visita?");
	if (encerra==1) {
		url = "atendimento_visitas_aceite_gravar.php?tipo=C&id="+visita;
		openWindow( url, 10, 10 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
	}
}

function encerra_visita(visita) {
	encerra = confirm("Deseja ENCERRAR esta visita?");
	if (encerra==1) {
		//mensagem(true,'processamento','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"></td></tr></table>');
		url = "atendimento_visitas_encerra.php?id="+visita;
		openWindow( url, 10, 10 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
		//loadXMLDoc(url,'processamento');
	}
}

function encerra_chamado(chamado) {
	document.formulario.submit();
}

function muda_tarefas(valor) {
	var ori_empresa = document.formulario.id_empresa.value;
	mensagem(true,'div_id_tarefa','<table width="100%"><TR ALIGN="left" VALIGN="middle"><TD><IMG SRC="images/carregando_pequeno.gif" WIDTH="16" HEIGHT="16" BORDER="0"></td></tr></table>');
	url = "atendimento_visitas_carrega_tarefas.php?";
	url = url+"empresa="+ori_empresa;
	loadXMLDoc(url,'div_id_tarefa');
}

function carrega_natureza(valor) {
	var ori_fornecedor = document.formulario.id_fornecedor.value;
	mensagem(true,'div_id_natureza','<table width="100%"><TR ALIGN="left" VALIGN="middle"><TD><IMG SRC="images/carregando_pequeno.gif" WIDTH="16" HEIGHT="16" BORDER="0"></td></tr></table>');
	url = "financeiro_diario_carrega_natureza.php?";
	url = url+"fornecedor="+ori_fornecedor;
	loadXMLDoc(url,'div_id_natureza');
}

function init_chamados(chamado,operacao) {
	mensagem(true,'atendimentos','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"><br>Carregando Atendimentos...</td></tr></table>');
	url = "atendimento_chamados_carrega_itens.php?";
	url = url+"chamado="+chamado;
	url = url+"&operacao="+operacao;
	loadXMLDoc(url,'atendimentos');
}

function grava_atendimento(chamado) {
	var ori_descricao  = document.formulario.descricao.value; //document.getElementById("descricao").value;
	var ori_observacao = document.formulario.observacao.value; //document.getElementById("observacao").value;

	mensagem(true,'trabalho','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"><br>Gravando Atendimentos...</td></tr></table>');
	url = "atendimento_chamados_grava_atendimento.php?";
	url = url+"chamado="+chamado;
	url = url+"&descricao="+ori_descricao;
	url = url+"&observacao="+ori_observacao;
	loadXMLDoc(url,'trabalho');
	mensagem(false,'trabalho');
	
	document.formulario.descricao.value  = "";
	document.formulario.observacao.value = "";
	init_chamados(chamado,'I');
}

function valida_chamado(chamado) {
	var ori_descricao  = document.formulario.descricao.value; //document.getElementById("descricao").value;
	var ori_observacao = document.formulario.observacao.value; //document.getElementById("observacao").value;

	if (ori_descricao!="") {
		alert("Voce deve primeiro gravar o atendimento digitado!");
	} else {
		mensagem(true,'encaminha','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"></td></tr></table>');
		url = "atendimento_chamados_atende_valida.php?";
		url = url+"chamado="+chamado;
		loadXMLDoc(url,'encaminha');
	}
}

function encaminha_chamado(chamado,tipo,user) {
	var ori_descricao  = document.formulario.descricao.value; //document.getElementById("descricao").value;
	var ori_observacao = document.formulario.observacao.value; //document.getElementById("observacao").value;
	if (ori_descricao!="") {
		alert("Voce deve primeiro gravar o atendimento digitado!");
	} else {
		mensagem(true,'encaminha','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"></td></tr></table>');
		url = "atendimento_chamados_encaminha.php?";
		url = url+"chamado="+chamado;
		url = url+"&tipo="+tipo;
		url = url+"&user="+user;
		loadXMLDoc(url,'encaminha');
	}
}

function ver_notafiscal(id,nota) {
	url = "financeiro_faturas_vernota.php?nota="+nota+"&id="+id;
	openWindow( url, 850, 600 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
	/*
	url = "notasfiscais/nfe_"+nota+".pdf";
	openWindow( url, 850, 600 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );

	url = "notasfiscais/bol_"+nota+".pdf";
	openWindow( url, 850, 600 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );
	*/
}function ver_pagcons(id) {	url = "financeiro_pagamentos_verrecibo.php?id="+id;	openWindow( url, 850, 600 ,0 ,0 ,0 ,0 ,1 ,1 ,10 ,10 );}

function envia_senha(usuario) {
	dummy = confirm("Deseja enviar o login de acesso para este usuário?");
	if (dummy == 1) {
		mensagem(true,'processa','<table width="100%"><TR ALIGN="center" VALIGN="middle"><TD><IMG SRC="images/carregando.gif" WIDTH="32" HEIGHT="32" BORDER="0"><br>Aguarde...</td></tr></table>');
		url = "administracao_usuarios_envia_senha.php?id="+usuario;
		loadXMLDoc(url,'processa');
		//mensagem(true,'processamento','');
	}

}

//**********************

//Funcoes Genericas
function strzero(string,tamanho) {
	zeros = '';
	for (i = 1; i <= tamanho; i++) {
   		zeros = zeros+'0';
	}
	nstr = zeros+string;
	result = nstr.substr(nstr.length-tamanho,tamanho);
	return result;
}


function sleep(comando,segundos) {
	setTimeout(comando,segundos*1000)
}

function paraNumero(valor) {
	valor = valor.replace(' ','');
	valor = valor.replace('.','');
	if (valor==null || valor=="") {
		valor = 0;
	} else {
		valor = valor.replace(',','.');
		valor = parseFloat(valor);
	}
	return valor;
}

function paraString(valor) {
	valor = valor.toFixed(2); 
	valor = valor.replace('.',',');
	return valor;
}

function mensagem(mostra,onde,mensagem) {
	if ( mostra ) {
   		document.getElementById(onde).innerHTML = "<font color='#0000C1'>"+mensagem+"</font>";
   	} else {
   		document.getElementById(onde).innerHTML = ""; //parent.
	}
}

function formata_moeda(valor) {
	var result = valor;
	result = result.toFixed(2); //toPrecision ou toFixed
	result = result.replace('.',',');
	return result;
}

//<script language="JavaScript">
//</script>

//<a href="javascript:history.back()" class="cz_azT">Voltar</a>



//Usage: openWindow( url , w , h , tb , stb , L , mb , sb , rs , x , y )
//# url - The URL of the page to open. Example: "http://scriptasylum.com".
//# w - The width of the window in pixels.
//# h - The height of the window in pixels (doesn't include menubars).
//# tb - Toolbar visible? 1 = yes, 0 = no.
//# stb - Status bar visible? 1 = yes, 0 = no.
//# L - Linkbar visible? 1 = yes, 0 = no.
//# mb - Menubar visible? 1 = yes, 0 = no.
//# sb - Scrollbars visible? 1 = yes, 0 = no.
//# rs - Resizable window? 1 = yes, 0 = no.
//# x - The horizontal position of the window from the left of the screen.
//# y - The vertical position of the window from the top of the screen.

function openWindow(url,w,h,tb,stb,l,mb,sb,rs,x,y) {
	x = (screen.width-w)/2;
	y = (screen.height-h)/2;

	var t=(document.layers)? ',screenX='+x+',screenY='+y: ',left='+x+',top='+y; //A LITTLE CROSS-BROWSER CODE FOR WINDOW POSITIONING
	tb=(tb)?'yes':'no'; stb=(stb)?'yes':'no'; l=(l)?'yes':'no'; mb=(mb)?'yes':'no'; sb=(sb)?'yes':'no'; rs=(rs)?'yes':'no';
	var x=window.open(url, 'newWin'+new Date().getTime(), 'scrollbars='+sb+',width='+w+',height='+h+',toolbar='+tb+',status='+stb+',menubar='+mb+',links='+l+',resizable='+rs+t);
	x.focus();
	return x;
}
/*
function openWindow(url,w,h,tb,stb,l,mb,sb,rs,x,y){
var t=(document.layers)? ',screenX='+x+',screenY='+y: ',left='+x+',top='+y; //A LITTLE CROSS-BROWSER CODE FOR WINDOW POSITIONING
tb=(tb)?'yes':'no'; stb=(stb)?'yes':'no'; l=(l)?'yes':'no'; mb=(mb)?'yes':'no'; sb=(sb)?'yes':'no'; rs=(rs)?'yes':'no';
var x=window.open(url, 'newWin'+new Date().getTime(), 'scrollbars='+sb+',width='+w+',height='+h+',toolbar='+tb+',status='+stb+',menubar='+mb+',links='+l+',resizable='+rs+t);
x.focus();
return x;
}
*/

//Funcao Para Validacao de Formulario - Campo Obrigatorio
function obrigatorio(valor,exibe) {
  if (valor.length == 0) {
		if (exibe!='N') {
		    alert('O campo deve ser preenchido!');
	    }
    return false;
  }
  return true;
}

function obrigatorio2(valor) {
alert(valor);
  if (valor == 0) {
		    alert('coco!');
    return false;
  }
  return true;
}

//Funcao Para Validacao de Formulario - Conteudo Positivo
function positivo(valor,exibe) {
  if (valor.length == 0) {
		if (exibe!='N') {
		    alert('O campo deve ser preenchido!');
	    }
    return false;
  }
  for (x=0;x<valor.length;x++) {
	if (valor.charCodeAt(x)<48 || valor.charCodeAt(x)>57) { //0 a 9
		if (valor.charCodeAt(x)!=46) { // .
			if (exibe!='N') {
    	       alert('Não é um número válido, utilize apenas números e ponto!');
    	    }
           return false;
        }
	}
  }
  if (valor.value < 0) {
	if (exibe!='N') {
    	alert('O valor não pode ser negativo!');
    }
    return false;
  }
  return true;
}

//Funcao Para Validacao de Formulario - Conteudo Pertence
function pertence(valor,pertence) {
  if (valor.value < 0) {
    alert('O valor não pertence ao conteudo permitido!');
    return false;
  }
}

//Funcao Redirecionador
function redirecionador(link){
	location.href=link
}

//Funcao Para Validacao de Formulario - Campos Data
function valdata(vr,exibe) {
	if (vr.length != 10 ) {
		if (exibe!='N') {
	    	alert('A data deve conter 10 dígitos [dd/mm/aaaa]!');
	    }
	    return false;
    }
	dia = vr.substr( 0, 2 );
	mes = vr.substr( 3, 2 );
	ano = vr.substr( 6, 4 );
	if (dia<1 || dia>31 || mes<1 || mes>12 || ano<1900 || ano>2999) {
		if (exibe!='N') {
			alert('Data Inválida!');
		}
		return false;
	}
	return true;
}

//Funcao Para Validacao de Formulario - Campo Hora
function valhora(vr,exibe) {
	if (vr.length != 5) {
		if (exibe!='N') {
	    	alert('A hora deve conter 5 dígitos [hh:mm]!');
	    }
	    return false;
    }
	hora   = vr.substr( 0, 2 );
	minuto = vr.substr( 3, 2 );
	if (hora<0 || hora>23 || minuto<0 || minuto>59) {
		if (exibe!='N') {
			alert('Hora Invalida!');
		}
		return false;
	}
	return true;
}

//Funcao Para Validacao de Formulario - Campo CEP
function valcep(vr,exibe) {
	if (vr.length != 9) {
		if (exibe!='N') {
	    	alert('O CEP deve conter 9 dígitos [99999-999]!');
	    }
	    return false;
    }
	if (vr.substr( 5, 1 )!='-') {
		if (exibe!='N') {
			alert('CEP Invalido!');
		}
		return false;
	}
	return true;
}

//DISPARA - Funcao para pegar um resultado do xml de resposta
function pegaresultado(xmlString,myString){
	xmlString  = xmlString.toUpperCase()
	var tamanho= myString.length;
	var pos1   = xmlString.indexOf(myString);
	var pos2   = xmlString.indexOf(myString,pos1+1);
	var pega_inicio = pos1+tamanho+1;
	var pega_final  = pos2-2;
	var pega_tamanho= pega_final-pega_inicio;
	var retorno= xmlString.substr(pega_inicio,pega_tamanho);
	return retorno;
}

function postXMLDoc(xmlString)
{
}

/**********************************************************************
***********************************************************************
**                                                                   **
**  XMLHttpRequest                                                   **
**                                                                   **
***********************************************************************
**********************************************************************/
// Constructor for generic HTTP client
function HTTPClient() {};

// Add methods and properties as array
HTTPClient.prototype = {
    url: null,

    // Instance of XMLHttpRequest
    xmlhttp: null,

	// This is the local for your data...
	xmlString: null,
	
    // Used to make sure multiple calls are not placed
    // with the same client object while another in progress
    callinprogress: false,

    // The user defined handler - see MyHandler below
    userhandler: null,

    init: function(url) {
        this.url = url;
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
 		this.objeXSLTProcessor;
		this.objeXmlDoc;
		this.objeXSLT;
		//Criando o processador de XLST
		objeXSLTProcessor = new XSLTProcessor();
		//Carregando o arquivo XSL
		this.xmlhttp=new XMLHttpRequest()
		//objeXsl = new XMLHttpRequest();
		//objeXsl.open("GET", "Conversao.xsl", false);
		//objeXsl.send(null);
		//objeXSLT = objeXsl.responseXML;
		//objeXSLTProcessor.importStylesheet(objeXSLT);
	}
	// code for IE
	else if (window.ActiveXObject)
	{
		this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	}

	if (this.xmlhttp)
	{
//		alert("ok!");
	}
	else
	{
//		alert("Ooops!");
		return false;
	}
    },

	setXML: function (xxx) {
		this.xmlString = xxx;
	},
	
    // handler argument is a user defined object to be called
    syncGET: function (handler) {

        // Prevent multiple calls
        if (this.callinprogress) {
            throw "Call in progress";
        };

        if (handler)
		this.userhandler = handler;

        // Open an async request - third argument makes it async
        this.xmlhttp.open('GET',this.url, false);

        if (handler)
		this.xmlhttp.onload = handler;

        // Have to assign "this" to a variable - not sure why can't use directly
        var self = this;

        // Send the request
        this.xmlhttp.send(null);
    },

    asyncGET: function (handler) {

        // Prevent multiple calls
        if (this.callinprogress) {
            throw "Call in progress";
        };

        if (handler)
	        this.userhandler = handler;

        // Open an async request - third argument makes it async
        this.xmlhttp.open('GET',this.url, true);

        // Have to assign "this" to a variable - not sure why can't use directly
        var self = this;

        // Assign a closure to the onreadystatechange callback
        this.xmlhttp.onreadystatechange = function() {
            self.stateChangeCallback(self);
        }

        // Send the request
        this.xmlhttp.send(null);
    },

    // handler argument is a user defined object to be called
    syncPOST: function (handler) {

        // Prevent multiple calls
        if (this.callinprogress) {
            throw "Call in progress";
        };
        if (handler)
	        this.userhandler = handler;

        // Open an async request - third argument makes it async
        this.xmlhttp.open('POST',this.url, false);

        if (handler)
		this.xmlhttp.onload = handler;

        // Have to assign "this" to a variable - not sure why can't use directly
        var self = this;
        
        // Send the request
        this.xmlhttp.send(this.xmlString);
    },

    asyncPOST: function (handler) {

        // Prevent multiple calls
        if (this.callinprogress) {
            throw "Call in progress";
        };

        if (handler)
	        this.userhandler = handler;

        // Open an async request - third argument makes it async
        this.xmlhttp.open('POST',this.url, true);

        // Have to assign "this" to a variable - not sure why can't use directly
        var self = this;

        // Assign a closure to the onreadystatechange callback
        this.xmlhttp.onreadystatechange = function() {
            self.stateChangeCallback(self);
        }

        // Send the request
        this.xmlhttp.send(this.xmlString);
    },

    stateChangeCallback: function(client) {
        switch (client.xmlhttp.readyState) {

            // Request not yet made
            case 1:
                try {
                    client.userhandler.onInit();
                } catch (e) { /* Handler method not defined */ }
            break;

            // Contact established with server but nothing downloaded yet
            case 2:
                try {
                    // Check for HTTP status 200
                    if ( client.xmlhttp.status != 200 ) {
                        client.userhandler.onError(
                            client.xmlhttp.status,
                            client.xmlhttp.statusText
                            );

                        // Abort the request
                        client.xmlhttp.abort();

                        // Call no longer in progress
                        client.callinprogress = false;
                    }
                } catch (e) {
                    /* Handler method not defined */
                }
            break;

            // Called multiple while downloading in progress
            case 3:
                // Notify user handler of download progress
                try {
                    // Get the total content length
                    // -useful to work out how much has been downloaded
                    try {
                        var contentLength =
                            client.xmlhttp.getResponseHeader("Content-Length");
                    } catch (e) {
                        var contentLength = NaN;
                    }

                    // Call the progress handler with what we've got
                    client.userhandler.onProgress(
                        client.xmlhttp.responseText,
                        contentLength
                    );

                } catch (e) { /* Handler method not defined */ }
            break;

            // Download complete
            case 4:
                try {
                    client.userhandler.onLoad(client.xmlhttp.responseText);
                } catch (e) {
                    /* Handler method not defined */
                } finally {
                    // Call no longer in progress
                    client.xmlhttp.callinprogress = false;
                }
            break;
        }
    }
}

// Invoke the client
function getPage(url, MyHandler) {
    // Modify this to some page
    var client = new HTTPClient();
    client.init(url);

    try {
        client.asyncGET(MyHandler);
    } catch (e) {
        alert(e);
    }
}

function getPageSync(url, MyHandler) {
    // Modify this to some page
    var client = new HTTPClient();
    client.init(url);

    try {
        client.syncGET(MyHandler);
	return client.xmlhttp.responseText;
    } catch (e) {
        alert(e);
    }
}

function postPage(url, xmlString, MyHandler) {
    // Modify this to some page
    var client = new HTTPClient();
    client.init(url);

    try {
    	client.setXML(xmlString);
        client.asyncPOST(MyHandler);
    } catch (e) {
        alert(e);
    }
}

function postPageSync(url, xmlString, MyHandler) {
    // Modify this to some page
    var client = new HTTPClient();
    client.init(url);

    try {
    	client.setXML(xmlString);
        client.syncPOST(MyHandler);
		return client.xmlhttp.responseText;
    } catch (e) {
        alert(e);
    }
}

//Futura Implementacao
//	var datadig = new Date(ano,mes-1,dia)	
//	var hoje  = new Date();	
//	var hjmes = hoje.getMonth()+1;
//	var hjano = hoje.getYear();
//	var hjdia = hoje.getDate();
//	var teste1 = ano.toString()+mes.toString()+dia.toString();
//	var teste2 = hjano.toString()+hjmes.toString()+hjdia.toString();
//	alert(teste1+teste2);
//	if (datadig<hoje) {
//		alert('Data deve ser maior ou igual a data de hoje!');
//		alert(hoje);
//		alert(datadig);
//		return false;
//	}

function apagafoto(foto){
	dummy = confirm("Deseja apagar esta foto?");
	if (dummy == 1) {
		redirecionador("foto_apaga.php?diretorio="+diretorio+"foto="+foto)
	} else {
		// False
	}
}

