function redirectProduto(nomeForm, acao, sku) {
	nomeForm.action='/cgi-bin/ncommerce3/ExecMacro/produtos/redirectProduto.d2w/report';
	nomeForm.acao.value=acao;
	nomeForm.cgnbr.value=sku;
	nomeForm.submit();
}

function moverCombo(comboOrigem, comboDestino) {
	var i = 0;
	for( i = 0; i < comboOrigem.options.length; i++ ) {
		if( comboOrigem.options[i].selected ) {
			mover(comboOrigem.options[i], comboDestino);
			comboOrigem.options[i].value = "";
			comboOrigem.options[i].text = "";
		}
	}
	refreshCombo(comboOrigem);
	refreshCombo(comboDestino);
}

function refreshCombo (combo) {
	for( var i = 0; i < combo.options.length; i++ ) {
		if( combo.options[i].value == "" )  {
			for(var j = i; j < combo.options.length - 1; j++)  {
				combo.options[j].value = combo.options[j + 1].value;
				combo.options[j].text = combo.options[j + 1].text;
			}
		var indice = i;
		break;
	   }
	}
	if( indice < combo.options.length )  {
		combo.options.length -= 1;
		refreshCombo(combo);
	}
}

function mover(opcaoOrigem, comboDestino) {
	var novaOpcao = new Option();
	novaOpcao.value = opcaoOrigem.value;
	novaOpcao.text = opcaoOrigem.text;
	comboDestino.options[comboDestino.options.length] = novaOpcao;
}

function validarCampoObrigatorio(campo, nomeCampo) {
	var valor;

	if (campo.value != undefined) {
		valor = campo.value;
	} 
	else {
		valor = campo;
	}
	
	if (trim(valor) == "") {
		alert("O preenchimento do campo \"" + nomeCampo + "\" é obrigatório.");
		return false;
	}
	return true;
}

function validarTamanhoCampo(campo, nomeCampo, tamanhoMin, tamanhoMax) {
	var valor;

	if (campo.value != undefined) {
		valor = campo.value;
	} 
	else {
		valor = campo;
	}
	
	if (valor.length < tamanhoMin) {
		alert("O campo \"" + nomeCampo + "\" não pode ter menos de " + tamanhoMin + " caracter(es).");
		return false;
	}
	if (valor.length > tamanhoMax) {
		alert("O campo \"" + nomeCampo + "\" não pode ter mais de " + tamanhoMax + " caracter(es).");
		return false;
	}
	return true;
}

function validarTamanhoMinimo(campo, nomeCampo, tamanhoMin) {
	var valor;

	if (campo.value != undefined) {
		valor = campo.value;
	} 
	else {
		valor = campo;
	}
	
	if (valor.length < tamanhoMin) {
		alert("O campo \"" + nomeCampo + "\" não pode ter menos de " + tamanhoMin + " caracter(es).");
		return false;
	}
	return true;
}

function validarTamanhoMaximo(campo, nomeCampo, tamanhoMax) {
	var valor;

	if (campo.value != undefined) {
		valor = campo.value;
	} 
	else {
		valor = campo;
	}
	if (valor.length > tamanhoMax) {
		alert("O campo \"" + nomeCampo + "\" não pode ter mais de " + tamanhoMax + " caracter(es).");
		return false;
	}
	return true;
}

function optionsToString(lista, campo) {
	var i = 0;
	for( i = 0; i < lista.options.length; i++ ) {
		campo.value = campo.value + lista.options[i].value;
		if (i < (lista.options.length - 1) ) {
			campo.value = campo.value + ",";
		}
	}
}

function optionsToString1() {
	document.editarUsuario.profileUsuario.value = "";
	var i = 0;
	for( i = 0; i < document.editarUsuario.profileIn.options.length; i++ ) {
		document.editarUsuario.profileUsuario.value = document.editarUsuario.profileUsuario.value + document.editarUsuario.profileIn.options[i].value;
		if (i < (document.editarUsuario.profileIn.options.length - 1) ) {
			document.editarUsuario.profileUsuario.value = document.editarUsuario.profileUsuario.value + ",";
		}
	}
}

function testaCombo(combo, descricao)
{
	if (combo.selectedIndex == -1 || combo.selectedIndex == 0) {
		if (trim(descricao) != "" && trim(descricao) != " "){
            	alert(descricao + " deve ter uma Opção Selecionada.");
        	}
    		return false;
    	}
  	else {
    		return true;
	}
}

function testaLista(lista, descricao) {
	if (lista.length == 0 || lista.length == -1) {
		if (trim(descricao) != "" && trim(descricao) != " ") {
    	alert(descricao + " deve ter uma Opção Selecionada.");
    }
    return false;
  }
  else {
  	return true;
	}
}

function testaRadio(radio, descricao) {
	for( var j=0; j<(radio.length); j++ ) {
		if (radio[j].checked) {
			return true;
		}
   }
   alert("Escolha uma opção de " + descricao + ".");
	return false;
}


function emailCheck (emailStr) {
        //remove espaços antes da verificação
        var emailStr = trim(emailStr)
        /* Critica de e-mail */
        var emailPat=/^(.+)@(.+)$/
        var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
        var validChars="\[^\\s" + specialChars + "\]"
        var quotedUser="(\"[^\"]*\")"
        var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
        var atom=validChars + '+'
        var word="(" + atom + "|" + quotedUser + ")"
        var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
        var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
        var matchArray=emailStr.match(emailPat)
        if (matchArray==null) {
                alert("O endereço de \"E-mail\" parece incorreto (verifique @ e .'s).")
                return false
        }

        var user=matchArray[1]
        var domain=matchArray[2]
        if (user.match(userPat)==null) {
            alert("O nome de usuário do \"E-mail\" não parece ser válido.")
            return false
        }

        var IPArray=domain.match(ipDomainPat)
        if (IPArray!=null) {
                  for (var i=1;i<=4;i++) {
                    if (IPArray[i]>255) {
                        alert("O endereço IP de destino do \"E-mail\" é inválido!")
                        return false
                    }
            }
            return true
        }

        var domainArray=domain.match(domainPat)
        if (domainArray==null) {
                alert("O nome do domínio do \"E-mail\" não parece ser válido.")
            return false
        }

        var atomPat=new RegExp(atom,"g")
        var domArr=domain.match(atomPat)
        var len=domArr.length
        if (domArr[domArr.length-1].length<2 ||
            domArr[domArr.length-1].length>3) {
           	alert("O endereço de \"E-mail\" deve terminar com um domínio de 3 letras ou um país com 2 letras.")
           	return false
        }

        if (len<2) {
           var errStr="Este endereço de \"E-mail\" não possui um nome de Host!"
           alert(errStr)
           return false
        }
        return true;
}


function validarDataNascimento(dateStr, descricao) {
	if (dateStr == "") {
		alert(descricao + " é campo obrigatório.");
		return false;
	}

	// Checks for the following valid date formats:
	// DD/MM/YY   DD/MM/YYYY   DD-MM-YY   DD-MM-YYYY

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		alert(descricao + " deve estar no formato DD/MM/AAAA.")
		return false;
	}

	day = matchArray[1];
	month = matchArray[3]; // parse date into variables
	year = matchArray[4];

	if (month < 1 || month > 12) { // check month range
		alert("Mês deve ser entre 1 e 12.");
		return false;
	}

	if (day < 1 || day > 31) {
		alert("Dia deve ser entre 1 e 31.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("Mês "+month+" não tem 31 dias!")
		return false
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			alert("Fevereiro " + year + " não tem " + day + " dias!");
			return false;
		}
	}

   var dataAtual = new Date();
   if( year > dataAtual.getFullYear() || year < 1900 ) {
      alert('Por favor, digite um ano menor do que o ano atual e maior do que 1900.');
      return false;
   }

   dataEntrada = new Date(year, month-1, day);
   if( dataEntrada > dataAtual ) {
      alert('Por favor, digite uma data anterior à do dia de hoje.');
      return false;
   }
	return true;  // date is valid
}

function testaData(dateStr, descricao) {
	if (dateStr == "") {
		alert(descricao + " é campo obrigatório.");
		return false;
	}

	// Checks for the following valid date formats:
	// DD/MM/YY   DD/MM/YYYY   DD-MM-YY   DD-MM-YYYY

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		alert(descricao + " deve estar no formato DD/MM/AAAA.")
		return false;
	}

	day = matchArray[1];
	month = matchArray[3]; // parse date into variables
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		alert("Mês deve ser entre 1 e 12.");
		return false;
	}

	if (day < 1 || day > 31) {
		alert("Dia deve ser entre 1 e 31.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("Mês "+month+" não tem 31 dias!")
		return false
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			alert("Fevereiro " + year + " não tem " + day + " dias!");
			return false;
		}
	}
	return true;  // date is valid
}

function trim(str) {
	str = str.toString().replace(/\$|\ /g,'');
	return str;
}

function isDigit(c)
{
	return ((c >= "0") && (c <= "9"))
}


// Função que verifica se a tecla pressionada é um número.
// Deverá ser utilizada no evento "onKeypress" do textbox.
function entradaNumero() {
  if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode != 13)) {  //O código Ascii está em decimal.
    event.returnValue = false;
  }
}


// Função que verifica se a tecla pressionada é um número ou se é um 'ponto'. Se for pressionada a 'vírgula', esta será substituída pelo 'ponto'
// Deverá ser utilizada no evento "onKeypress" do textbox e passar o nome do campo.
function entradaNumeroReal(campo) {
		if (event.keyCode != 46 && (event.keyCode < 48 || event.keyCode > 57)) {  //O código Ascii está em decimal.
			event.returnValue = false;
			if (event.keyCode == 44) {
				campo.value = campo.value + ".";
				campo.value = campo.value.replace(/,/gi, '.')
			}
		}
}

function entradaData() {
		if (event.keyCode!=47 && (event.keyCode < 48 || event.keyCode > 57)) {  //O código Ascii está em decimal.
			event.returnValue = false;
		}
}

function isInteger(s)
{
   var i;
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    return true;
}

function testaValor(str, descricao)
{
	if ( trim(str) != "" ) {
	    if ( !isInteger(str.value) || trim(str.value) == "" ) {
	        alert(descricao + " deve ser um valor numérico.");
	        return false;
	    }
    }
    return true;
}

function testaIntervalo(str, minimo, maximo, descricao)
{
    var max = 0;
    var min = 0;

    max = maximo;
    min = minimo;

    if (str > maximo) {
        alert(descricao + " não deve ser maior que " + max);
        return false;
    }

    if (str < minimo) {
        alert(descricao + " não deve ser menor que " + min);
        return false;
    }

    if ( trim(str) == "" ) {
        alert(descricao + " deve ser preenchido corretamente.");
        return false;
    }
    return true;
}
 /*
function formataCEP ( textbox, tecla ) {
	numeros = '01234567890';
	if ( (numeros.indexOf(String.fromCharCode(tecla)) != -1 ) && textbox.value.length < 9 ) {
		if (textbox.value.length == 5) {
		   textbox.value = campo.value + '-';
		}
	}
	else
		event.returnValue = false;
	}
}
*/

function verificaInputNumero(tecla) {
	numeros = '01234567890';
	if ( (numeros.indexOf(String.fromCharCode(tecla)) == -1 ) ) {
		event.returnValue = false;
	}
}

function rejeitaNumero() {
  if (event.keyCode > 47 && event.keyCode < 58) {  //O código Ascii está em decimal.
    event.returnValue = false;
  }
}

function rejeitaAspas() {
  if (event.keyCode == 34 || event.keyCode == 39) {  //O código Ascii está em decimal.
    event.returnValue = false;
  }
}


function removeAspas( campo ) {
    var texto = campo.value + "";               // armazena o texto original
    var novoTexto = "";                         // armazena o novo texto
    var c,                                      // o caracter a ser processado
        i;                                      // a posicao do caracter

    var exChar;                                 // lista de caracteres idesejaveis

    exChar = unescape("%22%27"); // ("')

    if( texto == "" )                           // validar
        return;
    for( var j = 0; j < texto.length; j++ ) {
        c = texto.charAt( j );
        if( exChar.indexOf( c ) != -1 )         // testar se eh indesejavel
            continue;                           // se eh, entao continuar
        novoTexto = novoTexto + c;              // finalmente, acrescenta-lo no novo texto
    }
    campo.value = novoTexto;                    // Atualizar o valor do campo
}

function limitaTamanhoTextArea(objTextArea, tamanhoMax) {
	if ( (objTextArea.value.length >= tamanhoMax) ) {
		event.returnValue = false;
	}
}

function verificaTamanhoTextArea(objTextArea, tamanhoMax) {
    var tamanho = objTextArea.value.length;
    if ( (tamanho > tamanhoMax) ) {
		alert("Desculpe, mas esse campo aceita no máximo " + tamanhoMax + " caracteres. \nOs caracteres excedentes serão descartados.");
		objTextArea.value = objTextArea.value.substring(0, tamanhoMax);
		objTextArea.focus();
	}
}

function existeNumero(texto) {
  var tamanho = texto.length;
  var letra;
  for (i=0; i<tamanho; i++) {
    letra = texto.charAt(i);
    if (isDigit(letra)) {
      return true;
    }
  }
  return false;
}

function checa_cpf(numcpf) {
	x = 0;
	soma = 0;
	dig1 = 0;
	dig2 = 0;
	texto = "";
	numcpf1="";
	len = numcpf.length; x = len -1;
	for (var i=0; i <= len - 3; i++) {
		y = numcpf.substring(i,i+1);
		soma = soma + ( y * x);
		x = x - 1;
		texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1=0 ;
	if (dig1 == 11) dig1=0 ;
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	x = 11; soma=0;
	for (var i=0; i <= len - 2; i++) {
		soma = soma + (numcpf1.substring(i,i+1) * x);
		x = x - 1;
	}
	dig2= 11 - (soma % 11);
	if (dig2 == 10) dig2=0;
	if (dig2 == 11) dig2=0;
	if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
		return true;
	}
	alert("Número do CPF inválido.");
	return false;
}

function verificaInputNumeroDecimal(tecla, element) {
	numeros = '01234567890,.';
	if ( (numeros.indexOf(String.fromCharCode(tecla)) == -1 ) && tecla != 13 ) {
		event.returnValue = false;
	}
	if ( String.fromCharCode(tecla).indexOf(",") != -1 || String.fromCharCode(tecla).indexOf(".") != -1  ) {
	    if ( element.value.indexOf(".") != -1 ) {
	        event.returnValue = false;
	    }
	}
}

function initDecimal(element) {
   if ( element.value.indexOf(",") != -1 ) {
      element.value =  element.value.replace(/,/gi, '.');
   }
}


function verificaTelefone(telres, dddres, telcel, dddcel, telcom, dddcom, descricao1, descricao2, descricao3) {
	if ( telres.value == "" && telcel.value == "" && telcom.value == "" ) {
		alert("Especifique pelo menos um telefone para contato.");
		dddres.focus();
		return false;
	}
	else if (telres.value != "" && dddres.value == "") {
		alert("Indique o DDD do " + descricao1 + ".");
		dddres.focus();
		return false;
	}
	else if (telcel.value != "" && dddcel.value == "") {
		alert("Indique o DDD do " + descricao2 + ".");
		dddcel.focus();
		return false;
	}
	else if (telcom.value != "" && dddcom.value == "") {
		alert("Indique o DDD do " + descricao3 + ".");
		dddcom.focus();
		return false;
	}
	return true;
}

// Esse função deverá ser utilizada para comparar os campos SENHA e CONFIRMAÇÃO DA SENHA.
function igualdadeCampos(campo1, campo2, campo3, descricao1, descricao2, descricao3) {
	if (campo1 != campo2) {
		alert("Os campos \"" + descricao1 + "\" e \"" + descricao2 + "\" deverão ser equivalentes.");
		return false;
	}
	else if (campo1 == campo3) {
		alert("A dica de senha não poderá ser igual à senha.");
		return false;
	}
	return 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.forms.length;i++) x=d.forms[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() {
  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; }
}


/*** Início das funções que fazem o TAB automáticos dos campos ***/

tab=true;
function checkTab(field, maxSize) {
	if ( (field.value.length == maxSize) && (tab) ) {
		var i=0,j=0, index=-1;
		for (i=0; i<document.forms.length; i++) {
			for (j=0; j<document.forms[i].elements.length; j++) {
				if (document.forms[i].elements[j].name == field.name) {
					index=i;
					break;
				}
			}
			if (index != -1)
		         break;
		}
		for (i=0; i<=document.forms[index].elements.length; i++) {
			if (document.forms[index].elements[i].name == field.name) {
				while ( (document.forms[index].elements[(i+1)].type == "hidden") &&
						(i < document.forms[index].elements.length) ) {
							i++;
				}
				document.forms[index].elements[(i+1)].focus();
				tab=false;
				break;
			}
		}
	}
}


function stopTab()
{
   tab=false;
}


function executeTab()
{
   tab=true;
}

/*** Fim das funções que fazem o TAB automáticos dos campos ***/

function validarCNPJ(campo, nomeCampo) {
    var rcgc = campo.value;
    rcgc = trim( rcgc );

    if (testaValor(campo, nomeCampo)) {
        if ( rcgc.length != 14 ) {
            alert("Erro: " + nomeCampo + " inválido.");
	    campo.focus() ;
            campo.select();
	    return false;
        }
    } else {
        alert("Erro: " + nomeCampo + " inválido.");
	campo.focus() ;
        campo.select();
	return false;
    }

    cgcA = rcgc;
    cgcB = "";
    controle = rcgc.substring(12,14);
    texto = "543298765432";
    contini = 13;

    for( j = 1; j <= 2; j++ ) {
        soma = 0;
        i = 1;
        while( i < contini ) {
            soma = soma + (parseInt(cgcA.substring(i-1,i))*parseInt(texto.substring(i-1,i)));
            i++;
        }
        digito = ( soma * 10 ) % 11;
        if( digito == 10 ) {
            digito = 0;
        }
        cgcB = cgcB + digito;
        texto = "6" + texto;
        cgcA = cgcA + digito;
        contini++;
    }
    if( controle == cgcB ){
        return true;
    } else {
        alert("Erro: " + nomeCampo + " inválido.");
	campo.focus() ;
        campo.select();
        return false;
    }

}

function validarNumeroDecimal(tecla, element) {
	numeros = '01234567890,.';
	if ( (numeros.indexOf(String.fromCharCode(tecla)) == -1 ) && tecla != 13 ) {
		event.returnValue = false;
	}

	if ( String.fromCharCode(tecla).indexOf(",") != -1 || String.fromCharCode(tecla).indexOf(".") != -1  ) {
	    if ( element.value.indexOf(".") != -1 ) {
	        event.returnValue = false;
	    }
	}
	
	if ( element.value.indexOf(".") != -1 ) {

    	 // Só pode ter 2 numeros nas casas decimais
         diferenca = element.value.length - element.value.indexOf(".");

         if (diferenca == 3) {
         	event.returnValue = false;
         }
    }
}

function validarNumeroDecimalSemImportarCadasDecimais(tecla, element) {
	numeros = '01234567890,.';
	if ( (numeros.indexOf(String.fromCharCode(tecla)) == -1 ) && tecla != 13 ) {
		event.returnValue = false;
	}

	if ( String.fromCharCode(tecla).indexOf(",") != -1 || String.fromCharCode(tecla).indexOf(".") != -1  ) {
	    if ( element.value.indexOf(".") != -1 ) {
	        event.returnValue = false;
	    }
	}	
}

function testarFormatoData(dateStr, descricao) {

	// Checks for the following valid date formats:
	// DD/MM/YY   DD/MM/YYYY   DD-MM-YY   DD-MM-YYYY

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		alert(descricao + " deve estar no formato DD/MM/AAAA")
		return false;
	}

	day = matchArray[1];
	month = matchArray[3]; // parse date into variables
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		alert("Mês deve ser entre 1 e 12.");
		return false;
	}

	if (day < 1 || day > 31) {
		alert("Dia deve ser entre 1 e 31.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("Mês "+month+" não tem 31 dias!")
		return false
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			alert("Fevereiro " + year + " não tem " + day + " dias!");
			return false;
		}
	}
	return true;  // date is valid
}
