protected void btnSalvar_Click(object sender, EventArgs e)
        {
            EmprestimosBL empBL = new EmprestimosBL();
            Emprestimos emp = new Emprestimos();

            emp.Id = utils.ComparaIntComZero(hfId.Value);

            emp.ExemplarId = utils.ComparaIntComZero(hfIdExemplar.Value);
            emp.PessoaId = utils.ComparaIntComZero(hfIdPessoa.Value);

            //a pessoa esta devendo?
            PessoasBL people = new PessoasBL();
            int fiado = people.EstaDevendo(emp.PessoaId);
            if (fiado > 0)
            {
                ExibirMensagem("Esta pessoa possui títulos em abeto com a Instituição e não pode emprestar este exemplar!");
                txtExemplar.Focus();
                return;  //throw new Exception(); //tem um jeito melhor de sair do metodo?
            }

            if (emp.Id > 0)
            { //editando == devolvendo
                if (this.Master.VerificaPermissaoUsuario("EDITAR"))
                {
                    empBL.EditarBL(emp);
                    //editar a movimentacao
                    EmprestimoMovBL emovBL = new EmprestimoMovBL();
                    EmprestimoMov mov = empBL.CarregaEmpNaoDevolvido(emp.Id);
                    if (mov.Id > 0)
                    {
                        DateTime hoje = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                        mov.DataDevolucao = hoje;
                        if (hoje > mov.DataPrevistaEmprestimo)
                        { //entregou atrasado? I shall have your money...

                           DateTime diaD = mov.DataPrevistaEmprestimo ?? hoje; //convertendo DateTime? para DateTime com opcao de setar valor padrao
                            TimeSpan span = hoje - diaD;
                            int multa = this.LerParametro(1, "F");
                            double valor = multa * span.TotalDays;

                            //cadastrar titulo da multa
                            TitulosBL titBL = new TitulosBL();
                            Titulos titulos = new Titulos();

                            titulos.Numero = titBL.NovoNumero();
                            titulos.Parcela = 1;
                            titulos.Pessoaid = emp.PessoaId;
                            titulos.DataEmissao = hoje;

                            int prazo = this.LerParametro(6, "F");
                            prazo = (prazo < 1 ? 7: prazo);
                            titulos.DataVencimento = hoje.AddDays(prazo);
                            titulos.Valor = Convert.ToDecimal(valor);
                            titulos.TipoDocumentoId = this.LerParametro(4, "F");
                            ExemplaresBL exb = new ExemplaresBL();
                            Exemplares ex = exb.LerBL(emp.ExemplarId);

                            titulos.Obs = "Titulo gerado automaticamente, devido ao atraso de " + Convert.ToInt16(span.TotalDays).ToString()
                                + " dia(s) na devolução do exemplar " + emp.Id.ToString() + " - " + ex.Obras.Titulo;

                            titulos.Portadorid = this.LerParametro(5, "F");
                            titulos.Tipo = "R";

                            titBL.InserirBL(titulos);
                        }
                        emovBL.EditarBL(mov);
                    }
                }
                else
                    Response.Redirect("~/erroPermissao.aspx?nomeUsuario=" + ((Label)Master.FindControl("lblNomeUsuario")).Text + "&usuOperacao=operação", true);
            }
            else
            { //inserindo == emprestando
                if (this.Master.VerificaPermissaoUsuario("INSERIR"))
                {

                    //Quantidade máxima de exemplares emprestado:
                    int param = this.LerParametro(1, "B");
                    if (param >= 0)
                    {
                        if (empBL.QuantosLivrosEmprestados(emp.PessoaId) > param)
                        {

                            ExibirMensagem(lblDesPessoa.Text + " já atingiu o limite máximo de empréstimos simultâneos.");
                            txtPessoa.Focus();
                            return; //                            throw new Exception(); //tem um jeito melhor de sair do metodo?
                        }
                    }

                    int meuid = empBL.InserirBL(emp);
                    //inserir a movimentacao
                    EmprestimoMovBL emovBL = new EmprestimoMovBL();
                    EmprestimoMov mov = new EmprestimoMov();
                    mov.EmprestimoId = meuid;
                    mov.DataDevolucao = null;
                    mov.DataEmprestimo = Convert.ToDateTime(txtdataInicio.Text);
                    mov.DataPrevistaEmprestimo = Convert.ToDateTime(txtdataPrevisao.Text);
                    emovBL.InserirBL(mov);
                }
                else
                    Response.Redirect("~/erroPermissao.aspx?nomeUsuario=" + ((Label)Master.FindControl("lblNomeUsuario")).Text + "&usuOperacao=operação", true);
            }

            // usuarios.DtInicio = Convert.ToDateTime(txtDtInicio.Text);
            Response.Redirect("viewReserva.aspx");
        }
        private void PesquisarEmprestimosAtivo(Int32 id_pessoa)
        {
            DataTable tabela = new DataTable("tabela");

            DataColumn coluna1 = new DataColumn("ID", Type.GetType("System.Int32"));
            DataColumn coluna2 = new DataColumn("EMPRESTIMOID", Type.GetType("System.Int32"));
            DataColumn coluna3 = new DataColumn("TOMBO", Type.GetType("System.Int32"));
            DataColumn coluna4 = new DataColumn("TITULO", Type.GetType("System.String"));
            DataColumn coluna5 = new DataColumn("RENOVAR", Type.GetType("System.String"));
            DataColumn coluna6 = new DataColumn("SITUACAO", Type.GetType("System.String"));
            DataColumn coluna7 = new DataColumn("DEVOLUCAO", Type.GetType("System.String"));
            DataColumn coluna8 = new DataColumn("QTDDIAS", Type.GetType("System.String"));

            tabela.Columns.Add(coluna1);
            tabela.Columns.Add(coluna2);
            tabela.Columns.Add(coluna3);
            tabela.Columns.Add(coluna4);
            tabela.Columns.Add(coluna5);
            tabela.Columns.Add(coluna6);
            tabela.Columns.Add(coluna7);
            tabela.Columns.Add(coluna8);

            EmprestimoMovBL empMovBL = new EmprestimoMovBL();
            List<EmprestimoMov> empMov;

            empMov = empMovBL.PesquisarMovAtivosDA(id_pessoa);

            foreach (EmprestimoMov ltEmpMov in empMov)
            {
                DataRow linha = tabela.NewRow();

                linha["ID"] = ltEmpMov.Id;
                linha["EMPRESTIMOID"] = ltEmpMov.EmprestimoId;
                linha["SITUACAO"] = ltEmpMov.Situacao;
                linha["DEVOLUCAO"] = ltEmpMov.DataPrevistaEmprestimo != null ? Convert.ToDateTime(ltEmpMov.DataPrevistaEmprestimo).ToString("dd/MM/yyyy") : "";
                linha["QTDDIAS"] = ltEmpMov.QtdeDias;

                if (ltEmpMov.Obras != null)
                    linha["TITULO"] = ltEmpMov.Obras.Titulo;
                else
                    linha["TITULO"] = "";

                if (ltEmpMov.Exemplares != null)
                    linha["TOMBO"] = ltEmpMov.Exemplares.Tombo;
                else
                    linha["TOMBO"] = 0;

                if (ltEmpMov.Situacao == "Emprestado")
                    linha["RENOVAR"] = "Sim";
                else
                    linha["RENOVAR"] = "Não";

                if (empMovBL.RetornaSituacaoTitulo((int)ltEmpMov.EmprestimoId) != null)
                    linha["RENOVAR"] = "Não";

                tabela.Rows.Add(linha);
            }

            dtgExemplar.DataSource = tabela;
            dtgExemplar.DataBind();
        }
        protected void btnRenovar_Click(object sender, EventArgs e)
        {
            EmprestimosBL empBL = new EmprestimosBL();
            Emprestimos emp = new Emprestimos();

            emp.Id = utils.ComparaIntComZero(hfId.Value);
            emp.PessoaId = utils.ComparaIntComZero(hfIdPessoa.Value);

            //a pessoa esta devendo?
            PessoasBL people = new PessoasBL();
            int fiado = people.EstaDevendo(emp.PessoaId);
            if (fiado > 0)
            {
                ExibirMensagem("Esta pessoa possui títulos em abeto com a Instituição e não pode renovar este exemplar!");
                txtExemplar.Focus();
                return;  //throw new Exception(); //tem um jeito melhor de sair do metodo?
            }

            //Quantidade máxima de renovações:
            int param = this.LerParametro(2, "B");
            if (param >= 0)
            {
                if (empBL.QtdRenovacoes(emp.Id) > param)
                {
                    ExibirMensagem("Este exemplar não pode mais ser renovado para esta pessoa!");
                    txtExemplar.Focus();
                    return;  //throw new Exception(); //tem um jeito melhor de sair do metodo?
                }
            }

            //chegou aqui? vamos renovar!
            //renovar consiste em editar o atual e setar a data de devolucao, e inserir um novo
            EmprestimoMovBL emovBL = new EmprestimoMovBL();
            EmprestimoMov mov = empBL.CarregaEmpNaoDevolvido(emp.Id);
            if (mov.Id > 0)
            {
                DateTime hoje = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                DateTime previsao = mov.DataPrevistaEmprestimo ?? hoje; //convertendo DateTime? para DateTime
                if (DateTime.Compare(previsao, hoje) > 0)
                {
                    mov.DataDevolucao = DateTime.Now;
                    emovBL.EditarBL(mov);
                    mov = new EmprestimoMov();
                    mov.EmprestimoId = emp.Id;
                    mov.DataEmprestimo = DateTime.Now;
                    param = this.LerParametro(4, "B");
                    DateTime lol = DateTime.Now;
                    if (param > 0)
                        lol = DateTime.Now.AddDays(param);
                    mov.DataPrevistaEmprestimo = lol;
                    mov.DataDevolucao = null;
                    emovBL.InserirBL(mov);
                }
                else
                {
                    ExibirMensagem("Exemplar atrasado não pode ser renovado!");
                    txtExemplar.Focus();
                    return;
                }
            }
            Response.Redirect("viewReserva.aspx");
        }
        private void IncluirExemplarDevolucao(DataSet dsExe)
        {
            EmprestimoMovBL empMov = new EmprestimoMovBL();

            if (Session["dtItensDev"] != null)
                dtItensDev = (DataTable)Session["dtItensDev"];

            if (dsExe.Tables[0].Rows.Count != 0)
            {
                DataRow linha = dtItensDev.NewRow();

                linha["MOVID"] = dsExe.Tables[0].Rows[0]["movid"].ToString();
                linha["ID"] = dsExe.Tables[0].Rows[0]["id"].ToString();
                linha["TOMBO"] = dsExe.Tables[0].Rows[0]["tombo"].ToString();
                linha["TITULO"] = dsExe.Tables[0].Rows[0]["titulo"].ToString();
                linha["DEVOLUCAO"] = Convert.ToDateTime(dsExe.Tables[0].Rows[0]["DATAPREVISTAEMPRESTIMO"]).ToString("dd/MM/yyyy");
                linha["SITUACAO"] = dsExe.Tables[0].Rows[0]["SITUACAO"].ToString();
                linha["VLRMULTA"] = empMov.RetornarValorMultaEmprestimo(Convert.ToDateTime(dsExe.Tables[0].Rows[0]["DATAPREVISTAEMPRESTIMO"]));

                dtItensDev.Rows.Add(linha);
            }

            Session["dtItensDev"] = dtItensDev;
            dtgExemplarDev.DataSource = dtItensDev;
            dtgExemplarDev.DataBind();
        }
        protected void btnRenovar_Click(object sender, EventArgs e)
        {
            Button btndetails = sender as Button;
            GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
            string empMov_id;
            string emp_id;
            string renovar;
            string qtdeDias;
            string erro;
            empMov_id = dtgExemplar.DataKeys[gvrow.RowIndex][0].ToString();
            emp_id = dtgExemplar.DataKeys[gvrow.RowIndex][1].ToString();
            renovar = gvrow.Cells[4].Text;
            qtdeDias = gvrow.Cells[5].Text;

            //renovar
            if (renovar == "Sim")
            {
                EmprestimoMovBL empMovBL = new EmprestimoMovBL();
                EmprestimoMov empMov = new EmprestimoMov();
                empMov.Id = utils.ComparaIntComZero(empMov_id);
                empMov.EmprestimoId = utils.ComparaIntComZero(emp_id);
                empMov.DataDevolucao = DateTime.Now;
                empMov.DataEmprestimo = null;

                erro = empMovBL.RenovarEmprestimoBL(empMov, utils.ComparaIntComZero(qtdeDias));

                if (erro == null || erro == string.Empty)
                {
                    if (chkReciboRenovacao.Checked)
                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),
                                             "WinOpen('/Relatorios/RelRecibos.aspx?emprestimoid=" + empMov.EmprestimoId + "','',600,850);", true);
                    else
                        ExibirMensagem("Renovação realizada com sucesso !");

                    PesquisarCliente(txtCliente.Text);
                }
                else
                    ExibirMensagem(erro);
            }
            else
                ExibirMensagem("Não é possível renovar esse exemplar");
        }
        protected void btnFinOperacoes_Click(object sender, EventArgs e)
        {
            EmprestimosBL empBL = new EmprestimosBL();
            EmprestimoMovBL emovBL = new EmprestimoMovBL();

            if (!empBL.VerificaQtdeMaximaEmprestimo(utils.ComparaIntComZero(hfIdPessoa.Value)))
            {
                ExibirMensagem("O cliente já atingiu o limite máximo de empréstimos permitido!");
                return;
            }

            if (Session["dtItensEmp"] != null)
                dtItensEmp = (DataTable)Session["dtItensEmp"];

            bool v_erro = false;

            foreach (DataRow linha in dtItensEmp.Rows)
            {
                Emprestimos emp = new Emprestimos();
                emp.PessoaId = utils.ComparaIntComZero(hfIdPessoa.Value);
                emp.ExemplarId = utils.ComparaIntComZero((linha["ID"].ToString()));

                emp.Id = empBL.InserirBL(emp);

                if (emp.Id > 0)
                {
                    EmprestimoMov mov = new EmprestimoMov();
                    mov.EmprestimoId = emp.Id;
                    mov.DataEmprestimo = DateTime.Now;
                    mov.DataPrevistaEmprestimo = Convert.ToDateTime((linha["DEVOLUCAO"].ToString()));
                    v_erro = emovBL.InserirBL(mov);
                    if (!v_erro)
                    {
                        if (empBL.ExcluirBL(emp))
                        {
                            ExibirMensagem("Não foi possível concluir o empréstimo. Contate o administrador do sistema.");
                            return;
                        }

                    }
                    else
                        if (chkReciboEmprestimo.Checked)
                            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),
                                         "WinOpen('/Relatorios/RelRecibos.aspx?emprestimoid=" + emp.Id + "','',600,850);", true);
                }
            }

            if (v_erro)
            {
                LimparCamposEmprestimo();
                LimparCamposRenovacao();
                ExibirMensagem("Empréstimo realizado com sucesso!");
            }
        }
        protected void btnFinOpeDev_Click(object sender, EventArgs e)
        {
            if (Session["dtItensDev"] != null)
                dtItensDev = (DataTable)Session["dtItensDev"];

            EmprestimoMovBL emovBL = new EmprestimoMovBL();

            foreach (DataRow linha in dtItensDev.Rows)
            {

                EmprestimoMov mov = new EmprestimoMov();
                mov.Id = utils.ComparaIntComZero(linha["MOVID"].ToString());
                mov.EmprestimoId = utils.ComparaIntComZero(linha["ID"].ToString());
                mov.DataPrevistaEmprestimo = utils.ComparaDataComNull(linha["DEVOLUCAO"].ToString());
                mov.PessoaId = utils.ComparaIntComZero(hfIdPessoaDev.Value);
                mov.Titulo = linha["TITULO"].ToString();
                mov.DataDevolucao = DateTime.Now;

                string retorno = emovBL.EditarBL(mov);
                if (retorno != "false")
                {
                    if (chkReciboDevolucao.Checked)
                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),
                                                 "WinOpen('/Relatorios/RelRecibos.aspx?emprestimoid=" + mov.EmprestimoId + "','',600,850);", true);
                    else
                        ExibirMensagem("Devolução realizada com sucesso!");

                    LimparCamposDevolucao();
                    LimparCamposRenovacao();
                    LimparCamposEmprestimo();
                }
                else
                    ExibirMensagem("Não foi possível realizar a devolução. Contate o administrador do sistema.");
            }
        }
        protected void btnRelatorio_Click(object sender, EventArgs e)
        {
            EmprestimoMovBL empMovBL = new EmprestimoMovBL();
            EmprestimoMov empMov = new EmprestimoMov();
            EmprestimosBL empBL = new EmprestimosBL();
            Emprestimos emp = new Emprestimos();

            string PaginaRelatorio = "";

            if (ddlTipo.SelectedValue == "A")
            {
                Session["ldsRel"] = empMovBL.PesquisarRelatorioBL(txtAssociado.Text, txtCodigo.Text, txtDataRetiradaIni.Text, txtDataRetiradaFin.Text, txtDevolucaoIni.Text, txtDevolucaoFim.Text, ddlStatus.SelectedValue.ToString(), "desc").Tables[0];
                PaginaRelatorio = "/Relatorios/RelEmprestimoAcumulado.aspx?Acumulado=Mais&";
            }
            else if (ddlTipo.SelectedValue == "B")
            {
                Session["ldsRel"] = empMovBL.PesquisarRelatorioBL(txtAssociado.Text, txtCodigo.Text, txtDataRetiradaIni.Text, txtDataRetiradaFin.Text, txtDevolucaoIni.Text, txtDevolucaoFim.Text, ddlStatus.SelectedValue.ToString(), "asc").Tables[0];
                PaginaRelatorio = "/Relatorios/RelEmprestimoAcumulado.aspx?Acumulado=Menos&";
            }
            else
            {
                Session["ldsRel"] = empMovBL.PesquisarRelatorioBL(txtAssociado.Text, txtCodigo.Text, txtDataRetiradaIni.Text, txtDataRetiradaFin.Text, txtDevolucaoIni.Text, txtDevolucaoFim.Text, ddlStatus.SelectedValue.ToString()).Tables[0];
                PaginaRelatorio = "/Relatorios/RelEmprestimos.aspx?";
            }
            if (((DataTable)Session["ldsRel"]).Rows.Count != 0)
            {                                                                                                                                                                                                                                                                                                                                                                                                                                           //l//c
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "WinOpen('" + PaginaRelatorio + "PessoaId=" + txtAssociado.Text + "&obraId=" + txtCodigo.Text + "&DataRetiradaIni=" + txtDataRetiradaIni.Text + "&DataRetiradaFim=" + txtDataRetiradaFin.Text + "&DevolucaoFim=" + txtDevolucaoFim.Text + "&DevolucaoIni=" + txtDevolucaoIni.Text + "&Status=" + ddlStatus.SelectedValue.ToString() + "','',600,1125);", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Sua pesquisa não retornou dados.');", true);
            }
        }