// JavaScript Document 
// FUNÕES COMUNS...
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

function openAjax() {
	var ajax;
	try {
		ajax = new XMLHttpRequest();
	} catch(ee) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				ajax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(E) {
				ajax = false;
			}
		}
	}
	return ajax;
}

function focar(id) {
	// Se hão houver o campo nome aborta a função
	if (!gE(id)) return false;
	// Concede o focus ao campo nome do cadastro
	gE(id).focus();
}

// Utilizado para evitar de digitar: document.getElementById toda hora, tornando o processo mais prático
function gE(ID) {
	return document.getElementById(ID);
}

function cT(texto) {
	return document.createTextNode(texto);
}

function cE(elemento) {
	return document.createElement(elemento);
}

// Utilizado para evitar de digitar: document.getElementsByTagName toda hora, tornando o processo mais prático
function gEs(tag) {
	return document.getElementsByTagName(tag);
}

function limparDiv(nomeDiv) {
	obj = gE(nomeDiv);
	for (i=obj.childNodes.length-1;i>=0;i--) {
		obj.removeChild(obj.childNodes[i]);
	}
}

function mostraEsconde(id) {
	var obj = gE(id);
	if(obj.style.display == "") {
		obj.style.display = "none";
	} else {
		obj.style.display = "";
	}
}

function esconde(opt, id) {
	obj = gE(id);
	if (opt) {
		obj.style.display = "none";
	} else {
		obj.style.display = "";
	}
}

function carregando(opt) {
	if (opt) {
		//cria uma div e o texto para ela...
		/*var novaDiv = document.createElement('div');
		var texto = document.createObject('Carregando...');
		//define o id da novaDiv
		novaDiv.setAttribute('id','carregando');
		//define o style da div...
		//novaDiv.style.background ='url(../img/carregando.gif)';
		novaDiv.style.textAlign='center';
		novaDiv.style.color='#FFFFFF';
		novaDiv.style.position='absolute';
		novaDiv.style.left = '2px';
		novaDiv.style.top='2px';
		novaDiv.style.width='135px'; //90px
		novaDiv.style.height='16px'; //20px
		novaDiv.appendChild(texto);
		//adiciona a div ao body...
		gE('body').appendChild(novaDiv);*/
	} else {
		//alert('pause');
		//divCarregando = gE('carregando');
		//divCarregando.parentNode.removeChild(divCarregando);
		//imgLoading.parentNode.removeChild(imgLoading);
	}
}

// Utilizado para criar o fundo sobre a página (wiewport), body.
function exibirBgBody() {
	// Seleciona a tag body. item(0) por que só existe uma tag body
	var tagBody = gEs('body').item(0);
	// Pega os tamanhos atuais da página, como largura, altura, ...
	var sizesPage = getPageSize();
	// Vamos criar uma tag div
	var bgBody = document.createElement('div');
	// Setar o atributo ID a div criada
	bgBody.setAttribute('id','bgBody');
	// Essa div terá o tamanho exato da página
	bgBody.style.height = arrayPageSize[1] + 'px';
	// Essa div terá a largura exata da página
	bgBody.style.width = arrayPageSize[0] + 'px';
	// Evita criar a div novamente
	if (!gE('bgBody')) {
		tagBody.insertBefore(bgBody, tagBody.firstChild);
	}	
}

/* Funções de terceiros */
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
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) 

}

function ehCampoObrigatorio(obrigatoriedade) {
	if (obrigatoriedade == "sim")
		return true;
	else
		return false;
}

function ehDigito(valor) {
	if ((valor=='0') || (valor=='1') || (valor=='2') || (valor=='3') || (valor=='4') || (valor=='5') || (valor=='6') || (valor=='7') || (valor=='8') || (valor=='9')) {
			return true;
	} else {
		return false;
	}
}

function incluirPagina(metodo, parametros, onde, caminho, funcaoPos1, parametro1) {
	//inicia a var ajax...
	var ajax = openAjax();
	//recipiente eh onde a pagina será incluida...
	var recipiente = gE(onde);
	// Informamos o método e a página que será requisitada


	ajax.open(metodo, caminho, true);
	//se o metodo é post, tem q enviar o cabeçalho...
	if (metodo=='POST')
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');	

	// colocamos uma função no onreadystatechange do ajax...
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 1) {
			// Cria o efeito de loading
			//elemento.innerHTML = 'Carregando...'; //Insere no 'elemento' o texto atribuído
		} // if->readyState->1
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				// Pega o conteúdo - HTML - da página requisitada: formulario.php?ajax=true e coloca dentra da div definida na variável recipiente
				recipiente.innerHTML = ajax.responseText;
				// Remove o efeito de loading
				if (funcaoPos1!=null){
					funcaoPos1(parametro1);
				}
				carregando(false);
			} // if-status->200
		} // if->readyState->4
	} // ajax->onreadystatechange
	ajax.send(parametros);
}
/*
function incluirPaginaGet(onde, caminho, funcaoPos, funcaoPos2) {
	//inicia a var ajax...
	var ajax = openAjax();
	//recipiente eh onde a pagina será incluida... 
	var recipiente = gE(onde);
	// Informamos o método e a página que será requisitada

	ajax.open('GET', caminho, true);
	//ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');	

	// colocamos uma função no onreadystatechange do ajax...
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 1) {
			// Cria o efeito de loading
			carregando(true);	
		} // if->readyState->1
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				// Pega o conteúdo - HTML - da página requisitada: formulario.php?ajax=true e coloca dentra da div definida na variável recipiente
				recipiente.innerHTML = ajax.responseText;
				// Remove o efeito de loading
				if (funcaoPos!=null)
					funcaoPos();
				if (funcaoPos2!=null)
					funcaoPos2();

				carregando(false);
			} // if-status->200
		} // if->readyState->4
	} // ajax->onreadystatechange
	ajax.send(null);
}
*/

function ativaAcoes (menu, funcaoPos) {
	// div acoes
	limparDiv('conteudoAcoes');
	ca = gE('conteudoAcoes');
	texto = cT('Incluir');
	ln = cE('a');
	ln.appendChild(texto);
	ln.setAttribute('href','#');
	ln.setAttribute('id','linkIncluir' + menu);
	ca.appendChild(ln);
	
	//ativarLinkIncluirFornecedor();
	funcaoPos();
}

function ativaAcoesInclusao(menu, funcaoPos) {
	// div acoes
	limparDiv('conteudoAcoes');
	ca = gE('conteudoAcoes');
	texto = cT('Voltar');
	
	ln = cE('a');
	ln.appendChild(texto);
	ln.setAttribute('href','#');
	ln.setAttribute('id','linkVoltar' + menu);
	ln.onclick = funcaoPos;
	ca.appendChild(ln);
	
	//ativarLinkIncluirFornecedor();
	
}

/*
function cabecalhoConteudoInclusao(menu) {
			//As variaveis contem as dicas, de cada cabecallho:
			
			//div titulo
			incluirPagina('conteudoTitulo', 'programas/tituloInclusao' + menu + '.php', null);
			
			//div dicas			
			incluirPagina('conteudoDicas', 'programas/dicaInclusao' + menu + '.php', null);
			
			//esconde(false, 'conteudoDicas'); 

			// div acoes
			limparDiv('conteudoAcoes');
			ca = gE('conteudoAcoes');
			texto = cT('Incluir');
			ln = cE('a');
			ln.appendChild(texto);
			ln.setAttribute('href','#');
			ln.setAttribute('id','linkIncluirFornecedor');
			ca.appendChild(ln);
			ativarLinkIncluirFornecedor();
			//div dados			
			//limparDiv('conteudoDados');
}
*/
function criaParcelas(formaPagamento, valor, descricao, data) {

	if (formaPagamento==0) {
		if (gE('divParcelas'))
			removerDiv('divParcelas');
	} else {

		//function validar(tipo, valor, obrigatorio) {
		erro = 'É preciso preencher alguns campos antes, verifique a indicação!'	
		nomeCampo = 'copDataCadastro';
		tipo = gE(nomeCampo).getAttribute('validador');
		valor = gE(nomeCampo).value;
		//alert(tipo);
		//alert(valor);	
		if (!validar(tipo, valor, true)) {
			gE('formaPagamento').selectedIndex = 0;
			alert(erro);
			gE(nomeCampo).focus();
			gE(nomeCampo).style.background = '#FF9393';
			gE(nomeCampo).onblur = function() {
				this.style.background = '';
			}
			return false;
		}

		nomeCampo = 'copDescricao';
		tipo = gE(nomeCampo).getAttribute('validador');
		valor = gE(nomeCampo).value;
		if (!validar(tipo, valor, true)) {
			gE('formaPagamento').selectedIndex = 0;
			alert(erro);
			gE(nomeCampo).focus();
			gE(nomeCampo).style.background = '#FF9393';
			gE(nomeCampo).onblur = function() {
				this.style.background = '';
			}
			return false;
		}
	
		nomeCampo = 'copValor';	
		tipo = gE(nomeCampo).getAttribute('validador');
		valor = gE(nomeCampo).value;
		if (!validar(tipo, valor, true)) {
			gE('formaPagamento').selectedIndex = 0;
			alert(erro);
			gE(nomeCampo).focus();
			gE(nomeCampo).style.background = '#FF9393';
			gE(nomeCampo).onblur = function() {
				this.style.background = '';
			}
			return false;
		}
		//numero de parcelas:

/*
      <option value="0">Selecione</option>
      <option value="1">A vista</option>
      <option value="2">Predatado</option>
      <option value="3">A prazo 1 + 1 parcelas (30d)</option>
      <option value="4">A prazo 1 + 2 parcelas (30d)</option>
      <option value="5">A prazo 1 + 3 parcelas (30d)</option>
      <option value="6">A prazo 1 + 4 parcelas (30d)</option>									
      <option value="7">A prazo 1 + 5 parcelas (30d)</option>


*/

		numParcelas = 0;

		if (formaPagamento==1) {
			numParcelas = 1;
		} else if (formaPagamento==2) {
			numParcelas = 1;
		} else if (formaPagamento==3) {
			numParcelas = 2;
		} else if (formaPagamento==4) {
			numParcelas = 3;
		} else if (formaPagamento==5) {
			numParcelas = 4;
		} else if (formaPagamento==6) {
			numParcelas = 5;
		}	else if (formaPagamento==7) {
			numParcelas = 6;
		}

		var dataPost = 'valor=' + valor;
		dataPost += '&descricao=' + descricao;
		dataPost += '&data=' + data;
		dataPost += '&parcelas=' + numParcelas;
		dataPost += '&formaPagamento=' + formaPagamento;

		if (!gE('divParcelas')) {
			//cria uma div e insere no documento...
			divParcelas = cE('div');
			divParcelas.setAttribute("id","divParcelas");
			referencia = gE('rodapeParcelas');
			parentTag = referencia.parentNode;
			parentTag.insertBefore(divParcelas, referencia);
		}
		//envia os dados para processamento php, após insere o retorno na div cirada...
		//alert(dataPost);
		incluirPagina('POST', dataPost, 'divParcelas', 'programas/formContaAPagar2.php', null, null);
		//function incluirPagina(metodo, parametros, onde, caminho, funcaoPos1, funcaoPos2)
	}
}

function arrDecimal(valor) {
	v = new String(valor);
	p1 = v.split('.')[0];
	p2 = v.split('.')[1];
	p2 = p2.substr(0,2);
/*
	if (p2=='100') {
		p2 = '00';
		p1++;
	}
	*/
	//alert(p1 + ',' + p2);
	return p1 + ',' + p2;
}

function removerDiv(idDiv) {
	if (gE(idDiv)) {
		idDiv = gE(idDiv);
		idDiv.parentNode.removeChild(idDiv);
	}
}
