Created
February 8, 2011 14:00
-
-
Save thelinuxlich/816468 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 | |
URL = "http://#{window.location.host}/aplic/eventos_internos" | |
# Classe que contém o comportamento geral do sistema. | |
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_status: KO "" | |
# Verifica se a View está em modo de edição(o evento já existe no banco) | |
VM.isEditing = KO -> VM.evento().id() isnt "" | |
# Texto para o botão de gravar evento | |
VM.captionSubmit = KO -> if VM.isEditing() then "Atualizar" else "Gravar" | |
# Texto para o botão de cancelar evento | |
VM.captionAlterarStatus = KO -> if VM.evento().status() is "A" then "Cancelar Evento" else "Ativar Evento" | |
# Habilita o botão de cadastro se o evento for válido. | |
VM.habilitaBotaoCadastrar = KO -> !VM.loading() and VM.evento().valido() | |
# Habilita o botão de excluir se o evento estiver em modo de edição | |
VM.habilitaBotaoExcluir = KO -> VM.habilitaBotaoCadastrar() and VM.isEditing() | |
# Habilita o botão de cancelar se o evento estiver em modo de edição e já foi autorizado. | |
VM.habilitaBotaoCancelar = KO -> VM.habilitaBotaoExcluir() and VM.evento().autorizado() is 'S' | |
# Carrega os assuntos na inicialização. | |
VM.init = (callback) -> | |
VM.verificaSessao -> | |
VM.carrega_cursos() | |
VM.carrega_estados -> | |
VM.evento().id("") | |
callback and callback() | |
# Inicializa o plugin Datatables na tabela de eventos | |
VM.init_datatable = -> | |
$("#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": (sSource, aoData, fnCallback) -> | |
RQ.add $.ajax | |
"dataType": 'json' | |
"type": "GET" | |
"url": "#{sSource}?foo=#{new Date}&tipo=publico" | |
"data": aoData, | |
"success": fnCallback | |
"fnRowCallback": (nRow, aData, iDisplayIndex) -> | |
$(nRow).mouseover -> $(nRow).attr "style","background-color:yellow !important;" | |
$(nRow).mouseout -> $(nRow).removeAttr "style" | |
$(nRow).click -> VM.carrega_evento aData[0] | |
return nRow | |
"oLanguage": TABLE_LANGUAGE | |
).css "width","99.5%" | |
# Carrega o evento selecionado | |
VM.carrega_evento = (id) -> | |
$.getJSON "#{URL}/get/busca_evento.php?foo=#{new Date()}",{id: id},(data) -> | |
VM.evento().id(id) | |
tipo_existente = false | |
$.each VM.tipos_de_evento,(i,item) -> | |
if item is data.tipo | |
tipo_existente = true | |
return false | |
if tipo_existente is 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 is "S") | |
.todos_os_cursos(data.todos_os_cursos is "S") | |
.responsavel(data.responsavel) | |
.autorizado(data.autorizado); | |
cursos_id = $.map data.cursos,(c) -> c.id | |
if data.todos_os_cursos is "N" | |
VM.evento().cursos(cursos_id) | |
VM.evento().estado({value: data.estado, callback: -> VM.evento().cidade(data.cidade).local(data.local)}) | |
# Carrega cidades, verificando primeiro no IdentityMap se não há um objeto guardado. | |
VM.carrega_cidades = (callback) -> | |
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, (data) -> | |
VM.cache.push {id: "cidades",params: params, data: data} | |
VM.carrega_cidades_aux data,callback | |
# Função auxiliar para carregar cidades. | |
VM.carrega_cidades_aux = (data,callback) -> | |
VM.cidades(data) | |
if VM.evento().id() is "" | |
if VM.evento().estado() is "SP" | |
VM.evento().cidade("MOGI DAS CRUZES") | |
callback and callback() | |
# Carregar as cidades ao selecionar o estado. | |
VM.evento().estado = KO("SP").intercept (value) -> | |
if typeof value is "object" | |
@(value.value) | |
VM.carrega_cidades(value.callback) | |
else if typeof value is "string" | |
@(value) | |
VM.carrega_cidades() | |
# Carrega os estados. | |
VM.carrega_estados = (callback) -> | |
RQ.add $.getJSON "#{URL}/get/busca_estados.php?foo=#{new Date()}",(data) -> | |
VM.estados(data) | |
VM.evento().estado {value: "SP",callback: callback} | |
# Carrega os cursos do coordenador | |
VM.carrega_cursos = (callback) -> | |
RQ.add $.getJSON "#{URL}/get/busca_cursos.php?foo=#{new Date()}",(data) -> | |
VM.cursos(data) | |
callback && callback() | |
# Reseta o evento da View | |
VM.resetar = -> | |
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 | |
VM.validar = -> | |
status = false | |
if compare_dates VM.evento().data_inicio(),VM.evento().data_termino() is 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() is 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() is 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() is false and this.cursos().length is 0 | |
alert "Selecione um curso para alocação no evento!".unescapeHtml() | |
$("#evento_cursos").focus() | |
else if this.tipo() is "OUTROS" and this.outro_tipo() is "" | |
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. | |
VM.enviarEvento = (callback) -> | |
status = if typeof TEST_ENV is "undefined" then VM.validar() else true | |
if status is true | |
$.post "#{URL}/post/gravar_evento.php",ko.toJS(VM.evento),(data) -> | |
if data.status is "OK" | |
if typeof VM.datatable isnt "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 and callback() | |
# Zera o evento e retorna ao estado de criação. | |
VM.voltar = -> | |
VM.resetar() | |
RQ.killAll() | |
# Exclui o evento selecionado se não houver inscrições. | |
VM.excluirEvento = (callback) -> | |
$.post "#{URL}/post/excluir_evento.php",{id: VM.evento().id()},(data) -> | |
if data.status is "OK" | |
VM.resetar() | |
if typeof VM.datatable isnt "undefined" | |
VM.datatable.fnReloadAjax() | |
alert "Evento interno removido!" | |
else | |
alert "Não foi possível remover o evento pois já existem inscrições." | |
callback and callback() | |
# Verifica a sessão atual e seta o nível de usuário | |
VM.verificaSessao = (callback) -> | |
RQ.add $.get "#{URL}/get/verifica_sessao.php?foo=#{new Date()}",(data) -> | |
if data.status is "OK" # && data.nivel === "N") { | |
callback and 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. | |
VM.abrirTelaAlterarStatus = -> | |
status = if VM.evento().status() is "A" then "I" else "A" | |
$("#dialog").dialog "option","title",if status is "I" then "Cancelar o evento" else "Ativar o evento" | |
$("#dialog").dialog "option","height",300 | |
$("#dialog").dialog "option","width",550 | |
$("#dialog").dialog "option","buttons", | |
"Cancelar": -> $(this).dialog "close" | |
"Enviar": -> | |
$("#frm_alterar_status").submit() | |
$(this).dialog("close") | |
$("#dialog").dialog "open" | |
# Cancela o evento selecionado. | |
VM.alterarStatusEvento = (callback) -> | |
status = if VM.evento().status() is "A" then "I" else "A" | |
$.post "#{URL}/post/alterar_status_evento.php",{id: VM.evento().id(),status: status,justificativa: VM.justificativa_status()},(data) -> | |
if data.status is "OK" | |
VM.resetar() | |
if typeof VM.datatable isnt "undefined" | |
VM.datatable.fnReloadAjax() | |
alert "Evento interno alterado!" | |
else | |
alert "Ocorreu um erro ao alterar o evento. Tente novamente mais tarde." | |
callback and callback() | |
$(document).ready -> | |
# Setando uma variável que diz o estado da request na view | |
RQ.beforeAdd = -> VM.loading(true) | |
RQ.afterRemove = -> VM.loading(false) | |
# Se estiver em ambiente de testes não há elementos para manipular | |
if typeof TEST_ENV is "undefined" | |
# Inicializar o modelo da view | |
VM.init -> $("#loading").fadeOut "slow", -> $("#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