/*
Função     : Fornece os JavaScripts comuns
Autor      : Cerli Rocha
Data       : 11/08/2004
atualizada : 11/08/2004
*/

//VALIDACAO DE LOGINS
function validaLogin(){
         if ( !TestaUser() ) {
			  return false;
		 }
         if ( !TestaSenha() ) {
			  return false;
		 }
		 return true;
}

function dropBlanks( oStrToBeDropped ){
         var oRet = "";
         var c_next = 0;
         var c_prev = 0;
         for( i = 0; i < oStrToBeDropped.length; i++ ){
              c_next = oStrToBeDropped.charAt( i );
              if( c_next == ' ' ){
                  }else{
                   oRet = oRet + c_next;
              }
	          c_prev = c_next;
          }
		  return oRet;
}

function TestaUser() {
        var user = dropBlanks(document.forms[0].USERNAME.value.toLowerCase());
        var c;
 
        if(user.length < 4) {
           alert(" LOGIN inválido.  Mínimo 4 caracteres.");
           return false;
        }
 
        if(user.length > 10) {
           alert(" LOGIN inválido.  Máximo 10 caracteres.");
           return false;
        }

        var valor = /[0-9]/;
        valor = valor.exec(user.substring(0,1));
        if(valor == null) {
           c = user.substring(0,1);
           alert("LOGIN inválido.  Não pode iniciar por " + c);
           return false;
        }
 
        var usval = /[^a-z0-9_.]/.exec(user);
        if(usval != null) {
           alert("LOGIN inválido. Possui caracteres inválidos.");
           return false;
        }
        return true;
}

function TestaSenha() {
        var senha = dropBlanks(document.forms[0].SENHA.value.toLowerCase());
        var c;

        if(senha.length < 4) {
           alert(" SENHA inválida.  Mínimo 4 caracteres.");
           return false;
        }

        if(senha.length > 10) {
           alert(" SENHA inválida.  Máximo 10 caracteres.");
           return false;
        }

        var valor = /[a-z0-9]/;
        valor = valor.exec(senha.substring(0,1));
        if(valor == null) {
           c = senha.substring(0,1);
           alert("SENHA inválida.  Não pode iniciar por " + c);
           return false;
        }

        var usval = /[^a-z0-9_.]/.exec(senha);
        if(usval != null) {
           alert("SENHA inválida. Possui caracteres inválidos.");
           return false;
        }
        return true;
}
//FIM DA VALIDACAO DE LOGINS

//INICIO DAS FUNCOES NATIVAS DO DREAWEAVER
function MM_openBrWindow(theURL,winName,features) { //v2.0
         window.open(theURL,winName,features);
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.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); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//FIM DAS FUNCOES NATIVAS DO DREAWEAVER

//FUNCAO PARA LIMPAR BRANCOS DA STRING
function trim(inputString) {
         if (typeof inputString != "string") {
		     return inputString; 
		 }
         
		 var retValue = inputString;
         var ch = retValue.substring(0, 1);
         
		 while (ch == " ") { // Check for spaces at the beginning of the string
                retValue = retValue.substring(1, retValue.length);
                ch = retValue.substring(0, 1);
         }
         
		 ch = retValue.substring(retValue.length-1, retValue.length);
		 
		 while (ch == " ") { // Check for spaces at the end of the string
			    retValue = retValue.substring(0, retValue.length-1);
			    ch = retValue.substring(retValue.length-1, retValue.length);
		 }
         
		 while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
                retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
         }
         
		 return retValue; // Return the trimmed string back to the user
} 
//FIM DA FUNCAO PARA LIMPAR BRANCOS DA STRING

//Função para navegar de acordo com o target recebido
function navegador( TARGET ) {
         if (( TARGET != null )&&( TARGET != "" )) {
		       document.location = TARGET;
		 }      
}
//Fim da função para navegar de acordo com o target recebido

///Função para limpar os forms, o parametro é o indice do form
function limpar( ID ) {
         if ( ID != null ) {
              for ( i=0; i<=document.forms[ID].elements.length-1; i++ ) {
		            if ( document.forms[ID].elements[i].value != "" ) {
						 document.forms[ID].elements[i].value = "" ;
					}
			   }
         }
		 return false;
}
///Fim da Função para limpar os forms

//Valida CPF
function validaCPF(cpf) {
		 if ( cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999" ) { 
			  return false;
		 }
		 soma = 0;
		 for ( i=0; i < 9; i++ ) {
		       soma += parseInt(cpf.charAt(i)) * (10 - i);
		 }
		 resto = 11 - (soma % 11);
		 if ( resto == 10 || resto == 11 ) {
		      resto = 0;
		 }
		 if ( resto != parseInt(cpf.charAt(9)) ) {
		      return false;
		 }
		 soma = 0;
		 for ( i = 0; i < 10; i ++ ) {
		       soma += parseInt(cpf.charAt(i)) * (11 - i);
		 }
		 resto = 11 - (soma % 11);
		 if ( resto == 10 || resto == 11 ) {
		      resto = 0;
		 }
		 if ( resto != parseInt(cpf.charAt(10)) ) {
		      return false;		 
		 }
		 return true;
}

function validaCNPJ(cnpj) {
		 var calcCNPJ;
		 var s1;
		 var s2;
		 var i;
		 var soma;
		 var digito;
		 var result;
		 s1 = cnpj;
		 result = false;
		 if ( s1.length != 14 ) {
		      return result;
		 }
		 if ( s1 == '00000000000000' ) {
		      return result;
		 }
		 calcCGC = s1.substring(0, 12);
		 //  Cálculo do 1º dígito
		 soma = 0;
		 for ( i = 1; i <= 4; i++ ) {
		       soma = soma + (calcCGC.charAt(i-1) * (6 - i));
		 }
		 for ( i = 1; i <= 8; i++ ) {
		       soma = soma + (calcCGC.charAt(i + 3) * (10 - i));
		 }
		 digito = 11 - (soma % 11);
		 if ( (digito == 10) || (digito == 11) ) {
		       calcCGC = calcCGC + '0';
		       } else {
		         calcCGC = calcCGC + digito;
		 }
		 // Cálculo do 2º dígito
		 soma = 0;
		 for ( i = 1; i <= 5; i++ ) {
		       soma = soma + (calcCGC.charAt(i-1) * (7 - i));
		 }
		 for ( i = 1; i <= 8; i++ ) {
		       soma = soma + (calcCGC.charAt(i + 4) * (10 - i));
		 }
		 digito = 11 - (soma % 11);
		 if ( (digito == 10) || (digito == 11) ) {
		       calcCGC = calcCGC + '0';
		       } else {
		         calcCGC = calcCGC + digito;
		}
		if ( calcCGC == s1 ) {
		     result = true;
		}
		return result;
}

// Este script mostra um pop-up no meio da página do visitante 
function popup( titulo, alvo, largura, altura ) {
		 var titulo = titulo;
		 var pagina = alvo;
		 var largura = largura;             
		 var altura  = altura;             
		 var posLargura = (screen.width / 2) - (largura / 2); //calcula o left
		 var posAltura  = (screen.height / 2) - (altura / 2);  //calcula o top
		 var propriedades = 'toolbar=no,';          // retira a barra de  trabalho 
		 propriedades    += 'margin=no,';         // retira a barra de localização 
		 propriedades    += 'location=no,';         // retira a barra de localização 
		 propriedades    += 'directories=no,';      // retira a barra de  diretorios 
		 propriedades    += 'status=no,';           // retira a barra de  status 
		 propriedades    += 'menubar=no,';          // retira a barra de  menu 
		 propriedades    += 'scrollbars=yes,';     // retira as barras  de rolagem 
		 propriedades    += 'resizable=no,';        // retira a opção de  reescalagem da janela 
		 propriedades    += 'width='+largura+',';   // largura da janela 
		 propriedades    += 'height='+altura+',';   // altura da janela 
		 propriedades    += 'left='+posLargura+','; // posição inicial  horizontal da janela 
		 propriedades    += 'top='+posAltura;       // posição inicial  vertical da janela  
		 window.open(pagina, titulo, propriedades); //abre a popup no meio da tela
}

//FUNÇÃO DAS LINHAS DAS TABELAS DO ADMIN
var Selecionado = null;
var Estilo_sel  = null;
function Seleciona(Tab, Estilo) {
	     if( Selecionado != null ) {
             Selecionado.className = Estilo_sel;
		 }
	     Tab.className = "clsTabSelecionado";
	     Selecionado   = Tab;
		 Estilo_sel    = Estilo;
}
//FIM DA FUNÇÃO DAS LINHAS DAS TABELAS DO ADMIN

// Funções Dreamweaver
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);
// Fim das funções do dreamweaver

//Validação do News
function validaNews() {
		 for ( i=0; i <= ( (document.FORM_NEWS.elements.length) - 2 ); i++ ) {
			   if ( document.FORM_NEWS.elements[i].value == "" ) {
					alert('o campo '  + document.FORM_NEWS.elements[i].name + ' não esta preenchido!');
				    document.FORM_NEWS.elements[i].focus();
					return false;
			   }
		 }
		 return true;
}
//Fim da Validação do News

//Validação do MOnte seu Micro
var monte_ok = false;
function validaMonte() {
         if ( monte_ok == false ) {
			  alert('Você deve selecionar pelo menos um componente!');
			  return false;
		 }
         setMonte(false);
		 return true;
}

function setMonte(STATUS) {
         monte_ok = STATUS;
}
//Fim da Validação do MOnte seu Micro

//Validação do Cadastro
function validaCadastro() {
		 for ( i=0; i <= ( (document.FORM_CADASTRO.elements.length) - 2 ); i++ ) {
			   if ( ( document.FORM_CADASTRO.elements[i].name != "EMPRESA" )&&( document.FORM_CADASTRO.elements[i].name != "CNPJ" )&&( document.FORM_CADASTRO.elements[i].name != "RG" )&&( document.FORM_CADASTRO.elements[i].name != "CPF" )&&( document.FORM_CADASTRO.elements[i].name != "COMPLEMENTO" ) ) {
					  if ( document.FORM_CADASTRO.elements[i].value == "" ) {
						   alert('o campo '  + document.FORM_CADASTRO.elements[i].name + ' não esta preenchido!');
						   document.FORM_CADASTRO.elements[i].focus();
						   return false;
					  }
			   }
		 }
		
		 if ( document.FORM_CADASTRO.DIA.options[document.FORM_CADASTRO.DIA.selectedIndex].value == "" ) {
			  alert('Você deve selecionar um opção no campo DIA!');
			  return false;
		 }

		 if ( document.FORM_CADASTRO.MES.options[document.FORM_CADASTRO.MES.selectedIndex].value == "" ) {
			  alert('Você deve selecionar um opção no campo MÊS!');
			  return false;
		 }

		 if ( document.FORM_CADASTRO.ANO.options[document.FORM_CADASTRO.ANO.selectedIndex].value == "" ) {
			  alert('Você deve selecionar um opção no campo ANO!');
			  return false;
		 }
		 
		 if ( document.FORM_CADASTRO.ESTADO.options[document.FORM_CADASTRO.ESTADO.selectedIndex].value == "" ) {
			  alert('Você deve selecionar um opção no campo ESTADO!');
			  return false;
		 }

		 if ( document.FORM_CADASTRO.PAIS.options[document.FORM_CADASTRO.PAIS.selectedIndex].value == "" ) {
			  alert('Você deve selecionar um opção no campo PAIS!');
			  return false;
		 }
		 return true;
}
//Fim da Validação do Cadastro

//Validação dos Contatos
function validaContato() {
		 for ( i=0; i <= ( (document.FORM_CONTATO.elements.length) - 2 ); i++ ) {
			   if ( document.FORM_CONTATO.elements[i].value == "" ) {
					alert('o campo '  + document.FORM_CONTATO.elements[i].name + ' não esta preenchido!');
				    document.FORM_CONTATO.elements[i].focus();
					return false;
			   }
		 }
		 
		 if ( document.FORM_CONTATO.DESTINO.options[document.FORM_CONTATO.DESTINO.selectedIndex].value == "" ) {
			  alert('Você deve selecionar um opção no campo DESTINO!');
			  return false;
		 }

		 return true;
}
//Fim da Validação dos Contatos

//Alterna as cores de linhas de tabelas
function changeBGColor(obj, color){eval(obj).style.backgroundColor=color};

//Testa o tipo de entrega e habilita os campos necessários
function seta_tipo( VALOR ) {
		 if ( VALOR == 'SEDEX_DINHEIRO' ) {
              troca_tipo(0);	//habilita correio
			  seta_cheque(0);	//desabilita cheque
			  seta_cartao(0);	//desabilita cartao
			  seta_padrao(1);	//habilita padrao
	     }
         if ( VALOR == 'SEDEX_CARTAO' ) {
              troca_tipo(0);	//habilita correio
			  seta_cheque(0);	//desabilita cheque	     
			  seta_cartao(1);	//habilita cartao
			  seta_padrao(1);	//habilita padrao
		 }
         if ( VALOR == 'MOTOBOY_DINHEIRO' ) {
              troca_tipo(1);	//habilita motoboy
			  seta_cheque(0);	//desabilita cheque	     
			  seta_cartao(0);	//desabilita cartao
			  seta_padrao(1);	//habilita padrao
		 }
         if ( VALOR == 'MOTOBOY_CHEQUE' ) {
              troca_tipo(1);	//habilita motoboy
			  seta_cheque(1);	//habilita cheque	     
			  seta_cartao(0);	//desabilita cartao
			  seta_padrao(1);	//habilita padrao
         }
         if ( VALOR == 'MOTOBOY_CARTAO' ) {
              troca_tipo(1);	//habilita motoboy
			  seta_cheque(0);	//desabilita cheque	     
			  seta_cartao(1);	//habilita cartao
			  seta_padrao(1);	//habilita padrao
		 }
		 /*
		 PAGAMENTOS BANRISUL
		 */
         if ( VALOR == 'MOTOBOY_BANRICOMPRAS_VISTA' ) {
              troca_tipo(1);	//habilita motoboy
			  seta_cheque(0);	//desabilita cheque	     
			  seta_cartao(0);	//desabilita cartao
			  seta_padrao(1);	//habilita padrao
		 }
		 if ( VALOR == 'SEDEX_BANRICOMPRAS_VISTA' ) {
              troca_tipo(0);	//habilita correio
			  seta_cheque(0);	//desabilita cheque
			  seta_cartao(0);	//desabilita cartao
			  seta_padrao(1);	//habilita padrao
	     }
		 /*
		 FIM DOS PAGAMENTOS BANRISUL
		 */
}

function seta_padrao( VALOR ) {
		 if ( document.getElementById("PADRAO") ) {
			  if ( VALOR == 0 ) {
				   document.getElementById("PADRAO").style.display = 'none'; 
				   document.getElementById("PADRAO1").style.display = 'none'; 
				   document.getElementById("PADRAO2").style.display = 'none'; 
				   document.getElementById("PADRAO3").style.display = 'none'; 
				   document.getElementById("PADRAO4").style.display = 'none'; 
				   } else {
				     document.getElementById("PADRAO").style.display = 'block'; 
				     document.getElementById("PADRAO1").style.display = 'block'; 
				     document.getElementById("PADRAO2").style.display = 'block'; 
				     document.getElementById("PADRAO3").style.display = 'block'; 
				     document.getElementById("PADRAO4").style.display = 'block'; 
			  }
		 }
}

function seta_cheque( VALOR ) {
		 if ( document.getElementById("CHEQUE") ) {
			  if ( VALOR == 0 ) {
				   document.getElementById("CHEQUE").style.display  = 'none'; 
				   document.getElementById("CHEQUE1").style.display = 'none'; 
				   document.getElementById("CHEQUE2").style.display = 'none'; 
				   } else {
					 document.getElementById("CHEQUE").style.display  = 'block'; 
					 document.getElementById("CHEQUE1").style.display = 'block'; 
					 document.getElementById("CHEQUE2").style.display = 'block'; 
			  }
		 }
}

function seta_cartao( VALOR ) {
		 if ( document.getElementById("CARTAO") ) {
			  if ( VALOR == 0 ) {
				   document.getElementById("CARTAO").style.display  = 'none'; 
				   document.getElementById("CARTAO1").style.display = 'none'; 
				   document.getElementById("CARTAO2").style.display = 'none'; 
				   document.getElementById("CARTAO3").style.display = 'none'; 
				   document.getElementById("CARTAO4").style.display = 'none'; 
				   } else {
					 document.getElementById("CARTAO").style.display  = 'block'; 
					 document.getElementById("CARTAO1").style.display = 'block'; 
					 document.getElementById("CARTAO2").style.display = 'block'; 
					 document.getElementById("CARTAO3").style.display = 'block'; 
					 document.getElementById("CARTAO4").style.display = 'block'; 
			  }
		 }
}

function troca_tipo( VALOR ) {
         if ( VALOR == 0 ) {
			  //Correios
			  //document.FORM_PEDIDO.BAIRRO.disabled = false;
			  //document.FORM_PEDIDO.CIDADE.disabled = false;
			  //document.FORM_PEDIDO.ESTADO.disabled = false;
			  //document.FORM_PEDIDO.CEP.disabled    = false;
			  if ( document.getElementById("CORREIO") ) {
				   document.getElementById("CORREIO").style.display  = 'block'; 
				   document.getElementById("CORREIO1").style.display = 'block'; 
				   document.getElementById("CORREIO2").style.display = 'block'; 
				   document.getElementById("CORREIO3").style.display = 'block'; 
			  }
			  //Entregas
			  //document.FORM_PEDIDO.POA_BAIRROS.disabled    = true;
			  //document.FORM_PEDIDO.OUTRAS_CIDADES.disabled = true;
			  //document.FORM_PEDIDO.DATA.disabled           = true;
			  //document.FORM_PEDIDO.HORARIO.disabled        = true;
			  if ( document.getElementById("ENTREGA") ) {
				   document.getElementById("ENTREGA").style.display  = 'none';
				   document.getElementById("ENTREGA1").style.display = 'none';
				   document.getElementById("ENTREGA2").style.display = 'none';
			  }
		      } else {
			    //Correios
			    //document.FORM_PEDIDO.BAIRRO.disabled = true;
			    //document.FORM_PEDIDO.CIDADE.disabled = true;
				//document.FORM_PEDIDO.CIDADE.disabled = true;
			    //document.FORM_PEDIDO.CEP.disabled    = true;
				if ( document.getElementById("CORREIO") ) {
					 document.getElementById("CORREIO").style.display = 'none'; 
					 document.getElementById("CORREIO1").style.display = 'none';
					 document.getElementById("CORREIO2").style.display = 'none'; 
					 document.getElementById("CORREIO3").style.display = 'none'; 
				}
			    //Entregas
			    //document.FORM_PEDIDO.POA_BAIRROS.disabled    = false;
			    //document.FORM_PEDIDO.OUTRAS_CIDADES.disabled = false;
			    //document.FORM_PEDIDO.DATA.disabled           = false;
			    //document.FORM_PEDIDO.HORARIO.disabled        = false;
				if ( document.getElementById("ENTREGA") ) {
					 document.getElementById("ENTREGA").style.display  = 'block';
					 document.getElementById("ENTREGA1").style.display = 'block';
					 document.getElementById("ENTREGA2").style.display = 'block';
				}
		 }
}

//Atualiza a taxa de entrega
function atualiza_taxa( VALOR ) {
		 document.FORM_PEDIDO.TAXA_ENTREGA_BACKUP.value = document.FORM_PEDIDO.TAXA_ENTREGA.value;
         document.FORM_PEDIDO.TAXA_ENTREGA.value        = divide_string( VALOR, 0 );
		 document.FORM_PEDIDO.VALOR_MINIMO.value        = divide_string( VALOR, 1 );
		 atualiza_controle(1);
}

//Divide o valor recebido num array
function divide_string( VALOR, INDICE ) {
         var retorno = "";
         var retorno = VALOR.split("@@");
         return retorno[INDICE];
}

//Recalcula o valor final do Pedido
function recalcular( VALOR ) {
         document.FORM_PEDIDO.TAXA_ENTREGA.disabled = false;
         //document.FORM_PEDIDO.action = 'index.php#CALCULO';
		 document.FORM_PEDIDO.action = 'index.php';
		 atualiza_controle(0);
         document.FORM_PEDIDO.submit();
}

//Atualiza o campo de controle
function atualiza_controle( STATUS ) {
		 document.FORM_PEDIDO.CAMPO_CONTROLADOR.value = STATUS;
}

function toInt ( x ) {
	     x = x.replace( ",", "." );
	     return ( x > 0 ? Math.floor( x ) : Math.ceil ( x ) );
}

function colocaZeros( VALOR ){
     	 VALOR = VALOR.replace( ".", "," );
	     if ( VALOR.indexOf(",") == -1 ) {
			  VALOR = VALOR + ",00"; 
		 }
		 return VALOR;
}

function limpaCombos() {
          if ( document.FORM_PEDIDO.ESTADO ) {
               document.FORM_PEDIDO.ESTADO.selectedIndex = -1;	
		  }
          if ( document.FORM_PEDIDO.POA_BAIRROS ) {
               document.FORM_PEDIDO.POA_BAIRROS.selectedIndex = -1;	
		  }
          if ( document.FORM_PEDIDO.OUTRAS_CIDADES ) {
               document.FORM_PEDIDO.OUTRAS_CIDADES.selectedIndex = -1;	
		  }
}
//Validação do Orçamento
function validaPedidoWeb() {
	     //TESTA SE OS CALCULOS FORAM ATUALIZADOS
         if ( document.FORM_PEDIDO.CAMPO_CONTROLADOR.value == 1 ) {
		      alert("Você deve clicar em \n[ Somar valor do pedido mais taxa de entrega ou sedex ]\n antes de enviar este pedido");
			  return false;
		 }

         if ( ( document.FORM_PEDIDO.TAXA_ENTREGA.value == 0 )||( document.FORM_PEDIDO.TAXA_ENTREGA.value == "" ) ) {
		      alert("Selecione sua cidade, estado ou bairro novamente, pois, por algum motivo a taxa de entrega esta inválida!!!");
			  limpaCombos();
			  atualiza_controle(1);
			  return false;
		 }

		 //TESTA SE O VALOR DO PEDIDO TOTAL ESTA DE ACORDO COM O PEDIDO MINIMO 
         if ( toInt(document.FORM_PEDIDO.TOTAL.value) < toInt(document.FORM_PEDIDO.VALOR_MINIMO.value) ) {
		      alert( "O pedido mínimo para este destino é de " + document.FORM_PEDIDO.VALOR_MINIMO.value );
			  return false;
		 }
		 
		 //NOME
		 if ( trim(document.FORM_PEDIDO.NOME.value) == "" ) {
			  alert('o campo NOME não esta preenchido!');
			  document.FORM_PEDIDO.NOME.focus();
			  return false;
		 }
		 
		 //ENDEREÇO
		 if ( trim(document.FORM_PEDIDO.ENDERECO.value) == "" ) {
			  alert('o campo ENDEREÇO não esta preenchido!');
			  document.FORM_PEDIDO.ENDERECO.focus();
			  return false;
		 }  

         //TIPO DE ENTREGA
	     var OK           = 0;
		 var TIPO_ENTREGA = 0;
		 for ( i=0; i<document.FORM_PEDIDO.TIPO_ENTREGA.length; i++ ) {
			   if ( document.FORM_PEDIDO.TIPO_ENTREGA[i].checked ) {
				    TIPO_ENTREGA = document.FORM_PEDIDO.TIPO_ENTREGA[i].value;
					OK = 1;
			   }                                                 
		 }                  

		 if ( OK==0 ) { 
			  alert('É necessário selecionar uma opção no TIPO DE ENTREGA!');
			  return false;
		 }
		 
		 //ENTREGA POR SEDEX
		 //DINHEIRO OU CARTAO
		 if ( ( TIPO_ENTREGA == 'SEDEX_DINHEIRO' )||( TIPO_ENTREGA == 'SEDEX_CARTAO' ) ) {
			    //BAIRRO
			    if ( trim(document.FORM_PEDIDO.BAIRRO.value) == "" ) {
				     alert('o campo BAIRRO não esta preenchido!');
				     document.FORM_PEDIDO.BAIRRO.focus();
				     return false;
			    }  
			    //CIDADE
			    if ( trim(document.FORM_PEDIDO.CIDADE.value) == "" ) {
				     alert('o campo CIDADE não esta preenchido!');
				     document.FORM_PEDIDO.CIDADE.focus();
				     return false;
			    }
			    //ESTADO
			    if ( document.FORM_PEDIDO.ESTADO.options[document.FORM_PEDIDO.ESTADO.selectedIndex].value == "0" ) {
				     alert('Você deve selecionar um opção no campo ESTADO!');
				     return false;
			    }
			    //CEP
			    if ( trim(document.FORM_PEDIDO.CEP.value) == "" ) {
				     alert('o campo CEP não esta preenchido!');
				     document.FORM_PEDIDO.CEP.focus();
				     return false;
			    }
		   }
		   
		   //Testa cartão SEDEX / MOTOBOY
		   if ( ( TIPO_ENTREGA == 'SEDEX_CARTAO' )||( TIPO_ENTREGA == 'MOTOBOY_CARTAO' ) ) {
				  //Testa se algum cartão gfoi selecionado
				  var OK_CARTAO   = 0;
				  var TIPO_CARTAO = 0;
				  for ( i=0; i<document.FORM_PEDIDO.TIPO_CARTAO.length; i++ ) {
					    if ( document.FORM_PEDIDO.TIPO_CARTAO[i].checked ) {
							 TIPO_CARTAO = document.FORM_PEDIDO.TIPO_CARTAO[i].value;
							 OK_CARTAO = 1;
					    }                                                 
				  }                  
				  if ( OK_CARTAO==0 ) { 
					   alert('É necessário selecionar uma opção no TIPO DE CARTÃO!');
					   return false;
				  }
				  //Fim do teste do cartão
				  //Testa o nr do cartão
				  if ( trim(document.FORM_PEDIDO.NR_CARTAO.value) == "" ) {
					   alert('o campo NR DO CARTÃO não esta preenchido!');
					   document.FORM_PEDIDO.NR_CARTAO.focus();
					   return false;
				  }
				  //Fim do teste do nr do cartão
				  //Testa a validade do cartão
				  if ( trim(document.FORM_PEDIDO.VALIDADE_CARTAO.value) == "" ) {
					   alert('o campo VALIDADE DO CARTÃO não esta preenchido!');
					   document.FORM_PEDIDO.VALIDADE_CARTAO.focus();
					   return false;
				  }
				  //Fim do teste da validade do cartão
				  //Testa se alguma parcela foi selecionado
				  OK_CARTAO      = 0;
				  PARCELA_CARTAO = 0;
				  for ( i=0; i<document.FORM_PEDIDO.PARCELAS_CARTAO.length; i++ ) {
					    if ( document.FORM_PEDIDO.PARCELAS_CARTAO[i].checked ) {
							 PARCELA_CARTAO = document.FORM_PEDIDO.PARCELAS_CARTAO[i].value;
							 OK_CARTAO = 1;
					    }                                                 
				  }                  
				  if ( OK_CARTAO==0 ) { 
					   alert('É necessário selecionar uma opção nas PARCELAS DO CARTÃO!');
					   return false;
				  }
				  //Fim do teste da parcela do cartão
		   }

		   //ENTREGA POR MOTOBOY
		   //DINHEIRO ou CHEQUE
		   if ( ( TIPO_ENTREGA == 'MOTOBOY_DINHEIRO' )||( TIPO_ENTREGA == 'MOTOBOY_CHEQUE' )||( TIPO_ENTREGA == 'MOTOBOY_CARTAO' ) ) {
			      //BAIRROS DE POA OU OUTRAS CIDADES
			      if ( ( document.FORM_PEDIDO.POA_BAIRROS.options[document.FORM_PEDIDO.POA_BAIRROS.selectedIndex].value == "0" ) && 
			         ( document.FORM_PEDIDO.OUTRAS_CIDADES.options[document.FORM_PEDIDO.OUTRAS_CIDADES.selectedIndex].value == "0" ) ){
				       alert('Você deve selecionar um opção no campo PORTO ALEGRE BAIRROS ou no Campo OUTRAS CIDADES!');
				       return false;
			      }
			      if ( ( document.FORM_PEDIDO.POA_BAIRROS.options[document.FORM_PEDIDO.POA_BAIRROS.selectedIndex].value != "0" ) && 
			         ( document.FORM_PEDIDO.OUTRAS_CIDADES.options[document.FORM_PEDIDO.OUTRAS_CIDADES.selectedIndex].value != "0" ) ){
				       alert('Você deve selecionar APENAS um opção no campo PORTO ALEGRE BAIRROS ou no Campo OUTRAS CIDADES!');
				       return false;
			      }
				  //DATA DE ENTREGA
			      if ( trim(document.FORM_PEDIDO.DATA.value) == "" ) {
				       alert('o campo DATA DE ENTREGA não esta preenchido!');
				       document.FORM_PEDIDO.DATA.focus();
				       return false;
			      }
			      //HORARIO
			      if ( document.FORM_PEDIDO.HORARIO.options[document.FORM_PEDIDO.HORARIO.selectedIndex].value == "0" ) {
				       alert('Você deve selecionar um opção no campo HORAS!');
				       return false;
			      }
				  //CHEQUE
				  if ( TIPO_ENTREGA == 'MOTOBOY_CHEQUE' ) {
					   //BANCO
					   if ( trim(document.FORM_PEDIDO.NR_BANCO.value) == "" ) {
						  alert('o campo BANCO não esta preenchido!');
						  document.FORM_PEDIDO.NR_BANCO.focus();
						  return false;
					 }
					 //AGENCIA
					 if ( trim(document.FORM_PEDIDO.NR_AGENCIA.value) == "" ) {
						  alert('o campo AGENCIA não esta preenchido!');
						  document.FORM_PEDIDO.NR_AGENCIA.focus();
						  return false;
					 }
					 //CONTA
					 if ( trim(document.FORM_PEDIDO.NR_CONTA.value) == "" ) {
						  alert('o campo CONTA não esta preenchido!');
						  document.FORM_PEDIDO.NR_CONTA.focus();
						  return false;
					 }
					 //CHEQUE
					 if ( trim(document.FORM_PEDIDO.NR_CHEQUE.value) == "" ) {
						  alert('o campo CHEQUE não esta preenchido!');
						  document.FORM_PEDIDO.NR_CHEQUE.focus();
						  return false;
					 }
					 //C3
					 if ( trim(document.FORM_PEDIDO.NR_C3.value) == "" ) {
						  alert('o campo C3 não esta preenchido!');
						  document.FORM_PEDIDO.NR_C3.focus();
						  return false;
					 }
 					 //CPF
					 if ( trim(document.FORM_PEDIDO.NR_CPF.value) == "" ) {
						  alert('o campo CPF não esta preenchido!');
						  document.FORM_PEDIDO.NR_CPF.focus();
						  return false;
					 }
				}
		 }
		 document.FORM_PEDIDO.TAXA_ENTREGA.disabled = false;
		 return true;
}
//Fim da Validação do Orçamento

//Trazer setado o tipo de entrega escolhidos
function setar_entrega( INDICE ) {
		 document.FORM_PEDIDO.TIPO_ENTREGA[INDICE].click();
}
//Trazer setado o tipo de cartao
function setar_cartao( INDICE ) {
		 document.FORM_PEDIDO.TIPO_CARTAO[INDICE].click();
}
//Trazer setado as parcelas do cartao
function setar_parcela_cartao( INDICE ) {
		 document.FORM_PEDIDO.PARCELAS_CARTAO[INDICE].click();
}
//Trazer setado as parcelas do cheque
function setar_parcela_cheque( INDICE ) {
		 document.FORM_PEDIDO.PARCELAS_CHEQUE[INDICE].click();
}
//Alterar as quantidades dos produtos
function setar_quantidade( INDICE, ACAO ) {
         document.FORM_PEDIDO.TAXA_ENTREGA.disabled = false;
         document.FORM_PEDIDO.action = 'index.php?INDICE_QUANTIDADE=' + INDICE + '&ACAO_QUANTIDADE=' + ACAO;
		 //atualiza_controle(0);
         document.FORM_PEDIDO.submit();



//var teste = CAMPO_ATUAL.length;
//	alert( document.FORM_PEDIDO.QUANTIDADE[0] );
	
		 /*
		 //Diminuir
		 if ( ACAO == '0' ) {
		      if ( CAMPO_ATUAL.value > 0 ) {
			       CAMPO_ATUAL.value = CAMPO_ATUAL.value - 1;
			  }
		 }
		 //Aumentar
		 if ( ACAO == '1' ) {
		      if ( CAMPO_ATUAL.value != '' ) {
			       CAMPO_ATUAL.value = CAMPO_ATUAL.value + 1;
			       } else {
				     CAMPO_ATUAL.value = 0;
			  }
		 }
		 */
}

function comprar( DOMINIO, LINK, REFERENCIA, DESCRICAO, PRECO ) {
/*	     if ( LINK != '' ) {
			  //FINALIZAR
			  if(confirm(' Você acaba de adicionar o seguinte produto:\n\n Ref.' + REFERENCIA + ' - ' + DESCRICAO + ' - R$ ' + colocaZeros(PRECO) + ' \n\n Se deseja finalizar seu pedido \nclicar em [ OK ], senão clicar em [ CANCELAR ]')) {
				 top.frames['PEDIDO'].location = '' + LINK + '&FINALIZAR=1';
			     } else { //CONTINUAR COMPRANDO
				   top.frames['PEDIDO'].location = '' + LINK + '';
				   document.location = ' ../index.php ';
			  }
		 }*/
		 window.open(DOMINIO + 'pop_confirma.php?REFERENCIA=' + REFERENCIA + '&LINK=' + LINK + '&DESCRICAO=' + DESCRICAO + '&VALOR=R$ ' + colocaZeros(PRECO),'CONFIRMA','width=350,height=200');
}

//Funções Banrisul
function submeterBanrisul( url ) {
	     Opcoes = 'width=800,height=600';
		 window.open( url, "Demonstrativo", Opcoes, true );
}

//Ajax
try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}

atual=0
var zerado = 0;

function zerar(){
         zerado = 1;	
}

function carrega( DOMINIO, LINK ){
	
    //Exibe o texto carregando no div conteúdo
    var conteudo=document.getElementById("cesta_pedido")
    conteudo.innerHTML='<div class="carregando">carregando...</div>'

    //Guarda a página escolhida na variável atual
    atual=LINK

    //Abre a url
	//alert(zerado);
	if ( zerado == 0 ) {
		 target = DOMINIO + "pedidos/gerenciar_pedidos.php?LINK="+atual+"";
	     }else{
		  conteudo.innerHTML='<div class="carregando">esvaziando cesta...</div>'
		  target = DOMINIO + "pedidos/gerenciar_pedidos.php?ZERADO=1";
	}
		
    xmlhttp.open("GET", target,true);

    //Executada quando o navegador obtiver o código
    xmlhttp.onreadystatechange=function() {

        if (xmlhttp.readyState==4){

            //Lê o texto
            var texto=xmlhttp.responseText

            //Desfaz o urlencode
            texto=texto.replace(/\+/g," ")
            texto=unescape(texto)

            //Exibe o texto no div conteúdo
            var conteudo=document.getElementById("cesta_pedido")
            conteudo.innerHTML=texto
        }
    }
    xmlhttp.send(null)
}

