var isNS4 = (navigator.appName=="Netscape")?1:0;
var varValorTotal = 0;

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_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_findObj(n, d) { //v4.01
  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 && d.getElementById) x=d.getElementById(n); 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];}
}

function MM_showHideLayers() { //v6.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; }
}

function ConfirmaExclusao(secao,id) {
	msg = "Você está prestes a excluir o item selecionado. Tem certeza de que deseja prosseguir ?";
	if (confirm(msg))
		location.replace(secao + "_c.asp?Excluir=1&Id=" + id);
}

function VerificaValor(op,cepop) {
	
	if (getCookieValue('valorTotal')) {
		var valor = getCookieValue('valorTotal');

		if (+valor < 35) {
			alert("Apenas pedidos com valor acima de R$ 35,00 são atendidos !");
		}
		else {
			if (cepop == "1") {
				alert("Seu endereço cadastrado não é atendido pelo nosso serviço de entregas ! \n\nApenas  os bairros Leblon, Gávea, Lagoa, Ipanema, Recreio e Barra são atendidos.");
			}
			else {
				if (op == "1") {
					window.location = "confirma_pedido.asp";
				}
				else if (op == "2") {
					FormaPagamento.submit();
					window.location = "obrigado.asp";
				}
			}
		}
	}
	else {
		alert("Seu carrinho ainda está vazio !");
	}
}

function AlteraProduto(id,op,valor) {
	
	nomeCookie = "produto_" + id;
	
	if (getCookieValue('valorTotal')) {
		valorTotal = getCookieValue('valorTotal');
	}
	else {
		var valorTotal = 0;
		writeSessionCookie('valorTotal', valorTotal);
	}
	
	if (getCookieValue(nomeCookie)) {
		valorCookie = getCookieValue(nomeCookie);
	}
	else {
		var valorCookie = 0;
		writeSessionCookie(nomeCookie, valorCookie);
	}
	
	if (op=="mais") {
		valorCookie = +valorCookie + 1;
		valorTotal = +valorTotal + +valor;
	}
	else if (op=="menos") {
		if (valorCookie > 0) {
			valorCookie = +valorCookie - 1;
			if (valorTotal > 0) {
				valorTotal = +valorTotal - +valor;
			}
		}
	}
	else {
		quantidade = document.getElementById(nomeCookie).value;
		diferenca = +quantidade - +getCookieValue(nomeCookie);
		valorCookie = document.getElementById(nomeCookie).value;
		
		if (diferenca > 0) {
			valorTotal = +valorTotal + (diferenca*(+valor));
		}
		else {
			valorTotal = +valorTotal + (diferenca*(+valor));
		}
		
	}
	
	if (document.getElementById('TotalTemp_' + id)) {
		valorTemp = +valor * +valorCookie;
		document.getElementById('TotalTemp_' + id).value = "R$ " + FormataNumero(valorTemp,'.',',');
	}
	
	document.getElementById(nomeCookie).value = valorCookie;
	writeSessionCookie(nomeCookie, valorCookie);
	
	writeSessionCookie('valorTotal', valorTotal);
	document.getElementById('valorTotal').value = "R$ " + FormataNumero(valorTotal,'.',',');
	
	varValorTotal = document.getElementById('valorTotal').value;
}

function FormataNumero(numero,sepMil,sepDec,casasDec) {
	numero = numero.toFixed(2);
	strValor = numero.toString();
	tam = strValor.length;
	possepDec = strValor.lastIndexOf('.') + 1; //posição da divisão das casas decimais
	strInteiro = strValor.substr(0,tam-3); //string contendo o valor inteiro do número
	strDecimais = strValor.substr(possepDec,2); //string contendo as duas casas decimais do número
	auxStr_1 = "";
	auxStr_2 = "";
	numeroFinal = "," + strDecimais;
	
	tamInteiro = tam - 3;
	
	if (tamInteiro > 3) {
		for(i=tamInteiro-1; i>0;) {
			auxStr_1 = strInteiro.substr(i-2,3);
			auxStr_2 = strInteiro.substr(0,i-2);
			i = i -3;
			
			if (auxStr_2.length > 3) {
				strInteiro = auxStr_2;
				auxStr_1 = "." + auxStr_1;
			}
			else if (auxStr_2.length == 0) {
				numeroFinal = auxStr_1 + "." + numeroFinal;
				break;
			}
			else {
				numeroFinal = auxStr_2 + "." + auxStr_1 + numeroFinal;
				break;
			}
		}
	}
	else {
		numeroFinal = strInteiro + numeroFinal;
	}
	
	return numeroFinal;
}

function EntregaIgual() {
	
	if (CadastroForm.e_igual_c.checked == true) {
		CadastroForm.endereco_e.value = CadastroForm.obendereco_c.value;
		CadastroForm.bairro_e.value = CadastroForm.obbairro_c.value;
		CadastroForm.cidade_e.value = CadastroForm.obcidade_c.value;
		CadastroForm.uf_e.value = CadastroForm.obuf_c.value;
		CadastroForm.cep_e.value = CadastroForm.obcep_c.value;
		CadastroForm.endereco_e.disabled = true;
		CadastroForm.bairro_e.disabled = true;
		CadastroForm.cidade_e.disabled = true;
		CadastroForm.uf_e.disabled = true;
		CadastroForm.cep_e.disabled = true;
	}
	else {
		CadastroForm.endereco_e.value = '';
		CadastroForm.bairro_e.value = '';
		CadastroForm.cidade_e.value = '';
		CadastroForm.uf_e.value = '';
		CadastroForm.cep_e.value = '';
		CadastroForm.endereco_e.disabled = false;
		CadastroForm.bairro_e.disabled = false;
		CadastroForm.cidade_e.disabled = false;
		CadastroForm.uf_e.disabled = false;
		CadastroForm.cep_e.disabled = false;
	}
}

function AlteraSenha() {
	
	if (CadastroForm.alteraSenha.checked == true) {
		CadastroForm.obsenha.disabled = false;
		CadastroForm.obc_senha.disabled = false;
	}
	else {
		CadastroForm.obsenha.disabled = true;
		CadastroForm.obc_senha.disabled = true;
	}
}

function ChecaFormulario(formulario) {
	//ERRO=1 - Campo obrigatorio não preenchido;
	//ERRO=2 - Data Inválida
	//ERRO=3 - CPF Inválido
	//ERRO=4 - Endereço de entrega não informado
	//ERRO=5 - Conferência de senha inválida
	
	objForm = MM_findObj(formulario);
	
	var pass=true;
	if (document.images) {
		for (i=0;i<formulario.length;i++) {
			var tempobj=objForm.elements[i];
			
			//VERIFICA SE O CAMPO É OBRIGATÓRIO
			if (tempobj.name.substring(0,2)=="ob") {
				
				//VERIFICA SE O CAMPO ESTÁ EM BRANCO
				if (((tempobj.type=="text"||tempobj.type=="textarea"||tempobj.type=="password"||tempobj.type=="file")&&tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s" && tempobj.selectedIndex==0)) {
					Erro=1;
					msg="Todos os campos marcados com * devem ser preenchidos !";
					pass=true;
					break;
        }
			}
		}
	}
	
	if (pass) {
		//Verifica se a senha e a confirmaçào da senha são iguais
		if (objForm.obsenha.value != objForm.obc_senha.value) {
			msg="A confirmação de senha não confere !";
			Erro=7;
			pass=false;
		}
		
		//Verifica se endereço de entrega é igual ao endereço e cobrança e se não verifica se os campos estão em branco
		if ((!objForm.endereco_e.disabled) && ((objForm.endereco_e.value=="") || (objForm.bairro_e.value=="") || (objForm.cidade_e.value=="") || (objForm.uf_e.value=="") || (objForm.cep_e.value==""))) {
			msg="Favor informar o endereço de entrega !";
			Erro=6;
			pass=false;
		}
		
		//Verifica se os ceps
		cep_c = objForm.obcep_c.value;
		cep_e = objForm.cep_e.value;
		if (!isCep(cep_c)) {
			msg="Cep de entrega inválido !";
			Erro=5;
			pass=false;
		}
		if (cep_e.length > 0) {
			if (!isCep(cep_c)) {
				msg="Cep de entrega inválido !";
				Erro=5;
				pass=false;
			}
		}
		
		//Verifica se endereço de e-mail é válido
		email = objForm.obemail.value;
		if (!isEmail(email)) {
			msg="E-mail inválido !";
			Erro=4;
			pass=false;
		}
		
		//Verifica se a data de nascimento é válida
		data = objForm.obnascimento.value;
		if (!isDate(data)) {
			Erro=3;
			msg="Data de nascimento inválida !";
			pass=false;
		}
		
		//Verifica se o cpf é válido
		cpf = objForm.obcpf.value;
		if (!isCpf(cpf)) {
			Erro=2;
			msg="CPF inválido !";
			pass=false;
		}

	}

	if (pass) {
		//Desabilita o botão enviar/submit e muda o value dele para Aguarde...
		objForm.Cadastrar.value="Aguarde...";
		objForm.Cadastrar.disabled=true;
		
		//Envia o formulário
		objForm.submit();
	}
	else {
		alert(msg);
	}
}

function isDate(data) {
	data_atual = new Date();
	ano_minimo = 1900;
	ano_maximo = data_atual.getFullYear()-18;
	dataArray = data.split("/");

	if(dataArray.length != 3) {
		return false;
	}
	else {
		dia = dataArray[0];
		mes = dataArray[1];
		ano = dataArray[2];
		
		//Verifica se todos os caracteres são números
		if (!(isInteger(dia)) || !(isInteger(mes)) || !(isInteger(ano))) {
			return false;
		}
		else {
			//Verifica se o dia e o mes são válidos
			if ((dia > 31) || (mes > 12)) {
				return false;
			}
			
			//Verifica o ano
			if ((ano.length < 4) || ((+ano < ano_minimo) || (+ano > ano_maximo))) {
				return false;
			}
			
			//Verifica ano bisexto e meses com 30 dias
			else {
				if (+mes == 2) {
					if ((((ano % 4) == 0) && (dia > 29)) || (((ano % 4) != 0) && (dia > 28))) {
						return false;
					}
				}
				else {
					if (((mes == "4")||(mes == "6")||(mes == "9")||(mes == "11")) && (dia > 30)) {
						return false;
					}
				}
			}
		}
	}
	return true;
}

function isInteger(s) {
	var i;
    for (i = 0; i < s.length; i++) {   
			//Verifica se o caractere atual é número.
			var c = s.charAt(i);
			if (((c < "0") || (c > "9")))
				return false;
    }
    //Todos os caracteres são números.
    return true;
}

function isCpf(cpf) {
	if (cpf.length != 11) {
		return false;
	}
	else {
		verificacaoArray = new Array(11,10,9,8,7,6,5,4,3,2);
		digitosArray = new Array(0,0,0,0,0,0,0,0,0,0,0);
		verificadoresArray = new Array(0,0);
		soma = 0;
		z = 0;
    for (var i=0; i<cpf.length; i++) {
      digito = parseInt(cpf.charAt(i));
			pos = 11-(cpf.length-i);
			digitosArray[pos] = digito;
    }
		//Calcula os digitos verificadores
		for (j=1; j>-1; j--) {
			for (i=0; i<(10-j); i++) {
				soma = soma + (digitosArray[i] * verificacaoArray[i+j]);
			}
			verificadoresArray[z] = soma % 11;
			
			if (verificadoresArray[z] < 2) {
				verificadoresArray[z] = 0;
			}
			else {
				verificadoresArray[z] = 11 - verificadoresArray[z];
			}
			
			if (verificadoresArray[z] != digitosArray[9+z]) {
				Erro=2;
				msg="CPF inválido !";
				return false;
			}
			else {
				soma = 0;
				z = z + 1;
			}
		}
		return true;
	}
}

function isCep(cep) {
	if(cep.length < 8){
		return false;
	}
	return true;
}

function isEmail(email) {
	if((email.indexOf("@")==-1) || (email.indexOf(".")==-1)){
		return false;
	}
	return true;
}

function SoNumeros() {
	if (!isNS4) {
		if (event.keyCode < 48 || event.keyCode > 57)
			event.returnValue = false;
	}
	else {
		if (event.which < 48 || event.which > 57)
			return false;
	}
}
