Created
February 8, 2011 14:01
-
-
Save thelinuxlich/816470 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** URL do sistema */ | |
var URL = "http://"+window.location.host+"/aplic/eventos_internos"; | |
/** | |
* Classe que contém o comportamento geral do sistema. | |
* @name VM | |
* @class | |
*/ | |
var VM = { | |
loading: KO(false), | |
evento: KO(new Evento()), | |
tipos_de_evento: ['CURSO','PALESTRA','FEIRA','JORNADA','SEMINÁRIO','CONGRESSO','WORKSHOP','OUTROS'], | |
cursos: KO([]), | |
estados: KO([]), | |
cidades: KO([]), | |
cache: new IdentityMap(), | |
justificativa: KO("") | |
}; | |
/** | |
* Verifica se a View está em modo de edição(o evento já existe no banco) | |
* @function | |
*/ | |
VM.isEditing = KO(function() { return VM.evento().id() !== "";}); | |
/** | |
* Texto para o botão de gravar evento | |
* @function | |
*/ | |
VM.captionSubmit = KO(function() { return(VM.isEditing() ? "Atualizar" : "Gravar");}); | |
/** | |
* Texto para o botão de cancelar evento | |
* @function | |
*/ | |
VM.captionAlterarStatus = KO(function() { | |
return(VM.evento().status() === "A" ? "Cancelar Evento" : "Ativar Evento"); | |
}); | |
/** | |
* Habilita o botão de cadastro se o evento for válido. | |
* @function | |
*/ | |
VM.habilitaBotaoCadastrar = KO(function() { return !VM.loading() && VM.evento().valido();}); | |
/** | |
* Habilita o botão de excluir se o evento estiver em modo de edição | |
* @function | |
*/ | |
VM.habilitaBotaoExcluir = KO(function() { | |
return VM.habilitaBotaoCadastrar() && VM.isEditing(); | |
}); | |
/** | |
* Habilita o botão de cancelar se o evento estiver em modo de edição e já foi autorizado. | |
* @function | |
*/ | |
VM.habilitaBotaoCancelar = KO(function() { | |
return VM.habilitaBotaoExcluir() && VM.evento().autorizado() === 'S'; | |
}); | |
/** | |
* Carrega os assuntos na inicialização. | |
* @param callback Callback opcional para ser executado após carregar os assuntos. | |
* @function | |
*/ | |
VM.init = function(callback) { | |
VM.verificaSessao(function() { | |
VM.carrega_cursos(); | |
VM.carrega_estados(function() { | |
VM.evento().id(""); | |
callback && callback(); | |
}); | |
}); | |
}; | |
/** | |
* Inicializa o plugin Datatables na tabela de eventos | |
* @function | |
*/ | |
VM.init_datatable = function() { | |
return $("#eventos_internos").dataTable({ | |
"aoColumns": [{"sClass": "hidden"},null,null,{"sType":"date-euro"},{"sType":"date-euro"},null,null], | |
"aaSorting": [[3,"desc"]], | |
"bJQueryUI": true, | |
"bFilter": true, | |
"bAutoWidth": false, | |
"bLengthChange": false, | |
"bSortClasses": false, | |
"sAjaxSource": "get/busca_eventos_internos.php", | |
"fnServerData": function (sSource, aoData, fnCallback) { | |
RQ.add($.ajax({ | |
"dataType": 'json', | |
"type": "GET", | |
"url": sSource+"?foo="+new Date()+"&tipo=publico", | |
"data": aoData, | |
"success": fnCallback | |
})); | |
}, | |
"fnRowCallback": function(nRow, aData, iDisplayIndex) { | |
$(nRow).mouseover(function() { $(nRow).attr("style","background-color:yellow !important;"); }); | |
$(nRow).mouseout(function() { $(nRow).removeAttr("style"); }); | |
$(nRow).click(function(){ VM.carrega_evento(aData[0]); }); | |
return nRow; | |
}, | |
"oLanguage": TABLE_LANGUAGE /** table_plugins.js */ | |
}).css("width","99.5%"); | |
}; | |
/** | |
* Carrega o evento selecionado | |
* @function | |
* @param id O ID do Evento. | |
*/ | |
VM.carrega_evento = function(id) { | |
$.getJSON(URL+"/get/busca_evento.php?foo="+new Date(),{id: id},function(data) { | |
VM.evento().id(id); | |
var tipo_existente = false; | |
$.each(VM.tipos_de_evento,function(i,item) { | |
if(item === data.tipo) { | |
tipo_existente = true; | |
return false; | |
} | |
}); | |
if(tipo_existente === true) | |
VM.evento().tipo(data.tipo); | |
else | |
VM.evento().tipo("OUTROS").outro_tipo(data.tipo); | |
VM.evento().descricao(data.descricao).status(data.status) | |
.carga_horaria(data.carga_horaria) | |
.numero_de_vagas(data.numero_de_vagas) | |
.data_inicio(data.data_inicio) | |
.data_termino(data.data_termino) | |
.data_inicio_inscricao(data.data_inicio_inscricao) | |
.data_termino_inscricao(data.data_termino_inscricao) | |
.hora_inicio(data.hora_inicio) | |
.atividade_complementar(data.atividade_complementar === "S") | |
.todos_os_cursos(data.todos_os_cursos === "S") | |
.responsavel(data.responsavel) | |
.autorizado(data.autorizado); | |
var cursos_id = $.map(data.cursos,function(c){ return(c.id);}); | |
if(data.todos_os_cursos === "N") | |
VM.evento().cursos(cursos_id); | |
VM.evento().estado({value: data.estado, callback: function() { | |
VM.evento().cidade(data.cidade).local(data.local); | |
}}); | |
}); | |
}; | |
/** | |
* Carrega cidades, verificando primeiro no IdentityMap se não há um objeto guardado. | |
* @function | |
* @param callback Uma função para executar no final | |
*/ | |
VM.carrega_cidades = function(callback) { | |
var params = {estado: VM.evento().estado()}, | |
cached = VM.cache.find("cidades",params); | |
if(cached) | |
VM.carrega_cidades_aux(cached.data,callback); | |
else | |
RQ.add($.getJSON(URL+"/get/busca_cidades.php?foo="+new Date(),params, function(data) { | |
VM.cache.push({id: "cidades",params: params, data: data}); | |
VM.carrega_cidades_aux(data,callback); | |
})); | |
}; | |
/** | |
* Função auxiliar para carregar cidades. | |
* @function | |
* @param data Um array de cidades | |
* @param callback Uma função para executar no final | |
*/ | |
VM.carrega_cidades_aux = function(data,callback) { | |
VM.cidades(data); | |
if(VM.evento().id() === "") | |
if(VM.evento().estado() === "SP") | |
VM.evento().cidade("MOGI DAS CRUZES"); | |
callback && callback(); | |
}; | |
/** | |
* Carregar as cidades ao selecionar o estado. | |
* @name VM#evento_campus | |
* @event | |
*/ | |
VM.evento().estado = KO("SP").intercept(function(value){ | |
if(typeof value === "object") { | |
this(value.value); | |
VM.carrega_cidades(value.callback); | |
} else if(typeof value === "string"){ | |
this(value); | |
VM.carrega_cidades(); | |
} | |
}); | |
/** | |
* Carrega os estados. | |
* @function | |
* @param callback Uma função para executar no final | |
*/ | |
VM.carrega_estados = function(callback) { | |
RQ.add($.getJSON(URL+"/get/busca_estados.php?foo="+new Date(),function(data){ | |
VM.estados(data); | |
VM.evento().estado({value: "SP",callback: callback}); | |
})); | |
}; | |
/** | |
* Carrega os cursos do coordenador | |
* @function | |
* @param callback Uma função para executar no final | |
*/ | |
VM.carrega_cursos = function(callback) { | |
RQ.add($.getJSON(URL+"/get/busca_cursos.php?foo="+new Date(),function(data){ | |
VM.cursos(data); | |
callback && callback(); | |
})); | |
}; | |
/** | |
* Reseta o evento da View | |
* @function | |
*/ | |
VM.resetar = function() { | |
VM.evento().atividade_complementar(true) | |
.todos_os_cursos(false).id("") | |
.descricao("").cursos([]).tipo("CURSO") | |
.status("A").carga_horaria("") | |
.numero_de_vagas("").local("") | |
.data_inicio("").data_termino("") | |
.data_inicio_inscricao("") | |
.data_termino_inscricao("").hora_inicio(""); | |
}; | |
/** | |
* Valida alguns campos do evento antes de salvar | |
* @function | |
*/ | |
VM.validar = function() { | |
var status = false; | |
if(compare_dates(VM.evento().data_inicio(),VM.evento().data_termino()) === 0) { | |
alert("Data de início do evento maior que a data de término!".unescapeHtml()); | |
$("#evento_data_inicio").focus(); | |
} else if(compare_dates(VM.evento().data_inicio_inscricao(),VM.evento().data_termino_inscricao()) === 0) { | |
alert("Data de início da inscriçção maior que a data de término!".unescapeHtml()); | |
$("#evento_data_inicio_inscricao").focus(); | |
} else if(compare_dates(VM.evento().data_termino_inscricao(),VM.evento().data_inicio()) !== 1) { | |
alert("Data de término da inscrição deve ser menor que a data de início do evento!".unescapeHtml()); | |
$("#evento_data_termino_inscricao").focus(); | |
} else if(this.todos_os_cursos() === false && this.cursos().length === 0) { | |
alert("Selecione um curso para alocação no evento!".unescapeHtml()); | |
$("#evento_cursos").focus(); | |
} else if(this.tipo() === "OUTROS" && this.outro_tipo() === "") { | |
alert("Digite o tipo do evento!"); | |
$("#evento_outro_tipo").focus(); | |
} else | |
status = true; | |
return status; | |
} | |
/** | |
* Enviar a pergunta ao servidor e zerá-la caso tenha sucesso. | |
* @function | |
*/ | |
VM.enviarEvento = function(callback) { | |
if(typeof TEST_ENV === "undefined") | |
var status = VM.validar(); | |
else | |
var status = true; | |
if(status === true) { | |
$.post(URL+"/post/gravar_evento.php",ko.toJS(VM.evento),function(data) { | |
if(data.status === "OK") { | |
if(typeof VM.datatable !== "undefined") | |
VM.datatable.fnReloadAjax(); | |
if(VM.isEditing()) | |
alert("Evento interno atualizado!"); | |
else | |
alert("Evento interno cadastrado!"); | |
VM.resetar(); | |
} else | |
alert("Ocorreu um erro ao gravar o evento. Tente novamente mais tarde."); | |
callback && callback(); | |
}); | |
} | |
}; | |
/** | |
* Zera o evento e retorna ao estado de criação. | |
* @function | |
*/ | |
VM.voltar = function() { | |
VM.resetar(); | |
RQ.killAll(); | |
}; | |
/** | |
* Exclui o evento selecionado se não houver inscrições. | |
* @function | |
* @param callback Uma função para ser executada no final. | |
*/ | |
VM.excluirEvento = function(callback) { | |
$.post(URL+"/post/excluir_evento.php",{id: VM.evento().id()},function(data) { | |
if(data.status === "OK") { | |
VM.resetar(); | |
if(typeof VM.datatable !== "undefined") | |
VM.datatable.fnReloadAjax(); | |
alert("Evento interno removido!"); | |
} else | |
alert("Não foi possível remover o evento pois já existem inscrições."); | |
callback && callback(); | |
}); | |
}; | |
/** | |
* Verifica a sessão atual e seta o nível de usuário | |
* @function | |
*/ | |
VM.verificaSessao = function(callback) { | |
RQ.add($.get(URL+"/get/verifica_sessao.php",{foo: new Date()},function(data) { | |
if(data.status === "OK") {// && data.nivel === "N") { | |
callback && callback(); | |
} else { | |
alert("Sessão inválida ou expirou. Favor efetuar o login.".unescapeHtml()); | |
window.location.replace("http://intranet.umc.br"); | |
} | |
})); | |
}; | |
/** | |
* Abre uma janela de diálogo pedindo justificava para ativar/cancelar um evento. | |
* @function | |
*/ | |
VM.abrirTelaAlterarStatus = function() { | |
var status = (VM.evento().status() === "A" ? "I" : "A"); | |
$("#dialog").dialog("option","title",(status === "I" ? "Cancelar o evento" : "Ativar o evento")); | |
$("#dialog").dialog("option","height",300); | |
$("#dialog").dialog("option","width",550); | |
$("#dialog").dialog("option","buttons",{ | |
"Cancelar": function() { | |
$(this).dialog("close"); | |
}, | |
"Enviar": function() { | |
$("#frm_alterar_status").submit(); | |
$(this).dialog("close"); | |
} | |
} | |
); | |
$("#dialog").dialog("open"); | |
}; | |
/** | |
* Cancela o evento selecionado. | |
* @function | |
* @param callback Uma função para ser executada no final. | |
*/ | |
VM.alterarStatusEvento = function(callback) { | |
var status = (VM.evento().status() === "A" ? "I" : "A"); | |
$.post(URL+"/post/alterar_status_evento.php",{id: VM.evento().id(),status: status,justificativa: VM.justificativa()},function(data) { | |
if(data.status === "OK") { | |
VM.resetar(); | |
if(typeof VM.datatable !== "undefined") | |
VM.datatable.fnReloadAjax(); | |
alert("Evento interno alterado!"); | |
} else | |
alert("Ocorreu um erro ao alterar o evento. Tente novamente mais tarde."); | |
callback && callback(); | |
}); | |
}; | |
$(function(){ | |
/** Setando uma variável que diz o estado da request na view */ | |
RQ.beforeAdd = function() { VM.loading(true);}; | |
RQ.afterRemove = function() { VM.loading(false);}; | |
/** Se estiver em ambiente de testes não há elementos para manipular */ | |
if(typeof TEST_ENV === "undefined") { | |
/** Inicializar o modelo da view */ | |
VM.init(function() { | |
$("#loading").fadeOut("slow",function() { | |
$("#container").fadeIn(); | |
}); | |
}); | |
/** Inicializa o grid da view */ | |
VM.datatable = VM.init_datatable(); | |
} | |
/** Iniciar a vinculação automática de variáveis ao DOM */ | |
ko.applyBindings(VM); | |
$(".ui-dialog-titlebar-close").remove(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment