$(function() {
	$("#tabs").tabs();
	$(".cpf").mask('999.999.999-99');
	$(".cnpj").mask('99.999.999/9999-99');
	$(".rg").mask('999999999999-9');
	$(".cnpj").mask('99.999.999/9999-99');
	$(".nascimento").mask('99/99/9999');
	$(".telefone").mask('(99) 9999-9999');
	$(".data").mask('99/99/9999');
	$(".cep").mask('99999-999');
	$(".hora").mask('99:99');
	//$(".site").mask('http://');
	$(".moeda").maskMoney({symbol:"R$",decimal:",",thousands:"."})
	$(".calendario").datepicker();
    $( ".calendario" ).datepicker( "option", "dayNamesShort", ['Do', 'Se', 'Te', 'Qa', 'Qi', 'Se', 'Sa'] );
	$( ".calendario" ).datepicker( "option", "dayNamesMin", ['Do', 'Se', 'Te', 'Qa', 'Qi', 'Se', 'Sa'] );
	$( ".calendario" ).datepicker( "option", "dateFormat", 'dd/mm/yy' );
	$( ".calendario" ).datepicker( "option", "monthNamesShort", ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'] );
	$( ".calendario" ).datepicker( "option", "monthNames", ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'] );
	$(".topicDois").hide();
	$(".topicTres").hide();
	$(".topicQuatro").hide();
	$(".topicCinco").hide();
	$('.pila').numeric();
});


$(function($) {
	$("#bntAvn").click(function(){
		$("#buscAvan").slideToggle("slow");
		return false;
	});

	$(".letter").click(function(){
		$.ajax({
			url: "scripts/ajax/consulta.php",
			type: "post",
			dataType: "html",
			data: "opcao=ba&letra="+$(this).html(),
			success: function (msg){
				if(msg!=''){
					$("#resultCidade").html(msg);
				}
			},
			beforeSend: function(){
				$(status).html("<img src='img/loading.gif' alt='carregando' />");
			}
		});
	});
	
	$(".more_recados").click(function() {
		var ultimo = $(".recados tr:last").attr("lang");
		var url = $(this).attr("rel");
		$(".status").html("<img src='../../img/loading.gif' alt='carregando' />");
		$.post(url, {ultimo: ultimo}, function(resposta) {
		   $(".status").empty();
		   $(".recados").append(resposta);
		});
	});
	
	$(".confirmacao").click(function(){
			if(confirm("Confirma esta ação?")) return true; else return false;
		});
		
	$(".botao-comentar").click(function(){
			if($("#text-comentario").val()==""){
				$("#texto-comentario").css("display", "block");
				$(".botao-comentar").html("<span class='icone'></span> Enviar");
			} else { $("#form-comentario").submit();}
	});
		

		$(".aceitar, .rejeitar").click(function() {
			var id = $(this).attr("lang");
			var acao = $(this).attr("rel");
			var parent = $(this).parent();
			var url = "../../scripts/convite.php";
			$.post(url, {acao: acao, id:id}, function(resposta) {
				parent.parent().fadeOut("slow");
			});
		});
});


    $(function($) {
        $(".all_agendamentos").click(function() {
            $(".agendamentos").empty();
			var url = "../../scripts/busca_agendamentos.php";
            $(".status_agenda").html("<img src='../../img/loading.gif' alt='carregando' />");
            $.post(url, {}, function(resposta) {
               $(".status_agenda").empty();
               $(".agendamentos").append(resposta);
				$(".all_agendamentos").hide();
				bindEvents();
            });
        });
    });

	var pg=1;			
    $(function($) {
        $(".more_indicacoes").click(function() {
            //var ultimo = $(".indicacoes tr:last").attr("lang");
			var ultimo = $("table tr:last-child").attr("lang");
            var url = $(this).attr("rel");
            $(".status").html("<img src='../../img/loading.gif' alt='carregando' />");
            $.post(url, {ultimo: ultimo}, function(resposta) {
					if(resposta!=''){
					   $(".status").empty();
					   $(".indicacoes").append(resposta);
						pg++;
						bindEvents();
					} else {
							$(".status").empty();
							$(".more_indicacoes").hide();
							}
            });
        });
    });

	var pg_clientes=0;
    $(function($) {
        $(".more_clientes").click(function() {
			if(pg_clientes==0){
				pg_clientes=1;
			}
            //var ultimo = $(".indicacoes tr:last").attr("lang");
			var ultimo = pg_clientes*3;
            var url = $(this).attr("rel");
            $(".status_clientes").html("<img src='../../img/loading.gif' alt='carregando' />");
            $.post(url, {ultimo: ultimo}, function(resposta) {
               $(".status_clientes").empty();
               $(".clientes").append(resposta);	
				bindEvents();			
				pg_clientes++;
            });
        });
    });

function selecionaCliente(valor, pagina){
		$.ajax({
			type: "POST",
			url: pagina,
			data: "id="+valor,
			success: function(msg){
				$('#dados_cliente').html(msg);
				return false;
				},
				beforeSend: function(){
				$('#dados_cliente').html("<img src='img/ajax-loader_4.gif' alt='aguarde' title='aguarde'>");
				}
		});
}

function selecionaEstado(pagina, valor){
		$.ajax({
			type: "POST",
			url: pagina,
			data: "id="+valor,
			success: function(msg){
				$('#cidades').html(msg);
				return false;
				},
				beforeSend: function(){
				$('#cidades').html("<img src='img/ajax-loader_4.gif' alt='aguarde' title='aguarde'>");
				}
		});
}


$(function() {
$(".delete-action").click(function() {
var href = $(this).attr("href");
var dataString = $(this).attr("rel");
var parent = $(this).parent().parent();
	
$.ajax({
   type: "POST",
   url: href,
   data: dataString,
   cache: false,

   success: function(msg)
   {
		alert(msg);

    if(1 == 1)
	{
    parent.fadeOut('slow', function() {$(this).remove();});
	}
	else
	{
	parent.slideUp('slow', function() {$(this).remove();});
	}
  }
   
 });

return false;
	});
});

function delete_action(campo){
		
		var href = $(campo).attr("href");
		var dataString = $(campo).attr("rel");
		var parent = $(campo).parent().parent();
		$.ajax({
		type: "POST",
		url: href,
		data: dataString,
		cache: false,
		success: function(msg){
		if(1 == 1){
		parent.fadeOut('slow', function() {$(campo).remove();});
			}
		else{
			parent.slideUp('slow', function() {$(campo).remove();});
			}
		}
		
		});
		
		return false;
}
$(document).ready(function(){
	$("a[rel^='prettyPhoto']").prettyPhoto({show_title:false,modal:true, counter_separator_label:false, allowresize: true});
	$("a[rel^='prettyPhoto']").click(function(){$(this).removeClass('negrito');});
	  $('.copy').focus(function(){
		this.select();
	  }).click(function(){
		this.select();
	  });
});

function bindEvents() {
	$('.indicacoes a').bind('click', $("a[rel^='prettyPhoto']").prettyPhoto({show_title:false,modal:true, counter_separator_label:false}));
	$('.recados a').bind('click', $("a[rel^='prettyPhoto']").prettyPhoto({show_title:false,modal:true, counter_separator_label:false}));

}

function filtraRecados(valor){
		var url = "../../scripts/busca_recados.php";
		$.ajax({
			type: "POST",
			url: url,
			data: "lido="+valor,
			success: function(msg){
		   $(".status").empty();
		   $(".recados").html(msg);
			bindEvents();
				return false;
				},
				beforeSend: function(){
					$(".status").html("<img src='../../img/loading.gif' alt='carregando' />");
				}
		});
}

function AAA(){
	$(".opcaoA").show();
	$(".opcaoB").hide();
	$(".opcaoC").hide();
	$("#formulario").show();
}
function BBB(){
	$(".opcaoA").hide();
	$(".opcaoB").show();
	$(".opcaoC").hide();
	$("#formulario").show();

}
function CCC(){
	$(".opcaoA").hide();
	$(".opcaoB").show();
	$(".opcaoC").show();
	$("#formulario").show();
}

function mostraCampo(campo){
	$(campo).show();
	return false;
}

function escondeCampo(campo){
	$(campo).hide();
	return false;
}

function responder(id, status){
		var url = "../../scripts/envia_recado.php";
		var valor = $(id).val();;
		$.ajax({
			type: "POST",
			url: url,
			data: "recado="+valor+"&id="+id,
			success: function(msg){
			   alert(msg);
				$(status).empty();
				$(status).html("<span>Enviado com sucesso.</span>");
				return false;
				},
				beforeSend: function(){
					$(status).html("<img src='../../img/loading.gif' alt='carregando' />");
				}
		});
}

$(document).ready(function(){
$.validator.setDefaults({
	//submitHandler: function() { alert("submitted!"); },
	highlight: function(input) {
		$(input).addClass("obrigatorio");
	},
	unhighlight: function(input) {
		$(input).removeClass("obrigatorio");
	}
	});

   $("#formsoliciti").validate();
	
	//$(".tooltip").tooltip();

	//$("#divulgacao_texto").limit(144,"#restante");

$.validator.setDefaults({
		rules: {
			login_usuario: {required:true},
			optlogin:{required:true},
			optemail:{required:true},
			senha_usuario:{required:true},
			confirmesenha_usuario:{required:true,equalTo:"#senha_usuario"},
			email_usuario:{required:true, 
							email: true},
			confirmeemail_usuario:{required:true,email: true,equalTo:"#email_usuario"},
			tipo_usuario:{required:true},
			li:{required:true}
		},
		messages: {
			login_usuario: {required:'Campo necessário'},
			optlogin:'Login indisponível',
			optemail:'Email indisponível',
			senha_usuario: 'Campo necessário',
			confirmesenha_usuario: {required:'Campo necessário',equalTo:'Senhas não conferem'},
			email_usuario: {required:'Campo necessário', email:'Email inválido'},
			confirmeemail_usuario: {required:'Campo necessário', email: true,equalTo:'Emails não conferem'},
			tipo_usuario: 'Campo necessário',
			li: 'Campo necessário'
		}
	});

$("#formCadastro").validate();
	jQuery.validator.addMethod("loginDisponivel", function(value, element, params) {
		
		//$.ajax({type:"POST", url: 'scripts/ajax/consulta.php', data: 'opcao=login&login='+value, success: function(msg){return msg;}});
		return ajax('scripts/ajax/consulta.php', 'opcao=login&login='+value, 'verificalogin');
	}, "Login indiponível!");
	
	jQuery.validator.addMethod("emailDisponivel", function(value, element, params) {
		var campo = ajax('scripts/ajax/consulta.php', 'opcao=email&email='+value, 'verificaemail');
	return campo;
		}, "Email indiponível!");
	
});

function required(checkbox, input){
	if(checkbox.checked){
	$(input).removeClass("required");
	}else $(input).addClass("required");
}

function addLink(){
	$("#links").append("Site: <input type='text' value='' name='links[]' size='50' class='site' /><br />");
	//$(".site").mask('http://');
	return false;
}

function indica(){
	id = document.getElementById('idvendedor').value;
	if(document.getElementById('idvendedor') && document.getElementById('logvend') && document.getElementById('senhavend')){
		usuario = document.getElementById('logvend').value;
		senha = document.getElementById('senhavend').value;
		url = "indicar.php?id="+id+"&logvend="+usuario+"&senhavend="+senha+"&iframe=true&width=60%&height=80%";
	} else url = "indicar.php?id="+id+"&iframe=true&width=60%&height=80%";
	$.prettyPhoto.open(url,'Indique um amigo para este vendedor','Faça uma indicação e ganhe por isso!');
}


function mostra(campo){
      $(campo).slideToggle("slow");
	  return false;
	 }
	 
var qt_vendedores=10;
function maisvendedores(){
		$.ajax({
		url: "scripts/mais_vendedores.php",
		type: "get",
		dataType: "html",
		data: "inicio="+qt_vendedores,
		success: function (msg){
			if(msg!=''){
				$("#block_mais_vend").append(msg);
				qt_vendedores+=10;
			} else {$('#mais_vendedores').hide()};
		}
	});
}

function historico(id){	
	var url = "../../scripts/historico_compra.php";
	$.ajax({
		type: "POST",
		url: url,
		data: "id="+id,
		success: function(msg){
			$("#"+id).html("");
			$("#"+id).html(msg);
			},
			beforeSend: function(){
			}
	});
}
function affiliates(id, campo, img){
	
	dimensoes = $(campo).val().split("|");
	height = dimensoes[0];
	width = dimensoes[1];
	texto = "<a href=\"http://www.indicavenda.com.br/2011/affiliates.php?id="+ id +"\"><img src=\"http://www.indicavenda.com.br/2011/img/afiliados/"+ img +"\" width='" + width + "'  height='" + height + "' /></a>";
	$("#copy").html(texto);
}

function opcao(valor){
	switch(valor){
		case 'A':$("#opA").show();$("#opB").hide();$("#opC").hide();$("#opD").hide();
		break;
		case 'B':$("#opA").hide();$("#opB").show();$("#opC").hide();$("#opD").hide();
		break;
		case 'C':$("#opA").hide();$("#opB").hide();$("#opC").show();$("#opD").hide();
		break;
		case 'D':$("#opA").hide();$("#opB").hide();$("#opC").hide();$("#opD").show();
		break;
	}
}

function limiteCaracteres() {
	return 144;
}
function updateMessageCounter(){
	var campo = document.getElementById('divulgacao_texto');
	var numCaracteres = limiteCaracteres() -(campo.value.length + campo.value.length);
	
	if(numCaracteres<0)
	{
		campo.value = campo.value.substring(0,campo.value.length + numCaracteres);
		numCaracteres=0;
		return false;
	}
	document.getElementById("idCount").innerHTML = numCaracteres;	
	return true;
}

function ajax(pagina, parametros, iddestino, idcampo){
		$.ajax({
			type: "POST",
			url: pagina,
			data: parametros,
			success: function(msg){
				if(msg=='true'){
					$('#'+iddestino).html("<img src='img/green-tick.gif' width='16' height='16'><input type='hidden' value='1' id='"+idcampo+"' name='"+idcampo+"'>");
				} else $('#'+iddestino).html("<img src='img/red-tick.gif' width='16' height='16' title='Indisponível'><input type='hidden' value='' id='"+idcampo+"' name='"+idcampo+"'>");
				},
				beforeSend: function(){
				$('#'+iddestino).html("<img src='img/loading.gif' alt='aguarde' title='aguarde'>");
				}
		});
}

function isEmail(email){
	if ((email.length != 0) && ((email.indexOf("@") < 1) || (email.indexOf('.') < 7))) return false; else return true;
}

function limpar(campo){
	$("#"+campo).html("");
}

function comentaIndicacao(){
	var texto = $("#texto-comentario").val();
	if(texto!=''){
		$.ajax({
			type: "POST",
			url: "../../scripts/lembrete.php",
			data: "texto="+texto,
			success: function(msg){
				$('#comentar').html(msg);
				},
				beforeSend: function(){
				$('#comentar').html("<img src='img/loading.gif' alt='aguarde' title='aguarde'>");
				}
		});
	}
	return false;
}

function shareplugin(campo, id, pagina){
	var dimensoes = $(campo).val();
	dimensoes = dimensoes.split("x");
	var altura = dimensoes[1];
	var largura = dimensoes[0];
	$("#share-frame").val("<iframe src=\"http://www.indicavenda.com.br/new/plugin/"+pagina+"?id="+id+"\" height='"+altura+"px' width='"+largura+"px' frameborder='0' ></iframe>");
}
