function trim(str){return str.replace(/^\s+|\s+$/g,"");}

$(document).ready(function() {

    $(".postagem").hover(
      function () {
        $("#contez").html( $(this).attr("rel") );
      }, 
      function () {
        $("#contez").html('');
      }
    );


	$("input").each(function() { 
		if ($(this).attr("ID") == 'cep') {
			$(this).mask("99999-999");
		}
	});

$("input, #dominio, #dpn").blur(function() {

	   if ($(this).attr("ID") == 'cep') {
		   var ceplimpo= $(this).val().replace(/[^0-9]+/g,'');
		   if (ceplimpo != '') {
			   	verificacep(ceplimpo,this);
			} else {
			}
	   }

	   if (($(this).attr("ID") == 'dominio') || ($(this).attr("ID") == 'dpn'))  {
		   var dom1 = $("#dominio").val();
		   var dom2 = $("#dpn").val();
		   if ($(this).val() != '') {
			   	verificadominio(dom1,dom2);
			} else {
			}
	   }

});

	ufs("estado");
});


//VALIDA DATA
function data_valida(value) {
	 //contando chars
	var data = value.split('/');
	var dia 		= data[0];
	var barra1		= '/';
	var mes 		= data[1];
	var barra2		= '/';
	var ano 		= data[2];
	if(barra1!="/"||barra2!="/"||isNaN(dia)||isNaN(mes)||isNaN(ano)||dia>31||mes>12)return false;
	if((mes==4||mes==6||mes==9||mes==11)&&dia==31)return false;
	if(mes==2 && (dia>29||(dia==29&&ano!=0)))return false;
	if(ano < 1900 )return false;
	return true;
};

//PROCESSA ENVIO
function envia(tipo) {
	if ((tipo == 1) || (tipo == 11))  {
		if ($("#nome").val().length < 5 ) { $("#nome").focus(); pop('Preencha seu nome corretamente.'); return;	}
		if ($("#email").val().length < 5 ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return;	}
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test($("#email").val()) == false ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return; }
		if ($("#comentarios").val().length < 10 ) { $("#comentarios").focus(); pop('Seu comentário deve conter no mínimo 10 digitos.'); return;	}
		$("#resultado").val('z'); mailer($("#email").val()); $("#enviar").attr("disabled", true); setTimeout("analisa("+tipo+")", 3000);
	}

	if (tipo == 2) {
	   var dom1 = $("#dominio").val();
	   var dom2 = $("#dpn").val();
		if ($("#nome").val().length < 5 ) { $("#nome").focus(); pop('Preencha seu nome corretamente.'); return;	}
		if ($("#dominio").val().length < 1 ) { $("#dominio").focus(); pop('Dominio inválido.'); return;	}
		if ($("#email").val().length < 5 ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return;	}
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test($("#email").val()) == false ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return; }
		$("#resultado").val('z'); $("#domex").val('z');  verificadominio(dom1,dom2);  mailer($("#email").val()); $("#enviar").attr("disabled", true); setTimeout("analisa(2)", 3000);
	}

	if (tipo == 3)  {
		if ($("#nome").val().length < 5 ) { $("#nome").focus(); pop('Preencha seu nome corretamente.'); return;	}
		if ($("#email").val().length < 5 ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return;	}
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test($("#email").val()) == false ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return; }
		if ($("#comentarios").val().length < 10 ) { $("#comentarios").focus(); pop('Seu comentário deve conter no mínimo 10 digitos.'); return;	}
		$("#resultado").val('z'); mailer($("#email").val()); $("#enviar").attr("disabled", true); setTimeout("analisa("+tipo+")", 3000);
	}

	if (tipo == 4)  {
		if ($("#titulo").val().length < 5 ) { $("#titulo").focus(); pop('O título deve conter no mínimo 5 caracteres.'); return;	}
		if ($("#url").val().length < 1 ) { $("#url").focus(); pop('Informe o endereço do site/blog corretamente.'); return;	}
		if ($("#email").val().length < 5 ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return;	}
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test($("#email").val()) == false ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return; }
		$("#resultado").val('z'); mailer($("#email").val()); $("#enviar").attr("disabled", true); setTimeout("analisa("+tipo+")", 3000);
	}

	if (tipo == 5)  {

		var day = $("#dia").val();
		var month = $("#mes").val();
		var year = $("#ano").val();
		var data = day+'/'+month+'/'+year;
		if ($("#email").val().length < 5 ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return;	}
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test($("#email").val()) == false ) { $("#email").focus(); pop('Preencha seu email corretamente.'); return; }
		if ($("#senha").val().length < 5 ) { $("#senha").focus(); pop('A senha deve conter no mínimo 5 caracteres.'); return;	}
		if (data_valida(data) == false) {$("#dia").focus(); pop('Informe uma data válida.'); return;	}
		$("#resultado").val('z'); mailer($("#email").val()); $("#enviar").attr("disabled", true); setTimeout("analisa("+tipo+")", 3000);
	}

	if (tipo == 6)  {
		if ($("#nome_amigo1").val().length < 5 ) { $("#nome_amigo1").focus(); pop('Ei ! Seu nome deve ter no mínimo 5 letras.'); return;	}
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test($("#email_amigo1").val()) == false ) { $("#email_amigo1").focus(); pop('Preencha seu email corretamente.'); return; }
		if ($("#nome_amigo2").val().length < 5 ) { $("#nome_amigo2").focus(); pop('O nome de seu amigo punheteiro deve ter no mínimo 5 letras.'); return;	}
		if (regmail.test($("#email_amigo2").val()) == false ) { $("#email_amigo2").focus(); pop('O email dele deve ser preenchido corretamente.'); return; }
		$("#resultado").val('z');  $("#resultado1").val('z');  mailer($("#email_amigo1").val() +'|'+ $("#email_amigo2").val()); $("#enviar").attr("disabled", true); setTimeout("analisa("+tipo+")", 5000);
	}

}

function analisa(x) {
	if ($("#resultado").val() == 'z') {
		alert('O servidor demorou muito para responder. Tente novamente.');
		$("#enviar").attr("disabled", '');
		return;
	} else {

		if (x == '6') {

			if ($("#resultado").val() != 1) {
					pop('Seu email é inválido.');
					$("#email_amigo1").focus();
					$("#enviar").attr("disabled", '');
					return false;
			} 

			if ($("#resultado1").val() != 1) {
					pop('O email do seu amigo é inválido.');
					$("#email_amigo2").focus();
					$("#enviar").attr("disabled", '');
					return false;
			}

			$.post("envia.php?amigo", { nome_amigo1: $('#nome_amigo1').val(), email_amigo1: $('#email_amigo1').val(), nome_amigo2: $('#nome_amigo2').val(), email_amigo2: $('#email_amigo2').val(), comentarios:$('#comentarios').val()  },
					function(data){
						if (data == '0') {
							$("#enviar").attr("disabled", '');
							$("#nome_amigo1").focus(); pop('Falha no registro.'); 
							return false;
						} 

						if (trim(data) == 'JC') {
							$("#enviar").attr("disabled", '');
							$("#nome_amigo2").focus(); pop('Você já enviou uma revista para este amigo. Conhece outro punheteiro ?'); 
							return false;
						} 

						$("#contato").replaceWith(data);
						
					}
			);
			





		} else {
			if ($("#resultado").val() == '0') {
					pop('Email inválido.');
					$("#email").focus();
					$("#enviar").attr("disabled", '');
			} else {
				//enviar, tudo ok....
				if (x == 1) {
					$.post("envia.php?contato", { nome: $('#nome').val(), email: $('#email').val(), comentarios:$('#comentarios').val() },
							function(data){
								$("#contato").replaceWith(data);
							}
					);
				}
	
				if (x == 11) {
					$.post("envia.php?cota", { nome: $('#nome').val(), email: $('#email').val(), comentarios:$('#comentarios').val() },
							function(data){
								$("#contato").replaceWith(data);
							}
					);
				}
	
				if (x == 2) {
	
					//DOMEX JA VEIO ?
					if ($("#domex").val() == 'z') {
						alert('O servidor demorou muito para responder. Tente novamente.');
						$("#enviar").attr("disabled", '');
						return;
					}

					$.post("envia.php?registro", { nome: $('#nome').val(), dominio: $('#dominio').val()+'.'+$("#dpn").val(), email: $('#email').val(), comentarios:$('#comentarios').val(), cep: $('#cep').val(), rua: $('#rua').val(), bairro: $('#bairro').val(), complemento: $('#complemento').val(), cidade: $('#cidade').val(), estado: $('#estado').val() },
							function(data){
								$("#registro").replaceWith(data);
							}
					);
				}
	
				if (x == 3) {
					$.post("envia.php?comentario", { nome: $('#nome').val(), email: $('#email').val(), comentarios:$('#comentarios').val(), id_post:$("#comenta").attr('rel')  },
							function(data){
								$("#contato").replaceWith(data);
							}
					);
				}

				if (x == 4) {
					$.post("envia.php?parceiro", { titulo: $('#titulo').val(), url: $('#url').val(), descritiva: $('#descritiva').val(), email: $('#email').val(), comentarios:$('#comentarios').val()  },
							function(data){
								$("#contato").replaceWith(data);
							}
					);
				}

				if (x == 5) {
					$.post("envia.php?novaconta", { email: $('#email').val(), senhax: $('#senha').val(), dia: $('#dia').val(), mes: $('#mes').val(), ano:$('#ano').val()  },
							function(data){
								if (data == '0') {
									$("#enviar").attr("disabled", '');
									$("#email").focus(); pop('Falha no registro.'); 
								} else {
									$("#contato").replaceWith(data);
								}
							
							}
					);
				}

			}
		}
	}
	
}


// email
function pop(msg) {
		$("#alert").html(msg);
		$(function () {
			var $alert = $('#alert');
			if($alert.length)
			{
				var alerttimer = window.setTimeout(function () { $alert.trigger('click'); }, 3000);
				$alert.animate({height: $alert.css('line-height') || '50px'}, 200).click(
					function () {
						window.clearTimeout(alerttimer);
						$alert.animate({height: '0'}, 200);
					});
			}
		});

	return false;
}


//// VERIFICA EMAIL
function mailer(x){
	var cte = x.split('|');
	if (x.split('|').length == 1) {
	    $.post("tools.php?em="+$.base64Encode(x), {}, function(data){$("#resultado").val(data);} );
	} else {
		$.post("tools.php?em="+$.base64Encode(cte[0]), {}, function(data){$("#resultado").val(data);} );
		$.post("tools.php?em="+$.base64Encode(cte[1]), {}, function(data){$("#resultado1").val(data);} );
	}

}

function ufs(posix)
{
	var baseuf = 'Selecione o estado|N.D||ACRE|AC||ALAGOAS|AL||AMAPÁ|AP||AMAZONAS|AM||BAHIA|BA||CEARÁ|CE||DISTRITO FEDERAL|DF||ESPÍRITO SANTO|ES||GOIÁS|GO||MARANHÃO|MA||MATO GROSSO|MT||MATO GROSSO DO SUL|MS||MINAS GERAIS|MG||PARÁ|PA||PARAÍBA|PB||PARANÁ|PR||PERNAMBUCO|PE||PIAUÍ|PI||RIO DE JANEIRO|RJ||RIO GRANDE DO NORTE|RN||RIO GRANDE DO SUL|RS||RONDÔNIA|RO||RORAIMA|RR||SANTA CATARINA|SC||SÃO PAULO|SP||SERGIPE|SE||TOCANTINS|TO';
	var baseufa = baseuf.split('||');
	var ufs = '';
	for (var i = 0; i < baseufa.length; i++) {
		var baseuf_1 = baseufa[i].split('|');
		ufs += '<option value="'+baseuf_1[1]+'">'+baseuf_1[0]+'</option>';
	}
	$('select#'+posix).html(ufs);
}

function verificacep(cp,op) {
		$.post("tools.php?cp="+$.base64Encode(cp), { },
			function(data){
				var base = data.split('||');
					$("#rua, #bairro, #cidade, #estado").each( function () {

						//CARIMBA RUA
						if ($(this).attr("ID") == 'rua')  {
							if (base[0] != '**') {$(this).val(base[0]);}
						}

						//CARIMBA BAIRRO
						if ($(this).attr("ID") == 'bairro')  {
							if (base[1] != '**') {$(this).val(base[1]);}
						}

						//CARIMBA CIDADE
						if ($(this).attr("ID") == 'cidade')  {
							if (base[2] != '**') {$(this).val(base[2]);} else { pop('Verifique o cep informado'); $("#cep").focus(); }
						} 

						//CARIMBA ESTADO
						if ($(this).attr("ID") == 'estado')  {
							if (base[3] != '**') {$(this).val(base[3]);}
						}

					});
				
			} 
		);
}

function verificadominio(d,m) {
		if (d == '') {
			return;
		}
		$.post("tools.php?dm="+$.base64Encode(d+'.'+m), { },
			function(data){
				$("#domex").val(data);
//				alert($("#domex").val());
				if (data != '2') {
					pop('['+d+'.'+m+'] Dominio inválido e/ou já registrado');
					$("#dominio").val("");
					$("#dominio").focus();
					return;
				}
				
			} 
		);
}

function abre(x) {
	$('#parte1').css({'display' : 'none'});
	$('#parte2').css({'display' : 'none'});
	$('#'+x).css({'display' : 'block'});
}


// AJUSTA ROTAÇÃO DO CYCLE
$(document).ready(function(){
		$('#s1').cycle({ 
			    fx:      	'scrollBothWays',
				prev:   	'#prev1',
				next: 		'#next1',
			    speed:  	1000,
			    timeout: 	0,
				pause:   	1,
				easeIn:     'easeOutBack',
				easeOut:    'easeOutBack',
			    cleartype:  true,
			    cleartypeNoBg:  true
		});
});

$.fn.cycle.transitions.scrollBothWays = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push($.fn.cycle.commonReset);
	opts.fxFn = function(curr, next, opts, cb, fwd) {
		var w = $cont.width();
		opts.cssFirst = { left: 0 };
		opts.animIn	  = { left: 0 };
		if(fwd){
			opts.cssBefore= { left: w, top: 0 };
			opts.animOut  = { left: 0-w };
		}else{
			opts.cssBefore= { left: -w, top: 0 };
			opts.animOut  = { left: w };
		};
		var $l = $(curr), $n = $(next);
		var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animOut = opts.animOut, animIn = opts.animIn;
		$n.css(opts.cssBefore);
		var fn = function() {$n.show();$n.animate(animIn, speedIn, easeIn, cb);};
		$l.animate(animOut, speedOut, easeOut, function() {
			if (opts.cssAfter) $l.css(opts.cssAfter);
			if (!opts.sync) fn();
		});
		if (opts.sync) fn();
	};
};

//SHARE
function favorita(){
    var url      = parent.location.href;
    var title    = parent.frames.document.title;
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

//JUMP
function jump(code) {
	var w=$(code).attr("width");
	var h=$(code).attr("height");
 	var router = 'vpict.php?im='+$(code).attr("longdesc");
	hs.preserveContent = false;
	hs.expandDuration = 0;
	hs.dimmingDuration = 0;
	hs.restoreDuration = 100;
	hs.fadeInOut = true;
	hs.transitionDuration = 10;
	hs.htmlExpand(code, {
		src: router,
		transitions : ["fade"],
		headingText: '',
		objectType : 'iframe',
		outlineType: '',
		width: 600,
		height: 600,
		wrapperClassName: 'noheader no-footer simples',
		align: 'center',
		dimmingOpacity: 0.5	
	});
}

//montaplayer
function plvd(idbox, idmidia) {
    swfobject.embedSWF("player_video.swf", idbox, "600", "375", "9.0.0", "#FFFFFF", {file:"media2.php?idm="+idmidia, type:"flv", skin:"overlay.swf", controlbar:"over", stretching:"fill", autostart:"false", image:"./galeria/"+idmidia+"C.jpg", screencolor:"FFFFFF"}, {menu:"false", allowfullscreen:"true", wmode: "transparent", quality:"high" } );
}

function red() {
	window.location = "./";
}

function remover(id) {
			$.post("remover.php", { id: id },
					function(data){
						if (data == '0') {
							pop('Falha na solicitação'); 
							return false;
						} 

						if (trim(data) == '1') {
							pop('Seu email foi removido corretamente.'); 
							window.setTimeout(function () { red() }, 1000);
							return false;
						} 
						
					}
			);
}


//verifica search
function verisearch() {
	if ($('#achar').val().length != 0) {
		document.forms['forbusca'].submit();
	} else {
		$("#achar").focus();
		pop('Você deve informar o que deseja pesquisar...');
	}
	//
	return false;
}

//hide show
function hid(id,sn){
	$('#'+id).css({'display' : sn});
}

function vote(x) {
	alert('aaa');
}