function ajax() {
};
ajax.prototype.iniciar = function()
{
	try { this.xmlhttp = new XMLHttpRequest(); }
	catch(ee)
	{
		try { this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch(e)
		{
			try { this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(E) { this.xmlhttp = false; }
		}
	}
	return true;
}

ajax.prototype.ocupado = function()
{
	estadoAtual = this.xmlhttp.readyState;
	return (estadoAtual && (estadoAtual < 4));
}

ajax.prototype.processa = function()
{
	if(this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) { return true; }	
}

ajax.prototype.enviar = function(url, metodo, modo)
{
	if(!this.xmlhttp) { this.iniciar(); }
	if(!this.ocupado())
	{
		if(metodo == "GET")
		{
			this.xmlhttp.open("GET", url, modo);
			this.xmlhttp.send(null);
		}
		else
		{        
			this.xmlhttp.open("POST", url, modo);
			this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			this.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			this.xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
			this.xmlhttp.setRequestHeader("Pragma", "no-cache");
			this.xmlhttp.send(url);
		}    
		
		if(this.processa) { return unescape(this.xmlhttp.responseText.replace(/\+/g," ")); }
	}
	return false;
}

function verificapesquisa()
{
	var re = "/#@?$%~|pau|xoxota|xereca|#@?$%~|c*|piranha|#@?$%~|buceta|viado|viadinho|#@?$%~|pariu|f***-se|boiola|boióla|f**** f***|boiola|bicha|bichinha|c*|caralhão|cuzinho|putinha|crioulo|criolo|crioulinho|crioinho|escroto|gls|rola|rôla|boquete|caralha|chupa|pica|piru|penis|pênis|vagina|f******|m*****|puto|babaca|viadão|bunda|nadega|gay/gi";
	if(document.getElementById('keywords').value=='') 
	{
		alert('Preencha o campo para a pesquisa');
		document.getElementById('keywords').focus();
		return false;
	}
	else if(document.getElementById('keywords').value.length < 4)
	{
		alert('Preencha pelo menos 4 caracteres para a pesquisa'); 
		document.getElementById('keywords').focus();
		return false;
	}
	else if(re.test(document.getElementById('keywords').value))
	{
		alert('Palavra inapropriada para efetuar uma busca');
		return false;
	}
	else return true;
}


function exibe_detalhes(id)
{
	//var win = null;
	var LeftPosition = (screen.width) ? (screen.width-500)/2 : 0;
	var TopPosition = (screen.height) ? (screen.height-600)/2 : 0;
	var settings = 'height=600,width=500,top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,resizable=no';
	window.open("template/PedidoDetails.php?id="+id,"Detalhes",settings);
}

function mensagem (tipo,cliente)
{
	switch(tipo)
	{
		case 'limpartudo':
		{
			if(confirm('Deseja realmente limpar toda a Lista de Desejos?'))
			{
				document.location.href = 'system/ActionHandler.execute.php?hdnTo=desejo&hdnAction=del&hdnRegisterID=' + cliente;
			}
			break;
		}
		case 'adicionarcarrinho':
		{
			if(confirm('Deseja incluir esse(s) item(ns) ao carrinho?'))
			{
				document.location.href = 'system/ActionHandler.execute.php?hdnTo=wishlist&hdnAction=ins';
			}
			break;
		}
	}
}

function pf(value, i, codigoo, promo)
{
	var total,total2;
	b = document.getElementById("pv"+i).innerHTML;
	b = b.replace(",",".");
	total = b * value;
	total2 = total.toFixed(2);
	total2 = total2.replace(".",",");
	document.getElementById("vt"+i).innerHTML = total2;
	document.location.reload();
}

function check_promoqtde(quant,id)
{
	remoto  = new ajax();
	xmlhttp = remoto.enviar("qtde_checker.php?q=" + quant+ "&id="+id, 'POST', false );
	var res = xmlhttp.split('.'); 
	var res2 = xmlhttp.split('$$$'); 
	if(xmlhttp != "ok")
	{
		if(confirm("A quantidade minima permitida para a promoção é de: "+res[0]+".\n Deseja comprar esse item pelo preço não promocional?"))
		{
			document.getElementById("preco_prod").value=res2[1];
			document.getElementById("hdnPromocao").value="nao";
			return true;
		}
		else{
			document.getElementById("prod_qtde").focus();
			return false;
			}
	}
	else
	return true;
}

function buscaCEP(bEntrega)
{
	sEnt = bEntrega ? 'Entrega' : '';

	if($('#txtCEP'+sEnt).val() != '')
	{
		$('#ajxLoader').show();
		$.ajax({
			url: PROJECT_ROOT + 'system/ActionHandler.execute.php',
			type: 'POST',
			data: 'hdnAction=chk&hdnTo=clientecep&hdnCEP='+$('#txtCEP'+sEnt).val(),
			success: function(data){
				var arrEndereco = data.split('||');
				if(arrEndereco.length == 4)
				{
					$('#txtLogradouro'+sEnt).val(arrEndereco[0]);
					$('#txtBairro'+sEnt).val(arrEndereco[1]);
					$('#txtUF'+sEnt).val(arrEndereco[2]);
					$('#txtCidade'+sEnt).val(arrEndereco[3]);
					$('#spaCEPValido').html('Por favor, informe o número de seu endereço.');
					$('#txtNumero').focus();
				}
				else
				{
					$('#spaCEPValido').html('Ocorreu um erro na busca do CEP.');
				}
				$('#ajxLoader').hide();
			}
		});
	}
	else
	{
		$('#spaCEPValido').html('CEP não foi informado.');
	}	
}

function copiarEndereco()
{
	if($('#chkMesmoEndereco').is(':checked')) 
	{
		$('#txtCEPEntrega').val($('#txtCEP').val());
		$('#txtLogradouroEntrega').val($('#txtLogradouro').val());
		$('#txtNumeroEntrega').val($('#txtNumero').val());
		$('#txtComplementoEntrega').val($('#txtComplemento').val());
		$('#txtBairroEntrega').val($('#txtBairro').val());
		$('#txtUFEntrega').val($('#txtUF').val());
		$('#txtCidadeEntrega').val($('#txtCidade').val());
	}
	else
	{
		$('#txtCEPEntrega, #txtLogradouroEntrega, #txtNumeroEntrega, #txtComplementoEntrega, #txtBairroEntrega, #txtUFEntrega, #txtCidadeEntrega').val('');
	}
}

function submitCEP(e, ent)
{
	if(e.keyCode==13)
	{
		buscaCEP(ent);
	}
}

//funcao de teste de senha dificil
function yaysenha(senha, campo)
{
	var entrada = 0;
	var resultadoado;

	if(senha.length < 7) { entrada = entrada - 1; }
	if(!senha.match(/[a-z_]/i) || !senha.match(/[0-9]/)) { entrada = entrada - 1; }
	if(!senha.match(/\W/)) { entrada = entrada - 1; }
	if(entrada == 0)
	{
		resultado = 'A Seguran&ccedil;a de sua senha &eacute;: <font color=\'#99C55D\'>EXCELENTE</font>';
	}
	else if(entrada == -1)
	{
		resultado = 'A Seguran&ccedil;a de sua senha &eacute;: <font color=\'#7F7FFF\'>BOM</font>';
	}
	else if(entrada == -2)
	{
		resultado = 'A Seguran&ccedil;a de sua senha &eacute;: <font color=\'#FF5F55\'>BAIXA</font>';
	}
	else if(entrada == -3)
	{
		resultado = 'A Seguran&ccedil;a de sua senha &eacute;: <font color=\'#A04040\'>MUITO BAIXA</font>';
	}

	$(campo).html(resultado);
	return;
}

function mascara(o,f)
{
	v_obj=o;
	v_fun=f;
	setTimeout("execmascara()",1);
}

function execmascara()
{
	v_obj.value=v_fun(v_obj.value);
}

function soNumeros(v)
{
	return v.replace(/\D/g,"");
}

$(document).ready(function(){
    $('#destaques1').cycle({
		fx: 'fade',
		delay: -4000
	});

	/** FORM VALIDATIONS **/
	$('#frmLogin').validate({
		rules: {
			txtEmail: {
				required: true,
				email: true
			},
			txtSenha: 'required'
		}
	});
	
	$('#frmRecuperarSenha').validate({
		rules: {
			txtEmail: {
				required: true,
				email: true
			}
		}
	});

	$('#frmCliente')
		.find('#txtCPF')
			.attr('maxlength', 11)
			.numeric()
		.end()
		.find('#txtRG')
			.attr('maxlength', 9)
			.numeric()
		.end()
		.find('#txtDataNascimento')
			.attr('maxlength', 10)
		.end()
		.find('#txtTelefoneDDD, #txtCelularDDD')
			.attr('maxlength', 2)
			.numeric()
		.end()
		.find('#txtTelefone, #txtCelular, #txtCEP, #txtCEPEntrega')
			.attr('maxlength', 8)
			.numeric()
		.end()
		.find('#txtUF, #txtUFEntrega')
			.attr('maxlength', 2)
		.end()
		.validate({
			rules: {
				txtNome: 'required',
				rdoSexo: 'required',
				txtCPF: {
					required: true,
					maxlength: 14,
					remote: {
						url: PROJECT_ROOT + 'system/ActionHandler.execute.php',
						type: 'post',
						data: {
							hdnTo: 'clientecpf',
							hdnAction: 'chk'
						}
					}
				},
				txtRG: 'required',
				txtDataNascimento: {
					required: true,
					date: true
				},
				txtSenha: {
					required: true,
					maxlength: 20
				},
				txtSenhaVerifica: {
					required: true,
					maxlength: 100,
					equalTo: '#txtSenha'
				},
				txtTelefoneDDD: 'required',
				txtTelefone: 'required',
				txtCelularDDD: 'required',
				txtCelular: 'required',
				txtEmail: {
					required: true,
					email: true,
					maxlength: 200,
					remote: {
						url: PROJECT_ROOT + 'system/ActionHandler.execute.php',
						type: 'post',
						data: {
							hdnTo: 'clienteemail',
							hdnAction: 'chk',
							hdnActionFrom: $('#hdnAction').val() 
						}
					}
				},
				txtEmailVerifica: {
					required: true,
					email: true,
					maxlength: 200,
					equalTo: '#txtEmail'
				},
				txtCEP: 'required',
				txtLogradouro: {
					required: true,
					maxlength: 255
				},
				txtBairro: {
					required: true,
					maxlength: 150
				},
				txtUF: 'required',
				txtCidade: {
					required: true,
					maxlength: 200
				},
				txtCEPEntrega: 'required',
				txtLogradouroEntrega: {
					required: true,
					maxlength: 255
				},
				txtBairroEntrega: {
					required: true,
					maxlength: 150
				},
				txtUFEntrega: 'required',
				txtCidadeEntrega: {
					required: true,
					maxlength: 200
				}
			},
			messages: {
				txtCPF: {
					remote: 'CPF inv&aacute;lido! Favor verificar sua autenticidade.'
				},
				txtSenhaVerifica: {
					equalTo: 'As senhas não coincidem.'
				},
				txtEmail: {
					remote: 'E-mail j&aacute; cadastrado em nosso sistema. <a href="?p=esquecisenha">Esqueceu sua senha?</a>'
				},
				txtEmailVerifica: {
					equalTo: 'Os e-mails não coincidem.'	
				}
			},
			success: function(e) {
				var idInput = e.parent().find('input:text').attr('id');
				
				if(idInput == 'txtCPF') { e.text('CPF Válido!').addClass('alerta'); }
				else if(idInput == 'txtEmail' && $('#hdnAction').val()=='ins') { e.text('E-mail disponível!').addClass('alerta'); }
				
			}
		});
		
	$('#frmPesquisa').validate({
		submitHandler: function(){
			if($('#txtKeywords').val() != "")
			{
				registraTagCloud($('#txtKeywords').val());
			}
			else
			{
				alert("Por favor, preencha o campo com um termo a ser pesquisado.")
			}
			return false;								
		}
	});
	$('#frmCarrinho').validate({
		submitHandler: function(form){
			alert('Pedido sujeito a aprovação comercial e quantidades disponíveis em estoque.');
			form.submit();
		}
	});
	
	$('#frmNewsletter').validate({
		rules: {
			txtEmail: {
				maxlength: 150,
				email: true,
				required: true
			},
			txtNome: {
				maxlength: 200,
				required: true
			}
		},
		messages: {
			txtEmail: '',
			txtNome: ''
		},
		submitHandler: function(){
			$('#ajxLoader').show();
	   	$.ajax({
	   		url: 'system/ActionHandler.execute.php',
	   		type: 'POST',
	   		data: 'hdnTo=newsletter&hdnAction=ins&txtEmail='+$('#txtEmail').val()+'&txtNome='+$('#txtNome').val(),
	   		success: function(data){
	   			$('#ajxLoader').hide();
	   			$('#frmNewsletter').html('E-mail <strong style="font-weight:bold;">'+$('#txtEmail').val()+'</strong> cadastrado com sucesso.<br/>Em breve você estará recebendo nossos newsletters.');
	   		}
	   	});
		}
	});
	/** END **/

	$('#lnkFirstPage, #lnkLastPage, #lnkPreviousPage, #lnkNextPage, .lnk_page_number:not(.on .lnk_page_number)').click(function(){
		window.location = $('base').attr('href') + $(this).attr('rel') + '/' + $(this).attr('param'); 
	});
	
	/*$('#txtKeywords').click(function(){
		$.ajax({
			url: 'http://shopping.correios.com.br/wbm/shopping/script/CalcPrecoPrazo.aspx',
			data: {
				nCdEmpresa: '',
				sDsSenha: '',
				nCdServico: '41106',
				sCepOrigem: '12235000',
				sCepDestino: '12236231',
				nVlPeso: 1,
				nCdFormato: 1,
				nVlComprimento: 0,
				nVlAltura: 0,
				nVlLargura: 0,
				nVlDiametro: 0,
				sCdMaoPropria: 'N',
				nVlValorDeclarado: 0,
				sCdAvisoRecebimento: 'N',
				StrRetorno: 'XML'
			},
			success: function(xml, txt, xhr){
				//alert($(xml).find('preco_postal').text());
				alert(xhr.responseText);
			},
			error: function (xhr, ajaxOptions, thrownError){
			  alert(xhr.responseText);
			  //alert(thrownError);
			}    
		});
	});*/
});

jQuery.fn.loadJSOrCSS = function(pFileName){
	var oFile;
	if(pFileName.indexOf('css') > 0)
	{
		oFile = document.createElement('link');
		oFile.setAttribute('rel', 'stylesheet');
		oFile.setAttribute('type', 'text/css');
		oFile.setAttribute('href', pFileName);
	}
	else if(pFileName.indexOf('js') > 0)
	{
		oFile = document.createElement('script');
		oFile.setAttribute('type', 'text/javascript');
		oFile.setAttribute('src', pFileName);
	}
	else return false

	document.getElementsByTagName('head')[0].appendChild(oFile);
}


function registraTagCloud(sKeyword)
{
	$.ajax({
		url: PROJECT_ROOT + 'system/ActionHandler.execute.php',
		type: 'POST',
		data: 'hdnTo=tagcloud&hdnAction=ins&hdnKeyword=' + sKeyword,
		success: function(data){
			window.location = $('base').attr('href') + 'produtos/' + sKeyword + '/';
		}
	});
}