/**
 * Funções Principais do Site
 * Arquivo compactado, devido a alterações feitos nele, perdeu - se sincronização com o source.
 * LEMBRAR SEMPRE DE FAZER ALTERACOES NO SOURCE PARA EM SEGUIDA COMPILA E PASSAR P/ OUTRO ARQUIVO.
 * Infelizmente mudanças terão que ser feitas aqui.
 * @date 19 / 05 / 2008
 *
 */

function printr (_var) {
	var out = '';
	for (var i in _var)
		out += _var [i];
	alert (out);
}

var _HTTP_PATH_ = "http://" + document.domain + "/";

switch (document.domain) {
	case '192.168.0.200' :
		_HTTP_PATH_ += "dev/trainerassessoria/";
		break;
	case 'www.magicwebdesign.com.br' :
		_HTTP_PATH_ += "dev/trainer/novo/";
		break;
}

var Trainer = {
	init : function(){
		Trainer.botaoOver();
		$(':text,:password,select,textarea').focus(function() {
			$(this).addClass('campo_form_over');
		}
		).blur(function(){
			$(this).removeClass('campo_form_over')
		}
		);
		with(window.location){
			if(pathname.match(/\b(calculos|matricule-se|fale\-conosco|meus-treinos)\b/g))
				Utils.loadScript('lib/jquery/jquery.blockUI.js');
			if(pathname.match(/\bcalculos\b/g))
				Trainer.Calculos.mascaraCampos();
			else if(pathname.match(/\bmatricule-se\b/g))
				Trainer.Matricula.mascaraCampos();
			else if(pathname.match(/\bgaleria-de-fotos\b/g))
				Trainer.Galeria.initGaleria();
			else if(pathname.match(/\bfale\-conosco\b/g))
				Trainer.Contato.mascaraCampos();
			else if(pathname.match(/\bmeus-treinos\b/g))
				Trainer.Treinos.initTreinos();
			if(pathname.match(/(\bmeus-treinos\/meus-dados\/editar\b|\bmeus-treinos\/classificados(\/|)\b|\bmeus-treinos\/feedback-dos-treinos\b)/g))
				Trainer.Treinos.mascaraCampos();
		}
	}
	, flash : function(element, nome){
		nome = nome || "home";
		var src, width, height;
		switch(nome){
			case'menu' :
			src = 'interna.swf';
			width = 266;
			height = 599;
			break;
			default :
			src = "inicial.swf";
			width = 971;
			height = 560;
			break;
		}
		$(element).flash({
			src : _HTTP_PATH_ + "swf/" + src, width : width, height : height, menu : false, quality : 'high', wmode : 'transparent'
		}
		,{
			expressInstall : true
		}
		);
	}
	, botaoOver : function(){
		$('a.botao img, input[type="image"].botao').hover(function(){
			this.src = this.src.replace(/img\/([^.]*).(jpg|gif)/g, 'img/$1-over.$2');
		}
		, function(){
			this.src = this.src.replace(/-over/g, '');
		}
		);
	}
	, Calculos :{
		mascaraCampos : function(){
			if($.mask){
				$.mask.addPlaceholder('h', "[0-2]");
				$.mask.addPlaceholder('r', "[0-9]");
				$.mask.addPlaceholder('m', "[0-5]");
				$.mask.addPlaceholder('s', "[0-9]");
				$('input#calc_prev_tempo_atual, input#calc_rit_tempo').mask('hr:ms:ms');
				$('input#calc_tempo_ritmo, input#calc_vel_tempo').mask('ms:ms');
				FormU.Validate.onlyBrazilFloat('input#calc_prev_dist_atual, input#calc_prev_dist_prev, input#calc_rit_dist, input#calc_tempo_dist');
			}
		}
		, addResultado : function(element, spanElement, out){
			$('form').removeClass('form_calc_result').filter(element).addClass('form_calc_result').find('span#' + spanElement).html(out);
		}
		, calculaPrevisao : function(){
			var out = "Dados inválidos, tente novamente.";
			$.ajax({
				type : 'post', url : $('form#formcalculeTempoPrevisto').attr('action') + "/ajaxJSON", cache : false, data : $('form#formcalculeTempoPrevisto').serialize(), dataType : 'json', beforeSend : function(){
					Utils.bloquearElemento('form#formcalculeTempoPrevisto', "<strong>Calculando...</strong>");
				}
				, success : function(data, textStatus){
					Utils.bloquearElemento('form#formcalculeRitmoDistanciaTempo'); if((typeof data == 'object')){
						if(data.tempo_previsto && data.tempo_previsto.hora)out = data.tempo_previsto.hora + "h " + data.tempo_previsto.minuto + "min " + data.tempo_previsto.segundo + "s";
						Trainer.Calculos.addResultado('#formcalculeTempoPrevisto', 'tempo_previsto', out);
					}
					else
					$('form#formcalculeTempoPrevisto').submit();
				}
				, error : function(){
					Utils.bloquearElemento('form#formcalculeRitmoDistanciaTempo'); Trainer.Calculos.addResultado('#formcalculeTempoPrevisto', 'tempo_previsto', "Erro ao efetuar o cálculo, tente novamente.");
				}
			}
			);
			Utils.bloquearElemento('form#formcalculeTempoPrevisto'); return false;
		}
		, calculaRimtoDistanciaTempo : function(){
			var out = "Dados inválidos, tente novamente.";
			$.ajax({
				type : 'post', url : $('form#formcalculeRitmoDistanciaTempo').attr('action') + "/ajaxJSON", cache : false, data : $('form#formcalculeRitmoDistanciaTempo').serialize(), dataType : 'json', beforeSend : function(){
					Utils.bloquearElemento('form#formcalculeRitmoDistanciaTempo', "<strong>Calculando...</strong>");
				}
				, success : function(data, textStatus){
					Utils.bloquearElemento('form#formcalculeRitmoDistanciaTempo'); if((typeof data == 'object')){
						if(data.ritmo_tempo && data.ritmo_tempo.minuto)out = data.ritmo_tempo.minuto + ":" + data.ritmo_tempo.segundo + " min/Km";
						Trainer.Calculos.addResultado('#formcalculeRitmoDistanciaTempo', 'ritmo_dist_tempo', out);
					}
					else
					$('form#formcalculeRitmoDistanciaTempo').submit();
				}
				, error : function(){
					Utils.bloquearElemento('form#formcalculeRitmoDistanciaTempo'); Trainer.Calculos.addResultado('#formcalculeRitmoDistanciaTempo', 'ritmo_dist_tempo', "Erro ao efetuar o cálculo, tente novamente.");
				}
			}
			);
			return false;
		}
		, calculaTempoRitmo : function(){
			var out = "Dados inválidos, tente novamente.";
			$.ajax({
				type : 'post', url : $('form#formcalculeTempoRitmo').attr('action') + "/ajaxJSON", cache : false, data : $('form#formcalculeTempoRitmo').serialize(), dataType : 'json', beforeSend : function(){
					Utils.bloquearElemento('form#formcalculeTempoRitmo', "<strong>Calculando...</strong>");
				}
				, success : function(data, textStatus){
					Utils.bloquearElemento('form#formcalculeTempoRitmo'); if((typeof data == 'object')){
						if(data.tempo_ritmo && data.tempo_ritmo.hora)out = data.tempo_ritmo.hora + "h " + data.tempo_ritmo.minuto + "min " + data.tempo_ritmo.segundo + "s";
						Trainer.Calculos.addResultado('#formcalculeTempoRitmo', 'tempo_rit_tempo', out);
					}
					else
					$('form#formcalculeTempoRitmo').submit();
				}
				, error : function(){
					Trainer.Calculos.addResultado('#formcalculeRitmoDistanciaTempo', 'tempo_rit_tempo', "Erro ao efetuar o cálculo, tente novamente.");
				}
			}
			);
			return false;
		}
		, calculaVelocidade : function(){
			var out = "Dados inválidos, tente novamente.";
			$.ajax({
				type : 'post', url : $('form#formcalculeVelocidade').attr('action') + "/ajaxJSON", cache : false, data : $('form#formcalculeVelocidade').serialize(), dataType : 'json', beforeSend : function(){
					Utils.bloquearElemento('form#formcalculeVelocidade', "<strong>Calculando...</strong>");
				}
				, success : function(data, textStatus){
					Utils.bloquearElemento('form#formcalculeVelocidade'); if((typeof data == 'object')){
						if(data.velocidade)out = data.velocidade + " Km/h";
						Trainer.Calculos.addResultado('#formcalculeVelocidade', 'velocidade', out);
					}
					else
					$('form#formcalculeTempoRitmo').submit();
				}
				, error : function(){
					Utils.bloquearElemento('form#formcalculeTempoRitmo'); Trainer.Calculos.addResultado('#formcalculeVelocidade', 'velocidade', "Erro ao efetuar o cálculo, tente novamente.");
				}
			}
			);
			return false;
		}
	}
	, Matricula :{
		mascaraCampos : function(){
			$('input#cep').mask('99999-999');
			FormU.Validate.onlyNumbers('input#cpf, input#rg');
			$('input#fone, input#fone2').mask('(99) 9999-9999');
			$('input#data_nascimento').mask('99/99/9999');
			$('input#contrato').click(function(){
				if(this.checked){
					$('input#enviar_botao').addClass('botao').attr({
						src : _HTTP_PATH_ + "img/bt_enviar.jpg", disabled : false
					}
					);
					Trainer.botaoOver();
				}
				else{
					$('input#enviar_botao').removeClass('botao').attr({
						src : _HTTP_PATH_ + "img/bt_enviar_disabled.jpg", disabled : true
					}
					);
				}
			}
			);
			if( ! $('input#contrato').attr('checked'))$('input#enviar_botao').attr({
				src : _HTTP_PATH_ + 'img/bt_enviar_disabled.jpg', disabled : true
			}
			);
			$('select#uf').change(function(){
				if(this.selectedIndex != 0)Trainer.Matricula.listaCidadesUF(this.value, $('select#cidade').val());
			}
			).change();
		}
		, listaCidadesUF : function(uf, cidade){
			uf = uf || "PR";
			cidade = cidade || 0;
			$('select#cidade').html('<option value="0">Carregando Cidades...</option>');
			$.ajax({
				type : 'get', url : _HTTP_PATH_ + "matricule-se/lista-cidades/" + uf + "/ajaxJSON", dataType : 'json', success : function(data, textStatus){
					if(data.cidades){
						$('select#cidade option').remove();
						$.each(data.cidades, function(k, val){
							$('select#cidade').append('<option value="'+val.cidad_id+'" ' + (val.cidad_id == cidade ? 'selected="selected"' : '') + '>' + val.cidad_nome + '</option>');
						}
						);
					}
					else
					alert("Não foi possível efetuar a requisição.\nPor favor tente mais tarde.");
				}
				, error : function(){
					alert("Não foi possível efetuar a requisição.\nPor favor tente mais tarde.");
				}
			}
			);
			return false;
		}
		, enviar : function(form){
			form = $(form); if(form.find('input#contrato').attr('checked')){
				$.ajax({
					type : 'post', url : form.attr('action') + "/ajaxJSON", cache : false, data : form.serialize(), dataType : 'json', beforeSend : function(){
						$('div#errors').hide().empty();
						$.blockUI({
							message : "Processando Matrícula...", css :{
								font : 'bold 160% sans-serif'
							}
						}
						);
					}
					, success : function(data, textStatus){
						$.unblockUI();
						if(data.errors){
							$('div#errors').append("<strong>Erro(s) encontrado(s):</strong>").append(Utils.arrayToUl(data.errors)).show();
							Utils.redireciona('#errors');
						}
						else if(data.sucesso)form.submit();
					}
					, error : function(){
						form.submit();
					}
				}
				);
			}
			else
			alert("Você precisa marcar a Opção que concorda com o contrato da Matrícula");
			return false;
		}
	}
	, Galeria :{
		initGaleria : function(){
			$('div.esquerda_galeria div.agrupa_tbs div.fotos a').click(function(){
				return Trainer.Galeria.trocaImagem(this);
			});
		}
		, trocaImagem : function(element){
			if($('img.foto_galeria').attr('src') != element.href){
				$('img.foto_galeria').fadeOut('slow', function(){
					var oSrc = this.src;
					$(document.createElement('img')).load(function(){
						$('img.foto_galeria').attr({
							src : this.src, oSrc : oSrc, alt : this.src
						}
						).fadeIn('slow');
					}
					).attr('src', element.href);
				}
				);
			}
			return false;
		}
		, carregar : function(galeria){
			if($('span.hide').html() != galeria){
				$.ajax({
					type : 'get', url : _HTTP_PATH_ + "galeria-de-fotos/ver/" + galeria + "/ajaxJSON", cache : false, dataType : 'json', beforeSend : function(){
					}
					, success : function(data, textStatus){
						if(data.galeria){
							$('div.agrupa_tbs').fadeOut('slow', function(){
								$('h3.titulo_galeria').html(data._load.galer_titulo);
								$('p.desc_galeria').html(data._load.galer_descricao);
								$('div.agrupa_tbs div.fotos a').remove();
								$('div.agrupa_tbs div.fotos input').remove();

						 $('div.agrupa_tbs div.fotos').append('<input type="hidden" id="curr_foto" value="1" />');
						 //$('div.agrupa_tbs div.fotos').append('<input type="hidden" id="total_pag" value="'+data.galeria._galer_imagens.paginacao.total+'" />');
						 document.getElementById('total_pag').value = data.galeria._galer_imagens.paginacao.total;
						 
						$.each(data.galeria._galer_imagens.imagens, function(k, img){
							$('div.agrupa_tbs div.fotos').append('<input type="hidden" id="foto_'+(k+1)+'" value="'+img._img_path+'" />');
							$('div.agrupa_tbs div.fotos').append('<a href="'+img._img_path+'" title="Imagem '+(k+1)+'" target="_blank">' + '<img src="'+img._img_thumb_path+'" alt="Imagem '+(k+1)+'" class="foto_galeria_menor" /></a>');
								}
								);
								Trainer.Galeria.initGaleria();

								if(data.galeria._galer_imagens.paginacao.total == 1)$('div.paginacao_fotos').hide();
								else{
									$('div.paginacao_fotos').show().find('span:eq(1)').html(data.galeria._galer_imagens.paginacao.total).prev().html('1');
									Trainer.Galeria.trocaPaginacao(false, 2);
								}
								Trainer.Galeria.trocaImagem($('div.agrupa_tbs div.fotos a:eq(0)').get(0));
								$('span#url_galeria').html(data.galeria._galer_titulo_url);
							}
							).fadeIn('slow');
						}
						else
						alert("Ocorreu um erro ao carregar a galeria solicitada.\nCaso o erro persista, contate nosso suporte técnico.");
					}
					, error : function(){
						alert("Ocorreu um erro ao carregar a galeria solicitada.\nCaso o erro persista, contate nosso suporte técnico.");
					}
				}
				);
			}
			return false;
		}
		, paginacaoImagens : function(proxima_pg){
			proxima_pg = proxima_pg || false;
			var pag   = parseInt($('div.paginacao_fotos span:eq(0)').html(), 10) || 1,
				total = parseInt($('div.paginacao_fotos span:eq(1)').html(), 10) || 1,
				cond_paginacao = proxima_pg ? (pag <= total) : (pag > 1);

			if(cond_paginacao){
				$.ajax({
					type : 'get', url : _HTTP_PATH_ + "galeria-de-fotos/ver/" + $('span#url_galeria').html() + "/" + (pag + (proxima_pg ? 1 : - 1)) + "/ajaxJSON", cache : false, dataType : 'json', beforeSend : function(){
					}
					, success : function(data, textStatus){
						if(data.galeria){
							$('div.agrupa_tbs').fadeOut('slow', function(){
								$('div.agrupa_tbs div.fotos a').remove();
								$('div.agrupa_tbs div.fotos input').remove();

						 $('div.agrupa_tbs div.fotos').append('<input type="hidden" id="curr_foto" value="1" />');
								$.each(data.galeria._galer_imagens.imagens, function(k, img){
							$('div.agrupa_tbs div.fotos').append('<input type="hidden" id="foto_'+(k+1)+'" value="'+img._img_path+'" />');
									$('div.agrupa_tbs div.fotos').append('<a href="'+img._img_path+'" title="Imagem '+(k+1)+'" target="_blank">' + '<img src="'+img._img_thumb_path+'" alt="Imagem '+(k+1)+'" class="foto_galeria_menor" /></a>');
								}
								);
								with(Trainer.Galeria){
									initGaleria();
									trocaPaginacao(proxima_pg, pag);
									trocaImagem($('div.agrupa_tbs div.fotos a:eq(0)').get(0));
								}
								$('span#url_galeria').html(data.galeria._galer_titulo_url);
							}
							).fadeIn('slow');
						}
						else
						alert("Ocorreu um erro ao carregar a galeria solicitada.\nCaso o erro persista, contate nosso suporte técnico.");
					}
					, error : function(){
						alert("Ocorreu um erro ao carregar a página solicitada.\nCaso o erro persista, contate nosso suporte técnico.");
					}
				}
				);
			}
		}
		, trocaPaginacao : function(proxima_pg, pag){
			pag = pag || 1;
		 $('div.paginacao_fotos a#imgs_prox').hide();
			$('div.paginacao_fotos a#imgs_ant').hide();

		 if (proxima_pg) {
				$('div.paginacao_fotos a#imgs_ant').show();
			 if (pag + 1 < document.getElementById('total_pag').value)
				 $('div.paginacao_fotos a#imgs_prox').show();
		 } else {
			$('div.paginacao_fotos a#imgs_prox').show();
			 if (pag > 2)
				  $('div.paginacao_fotos a#imgs_ant').show();
		  }
			$('div.paginacao_fotos').show().find('span:eq(0)').html(proxima_pg ? pag + 1 : pag - 1);
		}
	}
	, Contato :{
		mascaraCampos : function(){
			$('input#fone').mask('(99) 9999-9999');
		}
		, enviar : function(form){
			form = $(form); $.ajax({
				type : 'post', url : form.attr('action') + "/ajaxJSON", cache : false, data : form.serialize(), dataType : 'json', beforeSend : function(){
					$('div#errors').hide().empty();
					$.blockUI({
						message : "Enviando Formulário de Contato...", css :{
							font : 'bold 160% sans-serif'
						}
					}
					);
				}
				, success : function(data, textStatus){
					$.unblockUI();
					if(data.errors){
						$('div#errors').append("<strong>Erro(s) encontrado(s):</strong>").append(Utils.arrayToUl(data.errors)).show();
						Utils.redireciona('#errors');
					}
					else if(data.sucesso)form.submit();
				}
				, error : function(){
					form.submit();
				}
			}
			);
			return false;
		}
	}
	, Treinos :{
		initTreinos : function(){
			$('select#ano_treino, select#mes_treino').change(Trainer.Treinos.listaSemanas);
			if($('select#dias_treino').size() == 1){
				$('select#semana_treino').change(Trainer.Treinos.listaDiasSemana);
				$('select#semana_treino').change(Trainer.Treinos.listaFeedbacksSemana);
				$('select#dias_treino').change(Trainer.Treinos.listaTreinoDia);
				$('select#semana_treino').change();
				$('select#dias_treino').change();
				Trainer.Treinos.listaFeedbacksSemana();
			}
		}
		, mascaraCampos : function(){
			$('input#cep').mask('99999-999');

			$('input#fone1, input#fone2').mask('(99) 9999-9999');
			$('input#data_nascimento').mask('99/99/9999');
			$('select#uf').change(function(){
				if(this.selectedIndex != 0)Trainer.Treinos.listaCidadesUF(this.value, $('select#cidade').val());
			}
			);
			$.mask.addPlaceholder('h', "[0-2]");
			$.mask.addPlaceholder('r', "[0-9]");
			$.mask.addPlaceholder('m', "[0-5]");
			$.mask.addPlaceholder('s', "[0-9]");
			$('input#tempo').mask('hr:ms:ms');
			$('input#distancia');
			FormU.Validate.onlyNumbers('input#rg, input#distancia');
		}
		, listaCidadesUF : function(uf, cidade){
			uf = uf || "PR";
			cidade = cidade || 0;
			$('select#cidade').html('<option value="0">Carregando Cidades...</option>');
			$.ajax({
				type : 'get', url : _HTTP_PATH_ + "meus-treinos/lista-cidades/" + uf + "/ajaxJSON", dataType : 'json', success : function(data, textStatus){
					if(data.cidades){
						$('select#cidade option').remove();
						$.each(data.cidades, function(k, val){
							$('select#cidade').append('<option value="'+val.cidad_id+'" ' + (val.cidad_id == cidade ? 'selected="selected"' : '') + '>' + val.cidad_nome + '</option>');
						}
						);
					}
					else
					alert("Não foi possível efetuar a requisição.\nPor favor tente mais tarde.");
				}
				, error : function(){
					alert("Não foi possível efetuar a requisição.\nPor favor tente mais tarde.");
				}
			}
			);
			return false;
		}
		, listaSemanas : function(){
			$.ajax({
				type : 'post', url : _HTTP_PATH_ + "meus-treinos/listar-semanas/ajaxJSON", cache : false, data : "mes=" + $('select#mes_treino').val() + "&ano=" + $('select#ano_treino').val(), dataType : 'json', beforeSend : function(){
					//Utils.bloquearElemento('form#formTreinoData', "Carregando Semanas...");
				}
				, success : function(data, textStatus){
					//Utils.bloquearElemento('form#formTreinoData');
				if(data.semanas){
						$('select#semana_treino').empty();
						$.each(data.semanas, function(k, s){
							$('select#semana_treino').append('<option value="'+k+'">' + s + '</option>');
						}
						);
						$('select#semana_treino').change();
						//$('select#dias_treino').change();
					}
					else
					alert("Ocorreu um erro interno ao efetuar a busca das semanas.\nSe o erro persistir, entre em contato.");
				}
				, error : function(){
					alert("Erro ao obter os dados da operação.\nSe o erro persistir, entre em contato.");
					Utils.bloquearElemento('form#formTreinoData');
				}
			}
			);
		}
		, listaDiasSemana : function(){
			$.ajax({
				type : 'post', url : _HTTP_PATH_ + "meus-treinos/listar-dias-semana/ajaxJSON", cache : false, data : "semana=" + $('select#semana_treino').val() + "&mes=" + $('select#mes_treino').val() + "&ano=" + $('select#ano_treino').val(), dataType : 'json', beforeSend : function(){
				Utils.bloquearElemento('form#formFeedbackTreino');
				Utils.bloquearElemento('form#formTreinoData');
				Utils.bloquearElemento('form#formTreinoData', "Carregando Dias da Semana...");
				}
				, success : function(data, textStatus){
					if(data.dias){
						$('select#dias_treino').empty();
						$.each(data.dias, function(k, s){
							$('select#dias_treino').append('<option value="'+k+'">' + s + '</option>');
						}
						);
						$('select#dias_treino').change();
					}
					else
					alert("Ocorreu um erro interno ao efetuar a busca das semanas.\nSe o erro persistir, entre em contato.");
				}
				, error : function(){
					alert("Erro ao obter os dados da operação.\nSe o erro persistir, entre em contato.");
					Utils.bloquearElemento('form#formTreinoData');
				}
			}
			);
		}
		, listaFeedbacksSemana : function(){
			$.ajax({
				type : 'post', url : _HTTP_PATH_ + "meus-treinos/listar-feedbacks-semana/ajaxJSON", cache : false, data : "semana=" + $('select#semana_treino').val(), dataType : 'json', beforeSend : function(){
					Utils.bloquearElemento('div#divListaFeedbacks', "Carregando Feedbacks da Semana...");
				}
				, success : function(data, textStatus){
					if(data.feedbacks){
						$('div#divListaFeedbacks').empty();
						var _feed;
						$.each(data.feedbacks, function(k, f){
							_feed  = '<div id="feed_' + f.atfee_id + '" class="' + (f.atfee_atleta == 't' ? (f.atfee_alerta == 't' ? 'msg_feed' : 'msg_feed_respondida') : 'msg_feed_tecnico') + '" ';

							if (f.atfee_atleta == 't') {
								_feed += '<p class="linha_feed"><strong>' + f.atrei_data + ' - ' + f.trein_nome + '</strong></p>';
								_feed += '<p class="linha_feed"><strong>Batimento Cardíaco:</strong></p>';
								_feed += '<ul style="clear: both;">';
								_feed += '<li>Bat. Mínimo: ' + (f.atfee_batimento_minimo > 0 ? f.atfee_batimento_minimo : 0) + '</li>';
								_feed += '<li>Bat. Médio: ' + (f.atfee_batimento_medio > 0 ? f.atfee_batimento_medio : 0) + '</li>';
								_feed += '<li>Bat. Máximo: ' + (f.atfee_batimento_maximo > 0 ? f.atfee_batimento_maximo : 0) + '</li>';
								_feed += '<li>Tempo: ' + f.atfee_tempo + '</li>';
								_feed += '<li>Distância: ' + f.atfee_distancia + ' km</li>';
								_feed += '<li>Ritmo: ' + f.atfee_ritmo + ' min/km</li>';
								_feed += '<li>Velocidade: ' + f.atfee_velocidade + ' km/h</li>';
								_feed += '<li>Intensidade: ' + f.atfee_intensidade_nome + '</li>';
								_feed += '</ul>';
							} else {
								_feed += '<p class="linha_feed_tit"><strong>' + f.atfee_datahora_for + ' - ' + f.opera_nome + '</strong></p>';
							}
							_feed += '<p class="linha_feed">';
							_feed += '<strong>Mensagem:</strong><br />';
							_feed += f.atfee_descricao.replace("\n","<br />");
							_feed += '</p>';
							if (f.atfee_arquivo)
								_feed += '<p class="linha_feed"><a href="' + f.atfee_arquivo + '" target="_blank">Baixar Arquivo em anexo</a></p>';
							if (f.atfee_atleta == 't')
								_feed += '<a href="#" onclick="return Trainer.Treinos.excluirFeedback(' + f.atfee_id +');"><img src="../img/bt_excregistro.jpg" alt="Excluir Registro" title="Excluir Registro" width="140" height="23" class="bt_excregistro" /></a>';
							_feed += '</div>';
								$('div#divListaFeedbacks').append(_feed);
							}
							);
							$('select#dias_treino').change();
						}
					else
				{
						$('div#divListaFeedbacks').empty();
				  $('div#divListaFeedbacks').append('<div style="margin: 20px 0;">&nbsp;</div>');
					Utils.bloquearElemento('div#divListaFeedbacks');
					Utils.bloquearElemento('div#divListaFeedbacks', "Não há feedbacks nesta semana.",{
							color : '#FF0000'
						}
						);
				}
				}
				, error : function(){
					alert("Erro ao obter os dados da operação.\nSe o erro persistir, entre em contato.");
					Utils.bloquearElemento('form#formTreinoData');
				}
			}
			);
		}
		, listaTreinoDia : function(){
			var out = "Sem treinamento no dia selecionado.";
			$.ajax({
				type : 'post', url : _HTTP_PATH_ + "meus-treinos/listar-treinamento-dia/ajaxJSON", cache : false, data : "semana=" + $('select#semana_treino').val() + "&dia=" + $('select#dias_treino option:selected').html(), dataType : 'json', beforeSend : function(){
					$('div#errors').removeClass('show').empty();
					Utils.bloquearElemento('form#formFeedbackTreino'); Utils.bloquearElemento('form#formTreinoData', "Carregando Treinamento do dia...");
				}
				, success : function(data, textStatus){
					Utils.bloquearElemento('form#formTreinoData');

					if((data.treino) && (data.treino.nome.length > 0)) {
						out = data.treino.nome;
						$('#atrei_id').val(data.treino.id);
					}
					else {
						Utils.bloquearElemento ('form#formFeedbackTreino', "Não há treino para este dia.", {
							color : '#FF0000'
						}
						);
						$('#atrei_id').val(0);
					}
					$('span#treino').html(out);
				}
				, error : function() {
					alert("Erro ao obter os dados da operação.\nSe o erro persistir, entre em contato.");
					Utils.bloquearElemento('form#formTreinoData');
				}
			}
			);
		}
		, salvarCadastro : function(form){
			form = $(form); $.ajax({
				type : 'post', url : form.attr('action') + "/ajaxJSON", cache : false, data : form.serialize(), dataType : 'json', beforeSend : function(){
					$('div#errors').removeClass('show').empty();
					$.blockUI({
						message : "Salvando Alterações...", css :{
							font : 'bold 160% sans-serif'
						}
					}
					);
				}
				, success : function(data, textStatus){
					$.unblockUI();
					if(data.errors){
						$('div#errors').append("<strong>Erro(s) encontrado(s):</strong>").append(Utils.arrayToUl(data.errors)).addClass('show');
						Utils.redireciona('#errors');
					}
					else if(data.sucesso)form.submit();
				}
				, error : function(){
					form.submit();
				}
			}
			);
			return false;
		}
		, salvarClassificado : function(form){
			form = $(form); $.ajax({
				type : 'post', url : form.attr('action') + "/ajaxJSON", cache : false, data : form.serialize(), dataType : 'json', beforeSend : function(){
					$('div#errors').removeClass('show').empty();
					$.blockUI({
						message : "Gravando Classificado...", css :{
							font : 'bold 160% sans-serif'
						}
					}
					);
				}
				, error : function(data, textStatus){
					$.unblockUI();
					if(data.errors){
						$('div#errors').append("<strong>Erro(s) encontrado(s):</strong>").append(Utils.arrayToUl(data.errors)).addClass('show');
						Utils.redireciona('#errors');
					}
					else if(data.sucesso)form.submit();
				}
				, success : function(){
					form.submit();
				}
			}
			);
			return false;
		}
		, salvarFeedback : function(form){
			document.getElementById ('semana_treino2').value = document.getElementById ('semana_treino').value;
			form = $(form);
			$.ajax({
				type : 'post', url : form.attr('action') + "/ajaxJSON", cache : false, data : form.serialize(), dataType : 'json', beforeSend : function(){
					$('div#errors').removeClass('show').empty();
					$.blockUI({
						message : "Gravando Feedback...", css :{
							font : 'bold 160% sans-serif'
						}
					}
					);
				}
				, success : function(data, textStatus){
					$.unblockUI();
					if(data.errors){
						$('#mensagem_sucesso').hide();
						$('div#errors').append("<strong>Erro(s) encontrado(s):</strong>").append(Utils.arrayToUl(data.errors)).addClass('show');
						Utils.redireciona('#errors');
					}
					else if(data.sucesso)form.submit();
				}
				, error : function(){
					form.submit();
				}
			}
			);
			return false;
		}
		, excluirFeedback : function(atfee_id){
			var cond = confirm("Deseja mesmo apagar seu Feedback?");
			if(cond){
				$.ajax({
					type : 'post', url : _HTTP_PATH_ + "meus-treinos/excluir-feedback/ajaxJSON", cache : false, data : "atfee_id=" + atfee_id, dataType : 'json', beforeSend : function(){
						Utils.bloquearElemento('div#feed_' + atfee_id, "Excluindo feedback...");
					}
					, success : function(data, textStatus){
						Utils.bloquearElemento('div#feed_' + atfee_id);
						if(data.sucesso)$('div#feed_' + atfee_id).remove();
						else
						alert("Não foi possível excluir o Feedback selecionado.\nCaso o erro persista, entre em Contato.");
					}
					, error : function(){
						Utils.bloquearElemento('div#feed_' + atfee_id);
						alert("Não foi possível excluir o Feedback selecionado.\nCaso o erro persista, entre em Contato.");
					}
				}
				);
			}
			return false;
		},
		excluirMinhaFoto: function() {
			if (confirm("Deseja remover a sua foto?")) {
				$.ajax({
					url : _HTTP_PATH_ + "meus-treinos/apagar-foto/ajaxJSON",
					cache : false,
					dataType : 'json',
					beforeSend : function(){
						Utils.bloquearElemento('div#foto_atleta', "Excluindo foto...");
					}
					, success : function(data, textStatus){
						Utils.bloquearElemento('div#foto_atleta');
						if(data.result)
							$('div#container_foto').remove();
						else
							alert("Não foi possível excluir a Foto.\nCaso o erro persista, entre em Contato.");
					}
					, error : function(){
						Utils.bloquearElemento('div#foto_atleta');
						alert("Não foi possível excluir a Foto.\nCaso o erro persista, entre em Contato.");
					}
				});
			}
			return false;
		}
	}
	, Classificados :{
		busca : function(){
			var complemento_action;
			switch($('div#tipo input:checked').val().toUpperCase()){
				case'C' :
				complemento_action = "/compra";
				break;
				case'T' :
				complemento_action = "/troca";
				break;
				case'V' :
				complemento_action = "/venda";
				break;
				case'TODOS' :
				complemento_action = "/todos";
				break;
				default :
				complemento_action = "";
				break;
			}
			$('form#formBuscaClassificados').attr('action', $('form#formBuscaClassificados').attr('action') + complemento_action);
			return true;
		}
		, paginacaoDetalhes : function(categoria, pagina){
			$.ajax({
				type : 'get', url : _HTTP_PATH_ + "classificados/categoria-paginacao/" + categoria + "/" + pagina + "/ajaxJSON", dataType : 'json', success : function(data, textStatus){
					var classi = null
					i = 0;
					if(data.classificados){
						with(data){
							classi = $('dl.noticia_int:lt(' + (classificados.length + 1) + ')');
							for(i = 0; i < classificados.length; i ++ ){
								with(classi.eq(i)){
									find('a').attr('href', _HTTP_PATH_ + "classificados/detalhes/" + classificados[i]._titulo_url + "/" + pagina);
									find('.linha_noticia_int a:eq(0)').html(classificados[i]._class_data);
									find('.linha_noticia_int a:eq(1) strong').html(classificados[i]._class_titulo);
									find('.linha_noticia_int a:eq(2)').html(classificados[i]._class_descricao);
								}
							}
							if(classificados.length == 5)$('dl.noticia_int:hidden').show();
							else
							$('dl.noticia_int:gt(' + (classificados.length - 1) + ')').toggle();
							if(pagina > 1){
								$('div.paginacao a:eq(0)').show().get(0).onclick = function(){
									Trainer.Classificados.paginacaoDetalhes(categoria, parseInt(pagina, 10) - 1);
								}
								;
							}
							else
							$('div.paginacao a:eq(0)').hide();
							if(pagina < paginacao.resultados){
								$('div.paginacao a:eq(1)').show().get(0).onclick = function(){
									Trainer.Classificados.paginacaoDetalhes(categoria, parseInt(pagina, 10) + 1)
								}
								;
							}
							else
							$('div.paginacao a:eq(1)').hide();
							$('p.numeracao_pagina span').html(pagina);
						}
					}
				}
				, error : function(){
				}
			}
			);
			return false;
		},
		 excluirFotoClassificado: function(classi_id) {
			if (confirm("Deseja remover a foto deste classificado?")) {
				$.ajax({
					url : _HTTP_PATH_ + "classificados/apagar-foto/" + classi_id +  "/ajaxJSON",
					cache : false,
					dataType : 'json',
					beforeSend : function(){
						Utils.bloquearElemento('div#foto_upload_classificado', "Excluindo foto...");
					}
					, success : function(data, textStatus){
						Utils.bloquearElemento('div#foto_upload_classificado');
						if(data.result)
							$('div#foto_classificado').remove();
						else
							alert("Não foi possível excluir a Foto.\nCaso o erro persista, entre em Contato.");
					}
					, error : function(){
						Utils.bloquearElemento('div#foto_upload_classificado');
						alert("Não foi possível excluir a Foto.\nCaso o erro persista, entre em Contato.");
					}
				});
			}
			return false;
		}
	}
	, Noticias :{
		paginacaoInterna : function(pagina){
			$.ajax({
				type : 'get', url : _HTTP_PATH_ + "noticias/paginacao-interna/" + pagina + "/ajaxJSON", dataType : 'json', success : function(data, textStatus){
					var not = null
					i = 0;
					if(data.noticias){
						with(data){
							not = $('dl.noticia_int:lt(' + (noticias.length + 1) + ')');
							for(i = 0; i < noticias.length; i ++ ){
								with(not.eq(i)){
									find('a').attr('href', _HTTP_PATH_ + "noticias/ver/" + noticias[i]._notic_titulo_url + "/" + pagina);
									find('.linha_noticia_int a:eq(0)').html(noticias[i]._notic_data_ativacao);
									find('.linha_noticia_int a:eq(1) strong').html(noticias[i]._notic_titulo);
									find('.linha_noticia_int a:eq(2)').html(noticias[i]._notic_descricao);
								}
							}
							if(noticias.length == 5)$('dl.noticia_int:hidden').show();
							else
							$('dl.noticia_int:gt(' + (noticias.length - 1) + ')').toggle();
							if(pagina > 1){
								$('div.paginacao a:eq(0)').show().get(0).onclick = function(){
									Trainer.Noticias.paginacaoInterna(parseInt(pagina, 10) - 1);
								}
								;
							}
							else
							$('div.paginacao a:eq(0)').hide();
							if(pagina < paginacao.resultados){
								$('div.paginacao a:eq(1)').show().get(0).onclick = function(){
									Trainer.Noticias.paginacaoInterna(parseInt(pagina, 10) + 1)
								}
								;
							}
							else
							$('div.paginacao a:eq(1)').hide();
							$('p.numeracao_pagina span').html(pagina);
						}
					}
				}
				, error : function(){
				}
			}
			);
			return false;
		}
	}
}
;
var Utils = {
	loadScript : function(src){
		$('head script:last').after($(document.createElement('script')).attr({
			type : 'text/javascript', src : _HTTP_PATH_ + src
		}
		));
	}
	, loadCSS : function(src, media_css){
		$('head').append($(document.createElement('link')).attr({
			rel : 'stylesheet', type : 'text/css', media : media_css || 'screen,projection', href : _HTTP_PATH_ + src + "?" + parseInt((Math.random() * 10000))
		}
		));
	}
	, bloquearElemento : function(element, mensagem, css_options){
		css_options = css_options ||{
		}
		;
		if($.blockUI){
			if(mensagem){
				$(element).block({
					message : mensagem, css : $.extend({
						border : '2px solid #CCCCCC'
					}
					, css_options)
				}
				);
			}
			else
			$(element).unblock();
		}
	}
	, arrayToUl : function(arr, classe){
		var ul = $(document.createElement('ul'));
		if(classe != "undefined"){
			ul.addClass(classe);
			ul.attr({
				id : classe
			}
			);
		}
		$.each(arr, function(i, data){
			ul.append($(document.createElement('li')).html(data));
		}
		);
		return ul;
	}
	, redireciona : function(url, timeout){
		setTimeout('window.location = "'+url+'";', timeout || 0);
	}
}
;


// 	Extendendo variaveis tipo String
String.prototype.inject = function(begin, newVal) {
	return this.substr(0, begin > 0 ? begin : this.length + begin) + newVal + this.substr(begin);
}
//
String.prototype.getFunctionBody = function() {
	return this.replace(/function[^\{]*\{(.*)\}/ig, '$1');
}
$(document).ready(Trainer.init);
