
//------------------------ Funcao de Edicao de Inputs -----------------------------
var matrizFormType = new Array();	// guarda todos os tipos dos objetos do Form 
var matrizFormName = new Array();	// guarda todos os nomes dos objetos do Form 
var matrizFormHidden = new Array();	// guarda todos os camos hidden em seus tamanhos
var tamanhoForm = 0  //guarda o tamanho do Form
var tamanhoLink = 0  //guarda o tamanho do link
var tamanhoHidden = 0  //guarda o tamanho do hidden
var tamanhoPassword = 0	//guarda o tamanho do password
var correcaoColuna = 0	//guarda a correção da coluna quando não há um campo correspndente

function limpaForm(){
	// reseta o form, desinibe os campos travados, esconde as layers transparentes dos campos.
	document.FORM.reset();
	for(f=0;f<tamanhoForm;f++){
		if(matrizFormName[f].charAt(0)=='K'){
			document.FORM[matrizFormName[f]].onfocus = null;	//	desinibe os campos desativando a função inibidora dos campos chave no evento onFocus
			escondeLayer('L' + matrizFormName[f].substring(1,matrizFormName[f].length));
		};
	};
};
function exibeLayer(strLayer) {
	if (document.layers) {
    		document.layers[strLayer].visibility = 'show'; 
	} else {
    		document.all[strLayer].style.visibility = 'visible';
	};
};

function escondeLayer(strLayer) {
	if (document.layers){
    		document.layers[strLayer].visibility = 'hide';
	} else {
    		document.all[strLayer].style.visibility = 'hidden';
	};
};

function inibidora(){
	//	inibe o campo chave do sistema quando o registro estiver sendo editado
	//	para informar que um campo é chave é necessário que seu nome seja inicializado por 'K'
	//	alert('chegou');
	this.blur();
}
function inicializacao(){
	// identifica o número dos objetos do Form colocando-os em seus arrays e eliminando os radio
	for(f=0;f<document.FORM.length;f++){
		if(f!=0){
			if(document.FORM[f].name!= document.FORM[f-1].name){
				(document.FORM[f].type=='select-one')?(matrizFormType[tamanhoForm]='select'):(matrizFormType[tamanhoForm] = document.FORM[f].type);
				matrizFormName[tamanhoForm] = document.FORM[f].name;
				tamanhoForm ++;
			};
		} else {
			(document.FORM[f].type=='select-one')?(matrizFormType[tamanhoForm]='select'):(matrizFormType[tamanhoForm] = document.FORM[f].type);
			matrizFormName[tamanhoForm] = document.FORM[f].name;
			tamanhoForm ++;
		};
	};
	for(f=0;f<tamanhoForm;f++){
		if(matrizFormType[f]!='hidden'){
			tamanhoLink++;
		} else {
			matrizFormHidden[f] = tamanhoHidden;
			tamanhoHidden++;
		};
		if(matrizFormType[f]=='password'){
			tamanhoPassword++;
		};
	};
};

// encontra os valores nos links
function recolheValoresLink(numero){
	if(document.layers){
		return parent.dados.document.links[numero - correcaoColuna -  tamanhoPassword * ( linhaClicada - 1 )].text;
	} else {
		//alert('numero = ' + numero);
		//alert('linha clicada = ' + (correcaoColuna + tamanhoPassword * ( linhaClicada - 1 )));
		//alert('correcaoColuna = ' + correcaoColuna + ' tamanhoPassword = ' + tamanhoPassword + ' linhaClicada = ' + linhaClicada);
		//alert(numero - correcaoColuna - tamanhoPassword * ( linhaClicada - 1 ));
		return parent.dados.document.links[numero - correcaoColuna - tamanhoPassword * ( linhaClicada - 1 )].innerText;
	};
};

function rDados(numero){
	linhaClicada = numero;
	valorLink = (numero - 1) * tamanhoLink;	
	for(f=0;f<tamanhoForm;f++){
		eval('F' + matrizFormType[f] + '(valorLink)'); 										// desvia a execução para a função correspondente com o typo do campo
		if(matrizFormName[f].charAt(0)=='K'){ 												//  verifica se o campo é chave e desvia para funções apropriadas
			document.FORM[matrizFormName[f]].onfocus = inibidora;  							// trava o campo para edição
			exibeLayer('L' + matrizFormName[f].substring(1,matrizFormName[f].length));  	// mostra a layer transparente sobre o campo chave na edição
		};
	};
	correcaoColuna = 0;
};
function Ftext(valor){	//	coloca o valor do link correspondente no campo texto
	document.FORM[matrizFormName[f]].value = recolheValoresLink(valor + f);
};
function Fcheckbox(valor){  //  marca o desmarca o checkbox caso o seu valor seja igual ao do link correspondente
	(document.FORM[matrizFormName[f]].value==recolheValoresLink(valor + f))?(document.FORM[matrizFormName[f]].checked = true):(document.FORM[matrizFormName[f]].checked = false);
};
function Fselect(valor){	//	seleciona o valor que seja igual ao do link no select, verificando o texto e depois o value
	tTeste=true;
	for(g=0;g<document.FORM[matrizFormName[f]].length;g++){
		if(document.FORM[matrizFormName[f]][g].text==recolheValoresLink(valor + f)){
			document.FORM[matrizFormName[f]][g].selected = true;
			tTeste = false;
		} else {
			document.FORM[matrizFormName[f]][g].selected = false
		};
	};
	if(tTeste){
		for(g=0;g<document.FORM[matrizFormName[f]].length;g++){
			(document.FORM[matrizFormName[f]][g].value==recolheValoresLink(valor + f))?(document.FORM[matrizFormName[f]][g].selected = true):(document.FORM[matrizFormName[f]][g].selected = false);
		};
	};
};
function Fradio(valor){  //	seta o campo que possuir o mesmo value do select, caso nenhum exista desmarca todos
	for(g=0;g<document.FORM[matrizFormName[f]].length;g++){
		(document.FORM[matrizFormName[f]][g].value==recolheValoresLink(valor + f))?(document.FORM[matrizFormName[f]][g].checked = true):(document.FORM[matrizFormName[f]][g].checked = false);
	};
};
function Fhidden(valor){	//	procura e iguala os campos hidden do for com os do frame de dados
	posicaoHidden = (valor/tamanhoLink)*tamanhoHidden + matrizFormHidden[f] + (valor/tamanhoLink); // descobre a posição do campo hidden a der copiado para o form
	document.FORM[matrizFormName[f]].value = parent.dados.document.FORM[posicaoHidden].value;
};
function Fpassword(valor){  //	apaga o valor que existir dentro do campo pois nos campos de leitura não haverão valores para preenche-los
	document.FORM[matrizFormName[f]].value = '';
	correcaoColuna = 1;	//	faz com que o número de localização da coluna da tabela seja subtraída de um, pois não há coluna para o campo
};

//------------------------ Funcao de Filtro na Manutencao de Produtos -----------------------------
function filtro(){
	var codGrupo = eval(document.FORM.CODGRP.value);
	var URL = 'iManutProd.asp?Grupo=' + codGrupo;
	top.document.location=URL;
};

		
//------------------------ Funcoes do DreamWeaver para troca de Imagens (usado na Index) -----------------------------

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
// -->

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.FORM.length;i++) x=d.FORM[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

//------------------------------------------------ Funcoes usadas na Cesta de Compras -----------------------------
var valorCampo = 0;
function guardaValor(valor){
	nQtd = "QTD_" + valor;
	valorCampo = document.FORM[nQtd].value;	
};
function resetaCampo(valor){
	nQtd = "QTD_" + valor;
	if(valorCampo!=document.FORM[nQtd].value){
		document.FORM.submit();
	};
};

function tempLayer(){
	temporizador = setTimeout("document.FORM.submit()", 1000);
};
function cancelaTimaOut(){
	if(typeof(temporizador)!='undefined'){
		window.clearTimeout(temporizador);
	};
};
function mais(valor){
	nQtd = "QTD_" + valor;
	document.FORM[nQtd].value++;
	if(document.FORM[nQtd].value > 999 ){
		document.FORM[nQtd].value = 999;
	};
	cancelaTimaOut();
	tempLayer();
};
function menos(valor){
	nQtd = "QTD_" + valor;
	document.FORM[nQtd].value--;
	if(document.FORM[nQtd].value<0){
		document.FORM[nQtd].value=0;
	};
	cancelaTimaOut();
	tempLayer();
};

function deletar(valor){
	if(confirm('Deseja apagar este Item de sua cesta ?')){
		nQtd = "QTD_" + valor;
		document.FORM[nQtd].value = 0;
		document.FORM['passo'].value = 3; 
		document.FORM.submit();
	};
};

function apaga(){
	if(confirm('Deseja Apagar sua Cesta de Compras ?')){
		document.direita.apaga.value = 'apaga';     
		document.direita.submit();
	} else {
		escondeLayer('Layer1');
	};
	return void(0);
};
function finalizarCompra(){
	if(typeof(document.direita.qtd0)=='object'){
		document.finalizar.submit();
	} else {
		escondeLayer('Layer1');
		alert('Não há nenhum ítem na cesta para ser finalizada!');
	};
	return void(0);
};

function abre_Janela(url, tam){
	if (tam==1) window.open(url,"tutorial","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=300,height=300,left=150,top=160");
	if (tam==2) window.open(url,"tutorial","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=600,height=500,left=50,top=60");
	if (tam==3) window.open(url,"tutorial2","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=600,height=500,left=150,top=160");
	if (tam==4) window.open(url,"endereco","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=299,height=222");
	if (tam==5) window.open(url,"endereco2","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=299,height=250");

return void(0);
};

//------------------------------------------------ Funções de Crítica -----------------------------
function eliminaEspacos(nome){
	b='';
	c='';
	for(f=0;f<document.FORM[nome].value.length;f++){b=document.FORM[nome].value.charAt(f);if(b!=' '){c+=b};};
	document.FORM[nome].value = c;
};
function limpaEnpacosVariavel(nome){
	b='';
	c='';
	for(f=0;f<window[nome].length;f++){b=window[nome].charAt(f);if(b!=' '){c+=b};};
	window[nome] = c;
};
function testeGeral(nome,label,tipo,vazio){
	valorCampo = document.FORM[nome].value;
	limpaEnpacosVariavel('valorCampo');
	if(vazio){
		if(valorCampo==''){
			alert('O campo ' + label + ' precisa ser preenchido.');
			return false;
		};
	};
	if(tipo=='numero'){
		eliminaEspacos(nome);
		if(isNaN(document.FORM[nome].value)){
			alert('O campo ' + label + ' deve ser preenchido só com números.');
			return false;
		};		
	};
	if(tipo=='numero'){
		eliminaEspacos(nome);
		for(f=0;f<document.FORM[nome].value.length;f++){
			if((document.FORM[nome].value.charAt(f)=='.')||(document.FORM[nome].value.charAt(f)==',')){
				alert('O campo ' + label + ' é do tipo numérico inteiro.');
				return false;
			};
		};		
	};
	if(tipo=='data'){
		if(document.FORM[nome].value!=''){
			if(!testaData(document.FORM[nome].value)){
				alert('O campo ' + label + ' não possui uma data válida. \n O formato aceito é dd/mm/aaaa.');
				return false;
			};
		};
	};
	return true;
};

//----------------------------- Testa Data ------------------------

function testaData(recebeData){
	recebeData = recebeData.split('/');
	var arrayMeses = new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
	testaAnoBicesto = recebeData[2] /4 + ' ';
	if(testaAnoBicesto.indexOf('.')==-1){
		arrayMeses[2]=29;
	};
	if(recebeData[0]>arrayMeses[recebeData[1] - 0]){
	//	alert('Esta data é inválida!\n Favor utilizar dd/mm/aaaa.');
		return false;
	};
	return true;
};

//----------------------------- Valida Formulario de Pedido ------------------------
function submitPedido(){
		teste = true;
		teste = teste & testeGeral('nome','Nome do Cliente','xx',true);
		teste = teste & testeGeral('email','Email do Cliente','xx',true);
		teste = teste & testeGeral('endereco','Endereço do Cliente','xx',true);
		teste = teste & testeGeral('bairro','Bairro do Cliente','xx',true);
		teste = teste & testeGeral('cidade','Cidade do Cliente','xx',true);
		teste = teste & testeGeral('ddd1','DDD 1 do Cliente','numero',true);
		teste = teste & testeGeral('tel1','Telefone 1 do Cliente','numero',true);
		teste = teste & testeGeral('ddd2','DDD 2 do Cliente','numero',false);
		teste = teste & testeGeral('tel2','Telefone 2 do Cliente','numero',false);
		teste = teste & testeGeral('dddfax','DDD Fax do Cliente','numero',false);
		teste = teste & testeGeral('telfax','Fax do Cliente','numero',false);
		teste = teste & testeGeral('cep','CEP do Cliente','numero',false);	
		
		
		if(teste){document.FORM.submit()};
};

//----------------------------- Valida Formulario de Links ------------------------
function submitLink(){
		teste = true;
		teste = teste & testeGeral('nome','Nome do Cliente','xx',true);
		teste = teste & testeGeral('email','Email do Cliente','xx',true);
		teste = teste & testeGeral('url','Link de Cliente','xx',true);
		if(teste){document.FORM.submit()};
};

//----------------------------- Valida Formulario de Pergunte ------------------------
function submitAsk(){
		teste = true;
		teste = teste & testeGeral('nome','Nome do Cliente','xx',true);
		teste = teste & testeGeral('email','Email do Cliente','xx',true);
		if(teste){document.FORM.submit()};
};

//----------------------------- Valida Formulario de Tipos de Produtos ------------------------
function submitTpProduto(){
		teste = true;	
		teste = teste & testeGeral('DSCTIP','Descrição do Tipo','xx',true);
		teste = teste & testeGeral('NOMIMG','Nome da Imagem','xx',true);
		teste = teste & testeGeral('TXTIMG','Nome da Imagem de Texto','xx',true);
		if(teste){document.FORM.submit()};
};
//----------------------------- Valida Formulario de Grupos de Produtos ------------------------
function submitGrPRoduto(){
		teste = true;
		teste = teste & testeGeral('NOMGRP','Nome do Grupo','xx',true);
		if(teste){document.FORM.submit()};
};
//----------------------------- Valida Formulario de Atributos ------------------------
function submitAtrib(){
		teste = true;
		teste = teste & testeGeral('DSCATR','Descrição do Atributo','xx',true);
		teste = teste & testeGeral('TAMATR','Tamanho','xx',true);
		if (document.FORM.TIPATR[1].checked){
			teste = teste & testeGeral('DECATR','Casas Decimais','xx',true);
		};
		
		if(teste){document.FORM.submit()};
};
//----------------------------- Valida Formulario de Administradores ------------------------
function submitAdmin(){
		teste = true;
		teste = teste & testeGeral('LOGINUSUARIO','Login','xx',true);
		teste = teste & testeGeral('SENHAUSUARIO','Senha','xx',true);
		teste = teste & testeGeral('FLGUSUARIO','Situação','xx',true);
		if(teste){document.FORM.submit()};
};
//----------------------------- Valida Formulario de Parametros ------------------------
function submitParam(){
		teste = true;
		teste = teste & testeGeral('ENTREGARJ','Entrega','xx',true);
		if(teste){document.FORM.submit()};
};
//----------------------------- Valida Formulario de Observacoes ------------------------
function submitObs(){
		teste = true;
		teste = teste & testeGeral('DSCOBS','Descricao','xx',true);
		if(teste){document.FORM.submit()};
};
//----------------------------- Valida Formulario de Links ------------------------
function submitProd(){
		teste = true;
		teste = teste & testeGeral('DSCPROD','Descrição do Produto','xx',true);
		teste = teste & testeGeral('FABPROD','Código Fabricante','xx',false);
		teste = teste & testeGeral('PRCPROD','Preço R$','xx',true);
		if(teste){document.FORM.submit()};
};
