// JavaScript Document
function pageload(hash,recipiente) {
	//alert(hash)
	if(recipiente) {//ADICIONEI A FUNÇÃO DO RECIPIENTE PARA PODER MUDAR O LOADER DO JQUERY
		recipiente = recipiente
	} else {
		recipiente = ".linkMenu"
	}
	//alert(hash)
	//força o ajax a fazer sempre um novo carregamento evitando cache no IE
	var tempo = new Date()
	var novo = tempo.getYear() +''+ tempo.getMonth() +''+ tempo.getDay() +''+ tempo.getHours() +''+ tempo.getMinutes() +''+ tempo.getSeconds() +''+ tempo.getMilliseconds()
	if(hash) {
		$(".linkMenu").load("controlador.asp?n="+novo+"&"+hash);
	} else {
		// start page
		$(".linkMenu").load("controlador.asp?n="+novo+"&session=index");
	}
}


$(document).ready(function(){
	var tempo = new Date()
	var novo = tempo.getYear() +''+ tempo.getMonth() +''+ tempo.getDay() +''+ tempo.getHours() +''+ tempo.getMinutes() +''+ tempo.getSeconds() +''+ tempo.getMilliseconds()
	//$("#miolo").load("controlador.asp");
	$(".linkMenu").ajaxComplete(function() {
		$("#flashHome").html(objSWF("swf/home.swf","779","725"));
	});
	
	$.historyInit(pageload);
	$("a[@rel=linkMenu]").click(function(){
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		$.historyLoad(hash,this.id);
		return false;
	});
	
	$(".linkMenu").ajaxComplete(function() {
		$("a[@rel='linkAjax']").click(function(){
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			$.historyLoad(hash,this.id);
			return false;
		});		   
	});	
	// troca pessoa fisica e juridica
	$("#pessoaF").click(function(){
		mlink = window.location + "&";
		mlink = mlink.split("&");
		//alert(mlink[0])
		window.open(mlink[0],"_self")
	});
	$("#pessoaJ").click(function(){
		mlink = window.location + "&";
		mlink = mlink.split("&");
		//alert(mlink[0])
		window.open(mlink[0]+"&pessoa=j","_self")
	});
	
	if ($('form#formCadastro').attr("id")) validaForm('form#formCadastro');
	//** SUBMIT DOS FORMULÁRIOS
	$("form#formCadastro input#continuar").click(function(){
		$('#erroPost').attr("style", "display:none;");
		
		$.each($('form#formCadastro'),function(){
			var input = $('input',this).get();
			for (var i in input) {
				nomeForm = "form#formCadastro"
				objName	 = input[i].className;
				objID	 = input[i].id
				myInput	 = input[i]
				
				if(objName=="rec_dia" || objName=="rec_mes" || objName=="rec_ano")	{
					objID	 = "recAno";
					myInput	 = nomeForm+" input#ano_aniv";
				};
				
				if(objName=="rec_ddd" || objName=="rec_fone")	{
					objID = objID.replace("ddd_","");
					myInput	= nomeForm+" input#"+objID;
				};
				
				if(objName=="rec_cep1" || objName=="rec_cep2")	{
					objID = objID.replace("init_","");
					myInput	= nomeForm+" input#"+objID;
					//alert(myInput);
				};
				
				if(objName.substring(0,3)=="rec") {
					myEM = $("#erro"+objID).text();
					if(!myEM) $(myInput).after('<em id="erro'+objID+'">&nbsp;</em>');
					//alert(myInput)
				};
				//alert(objID)

				validaDados("erro",input[i],'form#formCadastro');
			 }
		});
		checaEmail("form#formCadastro input#email");
		checaCPF("form#formCadastro input#cpf_cnpj");
		
		alertas = 0;
		$.each($('form#formCadastro'),function(){
			if ($("#entregaN").attr('checked') == true) alertas = -6
			var erros = $('em',this).get();
			for (var i in erros) {
				if ($(erros[i]).html()!="&nbsp;") {alertas++};
			}
		});

		//alert(alertas)
		//return false
		if (alertas > 0) {
			$('#erroPost').attr("style", "display:block;");
			//$("#erroPost").html("Existem alguns erros no formulario!");
			$("#erroPost").html("Existem alguns erros no formulario, verifique!");
			return false;
		}
		
		$.each($('form#formCadastro'),function(){
			chave = "check_email|check_cpf_cnpj|";
			valor = $("form#formCadastro input#email").val()+"|"+$("form#formCadastro input#cpf_cnpj").val()+"|";
			 
			var input = $('input:radio',this).get();
			for (var i in input) {
				if (input[i].checked == true) {
					chave = chave + input[i].name+"|";
					valor = valor + input[i].value+"|";
				}
			 }

			var input = $('input:password',this).get();
			for (var i in input) {
				if(input[i].name != "") {
					chave = chave + input[i].name+"|";
					valor = valor + input[i].value+"|";
				}
			 }

			var input = $('input:text',this).get();
			for (var i in input) {
				if(input[i].name != "") {
					chave = chave + input[i].name+"|";
					valor = valor + input[i].value+"|";
				}
			 }
			 
			var input = $('input:hidden',this).get();
			for (var i in input) {
				if(input[i].name != "") {
					chave = chave + input[i].name+"|";
					valor = valor + input[i].value+"|";
				}
			 }

		});
		valor = valor.replace("'"," ");
		dadosD 	= chave+"&"+valor;
		//alert(dadosD);
		
		//dadosD	= dadosD.replace("'","&rsquo;")
		dados	= URLEncode (dadosD);
		//alert(dados);
		
		//$('#erroPost').attr("style", "display:block;");
		//$("#erroPost").html(dados)
		//return false
		//** checando c o email existe na base de dados
		email = $("form#formCadastro input#email").val();
		$.post("ajax_functions.asp","op=checkMail&valor=email&conteudo="+email,function(span){
			total = span.replace("<span>","")
			total = total.replace("</span>","")
			if (total==1) {
				$("#erroemail").addClass("erro");
				$("#erroemail").html("Endere&ccedil;o j&aacute; cadastrado");
				
				$('#erroPost').attr("style", "display:block;");
				$("#erroPost").html("Existem alguns erros no formulario 1!");
				//$("#erroPost").html("Existem alguns erros na IDENTIFICAÇÃO, verifique!");
				
				return false
			} else {//** caso naum exista checo o CPFs
					cpf_cnpj = $("form#formCadastro input#cpf_cnpj").val()
					$.post("ajax_functions.asp","op=check&valor=cpf_cnpj&conteudo="+cpf_cnpj,function(span){
						//alert(span)
						total = span.replace("<span>","")
						total = total.replace("</span>","")
						if (total==1) {
							$("#errocpf_cnpj").addClass("erro");
							$("#errocpf_cnpj").html("J&aacute; cadastrado");
							
							$('#erroPost').attr("style", "display:block;");
							$("#erroPost").html("Existem alguns erros no formulario 2!");
							//$("#erroPost").html("Existem alguns erros nos DADOS PESSOAIS, verifique!");
							return false
						} else {//** caso o cpf naum exista ai sim dou o post no formulário
							$.post("04_carrinho.asp?op=add",dados,function(html) {
								if(html == "<html>1</html>") {
									window.open("04_carrinhoConfirma.asp", '_parent');
								} else 	if(html == "<html>2</html>") {
									window.open("04_carrinhoConfirma.asp", '_parent');
								} else{
									$('#erroPost').attr("style", "display:block;");
									$("#erroPost").html("Existem alguns erros no formulario 3!");
									//$("#erroPost").html("Existem alguns erros nos DADOS PESSOAIS, verifique!");
									return false;
								}
					
							});
						};
					});
				};
		});		
		return false;
	});
	//** SUBMIT DO FORMULÁRIOS
	
	
	
	//*OCULTANDO OS DADOS DO CEP
	var inputCep1 = $('#cep').attr("value");
	//alert(inputCep1)
	if (inputCep1 == undefined) {
		$('fieldset.cep1 label.cep1').attr("style", "display:none;");
	}
	var inputCep2 = $('input#entregaN').attr("checked");
	if (inputCep2 == true) {
		$('fieldset.cep2').attr("style", "display:none;");
	}
	//*OCULTANDO OS DADOS DO CEP
	
	
	// validando cep e checando no webservice
	$("form#formCadastro input#cep").keypress(function(){
		$('fieldset.cep1 label.cep1').attr("style", "display:block;");
	});
	$("form#formCadastro input#cep").blur(function(){
		cep1 = $("form#formCadastro input#init_cep").val()
		cep2 = $(this).val()
		//alert(cep2.length)
		if(cep2.length==3) {
			cep = cep1+""+cep2
			$("form#formCadastro input#endereco").val("carregando...")
			$("form#formCadastro input#bairro").val("carregando...")
			$("form#formCadastro input#cidade").val("carregando...")
			$.post("ajax_functions.asp","op=jGeraEnd&cep="+cep,function(span){
				
				valorEnds = span.replace("<span>","")
				valorEnds = valorEnds.replace("</span>","")
				valorEnds = valorEnds.split("|")
				$("form#formCadastro input#endereco").val(valorEnds[0])
				$("form#formCadastro input#bairro").val(valorEnds[1])
				$("form#formCadastro input#cidade").val(valorEnds[2])
				$("form#formCadastro input#estado").val(valorEnds[3])
			});
		};
	});
	
	$("form#formCadastro input#cepent").keypress(function(){
		$('fieldset.cep2 label.cep2').attr("style", "display:block;");
	});
	$("form#formCadastro input#cepent").blur(function(){
		cep1 = $("form#formCadastro input#init_cepent").val()
		cep2 = $(this).val()
		//alert(cep2.length)
		if(cep2.length==3) {
			cep = cep1+""+cep2
			$("form#formCadastro input#endent").val("carregando...")
			$("form#formCadastro input#bent").val("carregando...")
			$("form#formCadastro input#cident").val("carregando...")
			$.post("ajax_functions.asp","op=jGeraEnd&cep="+cep,function(span){
				valorEnds = span.replace("<span>","")
				valorEnds = valorEnds.replace("</span>","")
				valorEnds = valorEnds.split("|")
				$("form#formCadastro input#endent").val(valorEnds[0])
				$("form#formCadastro input#bent").val(valorEnds[1])
				$("form#formCadastro input#cident").val(valorEnds[2])
				$("form#formCadastro input#estent").val(valorEnds[3])
			});
		};
	});
	
	$("#entregaN").click(function(){
		$('fieldset.cep2').attr("style", "display:none;");
		$('fieldset.cep2 label.cep2').attr("style", "display:none;");
	
	});
	
	$("#entregaS").click(function(){
		$('fieldset.cep2').attr("style", "display:block;");
		$('fieldset.cep2 label.cep2').attr("style", "display:none;");
	
	});
	
	// validando cep e checando no webservice
	
	// validando email e checando no webservice
	$("form#formCadastro input#email").blur(function(){
		checaEmail(this);
	});
	// validando email e checando no webservice


	// validando email e checando no webservice
	$("form#formCadastro input#cpf_cnpj").blur(function(){
		checaCPF(this);
	});
	// validando email e checando no webservice
	
	
	$(".formConfirma #continuar").click(function(){
		window.open("05_carrinho.asp", '_parent');
	});
	$(".formConfirma #voltar").click(function(){
		window.open("03_carrinho.asp", '_parent');
	});


	$("#logar").click(function(){
		email = $("#email").attr("value")
		senha = $("#senha").attr("value")
		dados=email+"&"+senha

		$.post("04_carrinho.asp?op=checa",dados,function(html) {
			if(html == "<html>1</html>") {
				window.open("05_carrinho.asp", '_parent');
			} else if(html == "<html>2</html>") {
				window.open("index.asp#session=produtos", '_parent');
			} else  {
				$('#formLogaerro').attr("style", "display:block;");
				$("#formLogaerro").html("Usu&aacute;rio e/ou senha inv&aacute;lidos!");
				return false;
			}

		});

		return false
	});
	$("#sendSenha").click(function(){
		email = $("#recEmail2").attr("value")
		dados=email
		$.post("send_senha.asp",dados,function(html) {
			//alert(html)
			if(html == "<html>1</html>") {
				$('#formEnvioSenhaerro').attr("style", "display:block;");
				$("#formEnvioSenhaerro").html("Dados enviados com sucesso");
			} else {
				$('#formEnvioSenhaerro').attr("style", "display:block;");
				$("#formEnvioSenhaerro").html("Usu&aacute;rio inv&aacute;lido!");
				return false;
			}

		});

		return false
	});

	$("#esqueci").click(function(){
		$('#divLog1').attr("style", "display:none;");
		$("#divLog2").attr("style", "display:block;");
		return false
	});
});



function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}













