var agenda = {
	
	mes: 0,
	ano: 0,
	$dias: null,
	
	init: function(){
		this.mesano();
		this.calendario(this.mes, this.ano);
	},

	binder: function(){
		$('#prev_mes').unbind('click').bind('click',this.prev_mes);
		$('#next_mes').unbind('click').bind('click',this.next_mes);
		this.$dias = $('table.calendario a');
		this.$dias.unbind('click').bind('click',this.carregar_horas);
		return false;
	},

	mesano: function(){
		$.post("ajax/agendamento.php", { act: 'mesano' }, function(response){
			agenda.mes = response.mes;
			agenda.ano = response.ano;
		},'json');
	},

	calendario: function(mes,ano){
		$.post("ajax/agendamento.php", { act: 'calendario', mes: mes, ano: ano }, function(response){
			$('.calendariophp').html(response);
			agenda.binder();
		});
		return false;
	},
	
	next_mes: function(){
		agenda.mes++;
		if (agenda.mes > 12) {
			agenda.mes = 1;
			agenda.ano++;
		}
		agenda.calendario(agenda.mes, agenda.ano);
		return false;
	},
	
	prev_mes: function(){
		agenda.mes--;
		if (agenda.mes < 1) {
			agenda.mes = 12;
			agenda.ano--;
		}
		agenda.calendario(agenda.mes, agenda.ano);
		return false;
	},
	
	bind_horas: function(){
		$('ul.horarios li a.indisponivel').bind('click',function(){ return false; });
		$('ul.horarios li a.disponivel').bind('click',this.carregar_form);
	},
	
	bind_form: function(){
		$('input.fone').mask('(99) 9999-9999');
		$('#frmAgenda').bind('submit',function(){
			var dados = $(this).serialize();
			$.post('email/email-servicos.php', { dados: dados }, function(resp){
				switch (parseInt(resp)) {
					case 1:
						alert('Serviço agendado com sucesso.');
						$('#form, #hora').html('');
						agenda.calendario(agenda.mes, agenda.ano);
					break;
					case 2:
						alert('Houve um erro durante o envio da mensagem.');
					break;
					case 3:
						alert('Este horário já está totalmente ocupado.');
					break;
					default:
						alert(resp);
					break;
				}
			});
			return false;
		});
	},
	
	trata_erros: function(erros){
		if (erros.length > 1) {
			var erro = 'Os seguintes erros foram encontrados:\n\n';
			for (var i = 0; i < erros.length; i++) {
				erro += erros[i] + '\n';
			}
			alert(erro);
		} else {
			alert('Erro encontrado: \n\n' + erros[0]);
		}
	},
	
	carregar_form: function(){
		$('.disponivel').removeClass('data_sel');
		$(this).addClass('data_sel');
		var data = $(this).attr('name');
		$('#form').html("Carregando...");
		$.post('ajax/agendamento-form-s.php', { data: data }, function(response){
			$('#form').html(response);
			agenda.bind_form();
		});
		return false;
	},
	
	carregar_horas: function(){
		$('#teste').css('teste','teste');
		$('#form').html('');
		agenda.$dias.removeClass('selected');
		$(this).addClass('selected');
		var data = $(this).attr('name');
		$.post('ajax/agendamento-hora-s.php', { data: data }, function(response){
			 $('#hora').html(response);
			 agenda.bind_horas();
		});
		return false;
	}
};