protected void btGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Connection conexion = new Connection();

                string clientId = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session.Contents["userid"].ToString());
                string query = String.Format("SELECT SALES_ID FROM VENDEDORES WHERE CLIENT_ID = '{0}'", clientId);

                //Se valida que el codigo de vendedor no este en la base de datos.
                DataTable tabla = conexion.getGridDataSource(query);
                foreach (DataRow fila in tabla.Rows)
                {
                    if (fila["SALES_ID"].ToString().ToUpper().Equals(txtCodigo.Text.ToUpper()))
                    {
                        lblMensajes.Text = String.Format("<script languaje='javascript'>" +
                                        "alert('Codigo de vendedor ya existe.');" +
                                     "</script>");
                        return;
                    }

                }

                query = String.Format("INSERT INTO VENDEDORES (SALES_ID, CLIENT_ID, SALES_NAME) VALUES ('{0}', '{1}', '{2}')",
                    txtCodigo.Text.ToUpper(), clientId, txtNombre.Text);

                if (conexion.Actualizar(query))
                    lblMensajes.Text = String.Format("<script languaje='javascript'>" +
                                        "alert('Vendedor ingresado con exito.');" +
                                        "window.location.href = '../Default.aspx';" +
                                     "</script>");
                else
                    lblMensajes.Text = String.Format("<script languaje='javascript'>" +
                                        "alert('Error de conexion, intente refrescar la pagina.');" +
                                     "</script>");
            }
            catch (Exception error)
            {
                literal.Text = String.Format("<script languaje='javascript'>" +
                    "alert('Sucedio el siguiente error: {0}');" +
                    "window.location.href = '../Default.aspx';" +
                    "</script>", error.Message);
            }
        }
        protected void grdConsulta_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            Connection conexion = new Connection();

            string userId = Session["userid"].ToString();
            string clientCodeKC = conexion.getUsersInfo("CLIENT_ID", "USER_ID", userId);

            int mesActual = DateTime.Now.Month;
            int mesHistorico = 0;
            int anioHistorico = 0;

            switch (mesActual)
            {
                case 1:
                    mesHistorico = 11;  //Mes de noviembre del año anterior
                    anioHistorico = DateTime.Now.Year - 1;
                    break;
                case 2:
                    mesHistorico = 12; //Mes de diciembre del año anterior
                    anioHistorico = DateTime.Now.Year - 1;
                    break;
                default:
                    mesHistorico = mesActual - 2; //Se calculan dos meses anterirores
                    anioHistorico = DateTime.Now.Year;
                    break;
            }

            //Se crea la fecha de inicio
            DateTime fechaHistorico = new DateTime(anioHistorico, mesHistorico, 1);

            string query = String.Format("SELECT SD.DR_ID, SD.DATE_REQUEST, R.REASON_DESCRIP,"
            + " (SELECT CF.TRADE_NAME FROM CLIENTES_FINALES AS CF WHERE CF.END_USER_ID = SD.END_USER_ID AND CF.CLIENT_ID = '{0}') AS TRADE_NAME,"
            + " S.SEGMENT_NAME, ST.STATUS_DESCRIP, SD.PROGRAMMING_DATE, SD.INVER_SOLICITADA, SD.INVER_APRO, SD.NEXT_MONTH"
            + " FROM SOLICITUD_DISPENSADORES AS SD JOIN RAZONES AS R ON SD.REASON_ID = R.ID_REASON"
            + " JOIN SEGMENTOS AS S ON SD.SEGMENT_ID = S.SEGMENT_ID JOIN STATUS_DESCRIP AS ST ON SD.STATUS_ID = ST.STATUS_ID"
            + " WHERE SD.CLIENT_ID = '{0}' AND SD.DATE_REQUEST BETWEEN '{1}' AND '{2}' ORDER BY DR_ID DESC", clientCodeKC,
            fechaHistorico.ToString("yyyMMdd"), DateTime.Now.ToString("yyyMMdd"));

            grdConsulta.DataSource = conexion.getGridDataSource(query);
        }
        protected void grdDescripciones_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                Connection conexion = new Connection();

                string query = String.Format("SELECT DD.PRODUCT_ID, DD.PRODUCT_QUANTITY, DD.DISPENSER_ID, D.DESCRIPTION, DD.DISPENSER_QUANTITY, DD.INVERSION, " +
                    "(SELECT DP.DISPENSER_PRICE FROM DISPENSADOR_PAIS AS DP WHERE DP.DISPENSER_ID = DD.DISPENSER_ID AND DP.COUNTRY_ID = '{0}') AS UNIDAD "
                + "FROM DESCRIPCION_DISPENSADORES AS DD JOIN DISPENSADORES AS D ON D.ID_DISPENSER = DD.DISPENSER_ID WHERE DD.DR_ID = {1}",
                conexion.getUsersInfo("ID_COUNTRY", "USER_ID", Session.Contents["userid"].ToString()), lblNumeroSol.Text);
                grdDescripciones.DataSource = conexion.getGridDataSource(query);
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        protected void grdAutorizaciones_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                Connection conexion = new Connection();

                string userId = Session["userid"].ToString();
                string Pais = conexion.getUsersInfo("ID_COUNTRY", "USER_ID", userId);

                int mesActual = DateTime.Now.Month;
                int mesHistorico = 0;
                int anioHistorico = 0;

                switch (mesActual)
                {
                    case 1:
                        mesHistorico = 11;  //Mes de noviembre del año anterior
                        anioHistorico = DateTime.Now.Year - 1;
                        break;
                    case 2:
                        mesHistorico = 12; //Mes de diciembre del año anterior
                        anioHistorico = DateTime.Now.Year - 1;
                        break;
                    default:
                        mesHistorico = mesActual - 2; //Se calculan dos meses anterirores
                        anioHistorico = DateTime.Now.Year;
                        break;
                }

                DateTime fechaHistorico = new DateTime(anioHistorico, mesHistorico, 1);

                string query = String.Format("SELECT SD.DR_ID, SD.DATE_REQUEST, R.REASON_DESCRIP, SD.INSTALL_DATE, SD.CLIENT_ID, CKC.CLIENT_NAME," +
                        " (SELECT CF.TRADE_NAME FROM CLIENTES_FINALES AS CF WHERE CF.END_USER_ID = SD.END_USER_ID AND CF.CLIENT_ID = SD.CLIENT_ID) AS TRADE_NAME, " +
                        " S.SEGMENT_NAME, ST.STATUS_DESCRIP, SD.COMMENTS, SD.PROGRAMMING_DATE, SD.NEXT_MONTH, SD.INVER_SOLICITADA, SD.INVER_APRO " +
                        " FROM SOLICITUD_DISPENSADORES AS SD JOIN RAZONES AS R ON SD.REASON_ID = R.ID_REASON" +
                        " JOIN SEGMENTOS AS S ON SD.SEGMENT_ID = S.SEGMENT_ID JOIN STATUS_DESCRIP AS ST ON SD.STATUS_ID = ST.STATUS_ID " +
                        " JOIN CLIENTES_KC AS CKC ON SD.CLIENT_ID = CKC.CLIENT_ID WHERE SD.ID_COUNTRY = '{0}' AND SD.DATE_REQUEST BETWEEN '{1}' AND '{2}' ORDER BY SD.DR_ID DESC",
                        Pais, fechaHistorico.ToString("yyyMMdd"), DateTime.Now.ToString("yyyMMdd"));

                grdAutorizaciones.DataSource = conexion.getGridDataSource(query);
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        protected void setDataSources()
        {
            Connection conexion = new Connection();

            sqlCiudad.ConnectionString = conexion.getConnectionString();
            sqlCiudad.SelectCommand = String.Format("SELECT DIVISION_NAME, CITY_NAME FROM DIVISION_TERRITORIAL WHERE COUNTRY_ID = '{0}'", conexion.getUserCountry(Session.Contents["userid"].ToString()));

            sqlMotivos.ConnectionString = conexion.getConnectionString();
            sqlMotivos.SelectCommand = String.Format("SELECT ID_REASON, REASON_DESCRIP FROM RAZONES WHERE ID_REASON <> 3");

            sqlClientes.ConnectionString = conexion.getConnectionString();
            string clientid = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session["userid"].ToString());
            sqlClientes.SelectCommand = String.Format("SELECT END_USER_ID, TRADE_NAME FROM CLIENTES_FINALES WHERE CLIENT_ID = '{0}' AND CLIENT_STATUS = 1", clientid);

            sqlVendedores.ConnectionString = conexion.getConnectionString();
            sqlVendedores.SelectCommand = String.Format("SELECT SALES_ID, SALES_NAME FROM VENDEDORES WHERE CLIENT_ID = '{0}'", clientid);

            sqlSegmento.ConnectionString = conexion.getConnectionString();
            sqlSegmento.SelectCommand = String.Format("SELECT SUB_SEGMENT_ID, SUB_SEGMENT_NAME FROM SUB_SEGMENTOS WHERE SUB_SEGMENT_ID <> 0 ORDER BY SUB_SEGMENT_ID ASC");

            sqlCondicionesPago.ConnectionString = conexion.getConnectionString();
            sqlCondicionesPago.SelectCommand = String.Format("SELECT ID_PAYMENT_CONDITION, PAYMENT_CONDITION FROM CONDICIONES_PAGO");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Menu menu = Master.FindControl("NavigationMenu") as Menu;
                MenuItem item = new MenuItem();
                MenuItem item2 = new MenuItem();
                MenuItem item3 = new MenuItem();

                item3.Text = "Clientes Nuevos";
                item3.NavigateUrl = "Solicitud_Clientes_Nuevos.aspx";

                item2.ChildItems.Add(item3);
                item2.Text = "Solicitud Dispensadores";
                item2.Selectable = false;

                item.Text = "Seguimiento Solicitudes";
                item.NavigateUrl = "SeguimientoSolicitudes.aspx";
                menu.Items[1].ChildItems.Add(item2);
                menu.Items[1].ChildItems.Add(item);

                Connection conexion = new Connection();

                if (Convert.ToDouble(Session.Contents["presupuesto"].ToString()) <= 0)
                    radajaxmanager.ResponseScripts.Add(@"sinTP();");

                if (!IsPostBack)
                {

                    if (Session.Contents["rol"].ToString().Equals("KCPADM") || Session.Contents["rol"].ToString().Equals("KCPCCR"))
                        Response.Redirect("../Default.aspx");

                    DateTime hoy = DateTime.Now;

                    dpFechaSolicitada.MinDate = hoy.AddDays(7);
                    dpFechaSolicitada.SelectedDate = hoy.AddDays(7);

                    setDataSources();

                    //Listas para los cambios de datos
                    datos = new List<string>();
                    campos = new List<string>();

                    //Listas para los productos y dispensadores
                    codigoDispensadores = new List<string>();
                    codigoProducto = new List<string>();

                    //Listas para las cantidades de dispensador y producto
                    cantidadDispensadores = new List<int>();
                    cantidadProductos = new List<int>();

                    //Lista de inversion de solicitud
                    costoDetalle = new List<double>();

                    if (Convert.ToDouble(Session["porcentaje"].ToString()) >= 80 && Convert.ToDouble(Session["porcentaje"].ToString()) < 100)
                    {
                        radajaxmanager.ResponseScripts.Add(@"alert('Advertencia su presupuesto es menor o igual a un 20%.');");

                        if (!Convert.ToBoolean(Session.Contents["correoBajo"].ToString()))
                        {
                            conexion.correoPresupuesto(conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session.Contents["userid"].ToString()), Convert.ToDouble(Session["porcentaje"].ToString()));
                            Session.Contents["correoBajo"] = true;
                        }
                    }
                    else if (Convert.ToDouble(Session["porcentaje"].ToString()) >= 100)
                    {
                        radajaxmanager.ResponseScripts.Add(@"alert('Advertencia presupuesto agotado toda solicitud sera movida al siguiente mes.');");
                        dpFechaSolicitada.MinDate = hoy.AddDays(new DateTime(hoy.Year, hoy.Month + 1, 1).DayOfYear - hoy.DayOfYear);

                        if (!Convert.ToBoolean(Session.Contents["correoSobre"].ToString()))
                        {
                            conexion.correoPresupuesto(conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session.Contents["userid"].ToString()), Convert.ToDouble(Session["porcentaje"].ToString()));
                            Session.Contents["correoSobre"] = true;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        protected bool mandarActualizar(string campo, string valor)
        {
            try
            {
                Connection conexion = new Connection();

                string clientid = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session["userid"].ToString());
                string query = String.Format("UPDATE CLIENTES_FINALES SET {0} = '{1}' WHERE CLIENT_ID = '{2}' AND END_USER_ID = '{3}'", campo, valor, clientid, cmbNombreComercial.SelectedValue);

                if (conexion.updateClientesFinales(query))
                    return true;
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
            return false;
        }
 protected void cmbNombreComercial_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
 {
     Connection conexion = new Connection();
     string clientid = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session["userid"].ToString());
     sqlCiudad.SelectCommand = String.Format("SELECT END_USER_ID, TRADE_NAME FROM CLIENTES_FINALES WHERE CLIENT_ID = '{0}' AND CLIENT_STATUS = 1 AND TRADE_NAME LIKE '%{1}%'", clientid, e.Text);
 }
        protected void cmbCiudad_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            Connection conexion = new Connection();

            string departamentoActual = conexion.getEndClientInfo("STATE", "END_USER_ID", cmbNombreComercial.SelectedValue, "CLIENT_ID", conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session.Contents["userid"].ToString()));

            if (!departamentoActual.Equals(cmbCiudad.Text))
            {
                campos.Add("STATE");
                datos.Add(cmbCiudad.Text);
            }

            campos.Add("CITY");
            datos.Add(cmbCiudad.SelectedValue);
        }
        protected void btEnviar_Click(object sender, EventArgs e)
        {
            try
            {
                //En el caso de que falle con javascript
                if (!CustomValidator1.IsValid || !CustomValidator2.IsValid || !CustomValidator3.IsValid || !CustomValidator4.IsValid || !CustomValidator5.IsValid
                    || !CustomValidator6.IsValid || !CustomValidator7.IsValid)
                {
                    radajaxmanager.ResponseScripts.Add(@"alert('Existen conflictos en campos requeridos favor verifique.');");
                    return;
                }

                Connection conexion = new Connection();
                string clientid = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session["userid"].ToString());
                bool paraSiguienteMes = false;
                bool esEditable = true;

                int inconsistencias = 0;

                #region Recuperacion de data del grid
                foreach (GridDataItem dataItem in grdDispensadoresProducto.MasterTableView.Items)
                {
                    if ((dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text.Equals(String.Empty))
                        (dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text = "0";

                    if ((dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text.Equals(String.Empty))
                        (dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text = "0";

                    if (((dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text != "0" && (dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text != String.Empty)
                        && ((dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text != "0" && (dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text != String.Empty))
                    {
                        string temporal = String.Empty;
                        string temporal1 = String.Empty;

                        TableCell celda = dataItem["Codigo"];
                        TableCell celdaPrecio = dataItem["dispenserPrice"];
                        temporal = celda.Text;
                        codigoDispensadores.Add(temporal);

                        temporal1 = (dataItem.FindControl("cmbProducto") as RadComboBox).SelectedValue;
                        codigoProducto.Add(temporal1);

                        int dispensadores = Convert.ToInt32((dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text);
                        int productos = Convert.ToInt32((dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text);
                        double valorDetalle = Convert.ToDouble(celdaPrecio.Text.Substring(1)) * dispensadores;

                        cantidadDispensadores.Add(dispensadores);
                        cantidadProductos.Add(productos);
                        costoDetalle.Add(valorDetalle);
                    }
                    else
                    {
                        if (((dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text != "0" && (dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text == "0")
                            || ((dataItem.FindControl("txtCantidadDispensadores") as RadNumericTextBox).Text == "0" && (dataItem.FindControl("txtCantidadProducto") as RadNumericTextBox).Text != "0"))
                            inconsistencias++;

                    }
                }
                #endregion

                if (inconsistencias > 0)
                {
                    codigoDispensadores.Clear();
                    codigoProducto.Clear();
                    cantidadDispensadores.Clear();
                    cantidadProductos.Clear();
                    costoDetalle.Clear();

                    radajaxmanager.ResponseScripts.Add(String.Format(@"alert('Se han encontrado {0} inconsistencias favor revise la tabla de dispensadores y productos.');", inconsistencias));

                    return;
                }

                //Validacion de la cantidad de dispensadores
                if (cantidadDispensadores.Count == 0)
                {
                    codigoDispensadores.Clear();
                    codigoProducto.Clear();
                    cantidadDispensadores.Clear();
                    cantidadProductos.Clear();
                    costoDetalle.Clear();

                    radajaxmanager.ResponseScripts.Add(@"alert('No se han contabilizado productos.');");

                    return;
                }

                #region Datos y proceso necesario para el query
                DateTime hoy = DateTime.Now;
                Session.Add("fechasolicitud", hoy.ToString("yyyMMdd"));

                DateTime fechaRequerida = DateTime.Parse(Convert.ToString(dpFechaSolicitada.SelectedDate));
                Session.Add("fecharequerida", fechaRequerida.ToString("yyyMMdd"));

                string query = String.Empty;
                string idpais = conexion.getUserCountry(Session["userid"].ToString());

                //Sumo todos los detalles para conseguir el costo de toda la solicitud
                double valorDetalle2 = 0;
                for (int i = 0; i < costoDetalle.Count; i++)
                    valorDetalle2 += costoDetalle[i];

                if ((valorDetalle2 + Convert.ToDouble(Session.Contents["pendiente"].ToString()) + Convert.ToDouble(Session.Contents["aprobado"].ToString()))
                    > Convert.ToDouble(Session.Contents["presupuesto"].ToString()))
                {
                    paraSiguienteMes = true;
                    esEditable = false;
                }

                verificarUpdates();

                string queryTemp = String.Format("SELECT SEGMENT_ID FROM SUB_SEGMENTOS WHERE SUB_SEGMENT_ID = '{0}'", cmbSubSegmento.SelectedValue);
                DataTable tablaTemp = conexion.getGridDataSource(queryTemp);

                //Verifica que el codigo postal no se guarde con valor vacio
                string codigoPostal = "N/A";
                if (!txtCodigoPostal.Text.Equals(String.Empty))
                    codigoPostal = txtCodigoPostal.Text;

                //si la extension esta vacio se coloca el 0
                if (txtExtension.Text.Equals(String.Empty))
                    txtExtension.Text = "0";

                #region Validacion de datos adicionales del cliente
                if (txtCantidadEmpleados.Text.Equals(String.Empty))
                    txtCantidadEmpleados.Text = "0";

                if (txtCantidadVisitantes.Text.Equals(String.Empty))
                    txtCantidadVisitantes.Text = "0";

                if (txtCantidadVisitantes.Text.Equals(String.Empty))
                    txtCantidadVisitantes.Text = "0";

                if (txtBañoHombre.Text.Equals(String.Empty))
                    txtBañoHombre.Text = "0";

                if (txtBañoMujer.Text.Equals(String.Empty))
                    txtBañoMujer.Text = "0";
                #endregion

                query = "INSERT INTO SOLICITUD_DISPENSADORES (DATE_REQUEST, ID_COUNTRY, REASON_ID, INSTALL_DATE, CLIENT_ID, SALES_ID, COMMENTS, END_USER_ID, SEGMENT_ID, SUB_SEGMENT_ID, ADDRESS, NEIGHBORHOOD, CITY, "
                + "STATE, POSTAL_CODE, CONTACT_TELEPHONE, CONTACT_NAME, CONTACT_EMAIL, CONTACT_POSITION, ID_PAYMENT_CONDITION, PURCHASE_FREQUENCY, MAINTENANCE_FREQUENCY, "
                + "STRATEGIC_CUSTOMER, TRAFFIC_TYPE, TERTIARY_CLEANING, EMPLOYEES, VISITORS, WASHBASIN, MALE_BATHROOM, FEMALE_BATHROOM, STATUS_ID, INVER_SOLICITADA, "
                + "NEXT_MONTH, IS_EDITABLE, CONTACT_EXT, CONTACT_SURNAME) VALUES ('" + hoy.ToString("yyyMMdd") + "', '" + idpais + "', '" + cmbMotivos.SelectedValue + "', '"
                + fechaRequerida.ToString("yyyMMdd") + "', '" + clientid + "', '" + cmbVendedor.SelectedValue + "', '" + txtComentarios.Text + "', '" +
                cmbNombreComercial.SelectedValue + "', '" + tablaTemp.Rows[0]["SEGMENT_ID"].ToString() + "', '" + cmbSubSegmento.SelectedValue + "', '" + txtDireccion.Text + "', '" +
                txtBarrio.Text + "', '" + cmbCiudad.SelectedValue + "', '" + cmbCiudad.Text + "', '" + codigoPostal + "', '" +
                txtTelefono.Text + "', '" + txtPersonaContacto.Text + "', '" + txtCorreoContacto.Text + "', '" + txtPosicion.Text + "', '" +
                cmbCondicionPago.SelectedValue + "', '" + cmbFrecuenciaCompra.SelectedValue + "', '" + cmbFrecuenciaMantenimiento.SelectedValue + "', '" +
                cmbClienteEstrategico.SelectedValue + "', '" + cmbTipoTrafico.SelectedValue + "', '" + cmbLimpiezaTercerizada.SelectedValue + "', " +
                Convert.ToInt32(txtCantidadEmpleados.Text) + ", " + Convert.ToInt32(txtCantidadVisitantes.Text) + ", " + Convert.ToInt32(txtCantidadLavatorios.Text) + ", " +
                Convert.ToInt32(txtBañoHombre.Text) + ", " + Convert.ToInt32(txtBañoMujer.Text) + ", 1, " + valorDetalle2 + ", '" + paraSiguienteMes + "', '" +
                esEditable + "', '" + txtExtension.Text + "', '" + txtApellido.Text + "')";
                #endregion

                #region Inserccion
                string dispenserId = String.Empty;

                //Lista para el correo
                List<string> datosGenerales = new List<string>();

                if (conexion.setDispenserGeneral(query))
                {
                    string codigoCliente = conexion.getClientKCInfo("SUBSIDIARY_ID", "CLIENT_ID", clientid);
                    dispenserId = conexion.getdispenserReqId(hoy.ToString("yyyMMdd"), codigoCliente);

                    if (conexion.setDescripcionDis(dispenserId, codigoDispensadores, codigoProducto, cantidadDispensadores, cantidadProductos, costoDetalle))
                    {
                        //valorDetalle2 += Convert.ToDouble(Session.Contents["pendiente"].ToString());

                        string query2 = String.Format("UPDATE CLIENTES_KC SET INVERSION_FLOTANTE = (INVERSION_FLOTANTE + {0}) WHERE CLIENT_ID = '{1}'", valorDetalle2, clientid);
                        conexion.updateClientesFinales(query2);

                        btEnviar.Visible = false;
                        grdDispensadoresProducto.Visible = false;

                        main.Visible = false;
                        string nombrecliente = conexion.getClientKCInfo("CLIENT_NAME", "CLIENT_ID", clientid);

                        //Para el correo electronico
                        datosGenerales.Add(nombrecliente);//Indice 0
                        datosGenerales.Add(txtNombreComercial.Text); //Indice 1
                        datosGenerales.Add(conexion.getUsersInfo("USER_NAME", "USER_ID", Session.Contents["userid"].ToString()));//indice 2
                        datosGenerales.Add(hoy.ToString("dd/MM/yyy"));//indice 3
                        datosGenerales.Add(fechaRequerida.ToString("dd/MM/yyy"));//indice 4
                        datosGenerales.Add(cmbMotivos.Text);//indice 5
                        datosGenerales.Add(txtDireccion.Text);//indice 6
                        datosGenerales.Add(String.Format("{0} {1}", txtPersonaContacto.Text, txtApellido.Text));//inidice 7
                        datosGenerales.Add(txtTelefonoContacto.Text);//incice 8
                        datosGenerales.Add(txtExtension.Text);//indice 9
                        datosGenerales.Add(txtComentarios.Text);//indice 10

                        if (conexion.enviarEmail(datosGenerales, codigoDispensadores, codigoProducto, cantidadDispensadores, cantidadProductos, idpais,
                            clientid, paraSiguienteMes))
                        {
                            datosGenerales.Clear();
                            codigoDispensadores.Clear();
                            codigoProducto.Clear();
                            cantidadDispensadores.Clear();
                            cantidadProductos.Clear();
                            costoDetalle.Clear();
                            datos.Clear();
                            campos.Clear();

                            if (!paraSiguienteMes)
                                radajaxmanager.ResponseScripts.Add(String.Format("alerta('{0}');", valorDetalle2));
                            else
                                radajaxmanager.ResponseScripts.Add(String.Format("alerta2('{0}');", valorDetalle2));
                        }
                        else
                        {
                            datosGenerales.Clear();
                            codigoDispensadores.Clear();
                            codigoProducto.Clear();
                            cantidadDispensadores.Clear();
                            cantidadProductos.Clear();
                            costoDetalle.Clear();
                            datos.Clear();
                            campos.Clear();
                            if (!paraSiguienteMes)
                                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio(\"La solicitud fue creada costo total ${0}, sin aviso por correo.\");", valorDetalle2));
                            else
                                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio(\"La solicitud fue creada costo total ${0} y movida al siguiente mes presupuesto excedido, sin aviso por correo.\");", valorDetalle2));
                        }
                    }
                    else
                    {

                        string queryError = String.Format("DELETE SOLICITUD_DISPENSADORES WHERE DR_ID = '{0}'", dispenserId);
                        conexion.setDispenserGeneral(queryError);

                        codigoDispensadores.Clear();
                        codigoProducto.Clear();
                        cantidadDispensadores.Clear();
                        cantidadProductos.Clear();
                        costoDetalle.Clear();
                        datosGenerales.Clear();
                        datos.Clear();
                        campos.Clear();
                        radajaxmanager.ResponseScripts.Add(@"alert('Error al guardar la Descripcion de solicitud intentelo mas tarde.');");

                        return;
                    }

                }
                else
                {
                    codigoDispensadores.Clear();
                    codigoProducto.Clear();
                    cantidadDispensadores.Clear();
                    cantidadProductos.Clear();
                    costoDetalle.Clear();
                    datosGenerales.Clear();
                    datos.Clear();
                    campos.Clear();
                    radajaxmanager.ResponseScripts.Add(@"alert('Error al guardar la solicitud intentelo mas tarde.');");

                    return;
                }

                #endregion
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        protected void cargarData(string codigo)
        {
            try
            {
                Connection conexion = new Connection();
                string listasDesplegables = String.Empty;
                string clientid = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session.Contents["userid"].ToString());
                string query = String.Format("SELECT * FROM CLIENTES_FINALES WHERE END_USER_ID = '{0}' AND CLIENT_ID = '{1}'"
                    , codigo, clientid);

                DataTable clientesFinales = conexion.getGridDataSource(query);

                string clienteEscogido = clientesFinales.Rows[0]["END_USER_ID"].ToString() + " | " + clientesFinales.Rows[0]["TRADE_NAME"].ToString();

                txtNombreComercial.Text = clientesFinales.Rows[0]["TRADE_NAME"].ToString();

                txtRazonSocial.Text = clientesFinales.Rows[0]["SOCIAL_REASON"].ToString();
                if (txtRazonSocial.Text.Equals("N/A"))
                    txtRazonSocial.Text = String.Empty;

                txtCedulaJuridica.Text = clientesFinales.Rows[0]["CORPORATE_ID"].ToString();
                if (txtCedulaJuridica.Text.Equals("N/A"))
                    txtCedulaJuridica.Text = String.Empty;

                txtDireccion.Text = clientesFinales.Rows[0]["ADDRESS"].ToString();
                if (txtDireccion.Text.Equals("N/A"))
                    txtDireccion.Text = String.Empty;

                txtBarrio.Text = clientesFinales.Rows[0]["NEIGHBOR"].ToString();
                if (txtBarrio.Text.Equals("N/A"))
                    txtBarrio.Text = String.Empty;

                txtCodigoPostal.Text = clientesFinales.Rows[0]["POSTAL_CODE"].ToString();
                if (txtCodigoPostal.Text.Equals("N/A"))
                    txtCodigoPostal.Text = String.Empty;

                txtTelefono.Text = clientesFinales.Rows[0]["TELEPHONE"].ToString();

                txtEMail.Text = clientesFinales.Rows[0]["E_MAIL"].ToString();
                if (txtEMail.Text.Equals("N/A"))
                    txtEMail.Text = String.Empty;

                txtCantidadEmpleados.Text = clientesFinales.Rows[0]["EMPLOYEES"].ToString();
                txtCantidadVisitantes.Text = clientesFinales.Rows[0]["VISITORS"].ToString();
                txtCantidadLavatorios.Text = clientesFinales.Rows[0]["WASHBASIN"].ToString();
                txtBañoHombre.Text = clientesFinales.Rows[0]["MALE_BATH"].ToString();
                txtBañoMujer.Text = clientesFinales.Rows[0]["FEMALE_BATH"].ToString();

                txtPersonaContacto.Text = clientesFinales.Rows[0]["CONTACT_PERSON"].ToString();
                if (txtPersonaContacto.Text.Equals("N/A"))
                    txtPersonaContacto.Text = String.Empty;

                txtApellido.Text = clientesFinales.Rows[0]["CONTACT_SURNAME"].ToString();
                if (txtApellido.Text.Equals("N/A"))
                    txtApellido.Text = String.Empty;

                txtTelefonoContacto.Text = clientesFinales.Rows[0]["CONTACT_TELEPHONE"].ToString();
                if (txtTelefonoContacto.Text.Equals("N/A"))
                    txtTelefonoContacto.Text = String.Empty;

                txtExtension.Text = clientesFinales.Rows[0]["CONTACT_EXT"].ToString();

                txtCorreoContacto.Text = clientesFinales.Rows[0]["CONTACT_MAIL"].ToString();
                if (txtCorreoContacto.Text.Equals("N/A"))
                    txtCorreoContacto.Text = String.Empty;

                txtPosicion.Text = clientesFinales.Rows[0]["CONTACT_POSITION"].ToString();
                if (txtPosicion.Text.Equals("N/A"))
                    txtPosicion.Text = String.Empty;

                listasDesplegables = clientesFinales.Rows[0]["SELLER_ID"].ToString();
                if(!listasDesplegables.Equals("N/A"))
                    cmbVendedor.FindItemByValue(listasDesplegables, true).Selected = true;

                listasDesplegables = clientesFinales.Rows[0]["SUB_SEGMENT_ID"].ToString();
                if (!listasDesplegables.Equals("0"))
                    cmbSubSegmento.FindItemByValue(listasDesplegables, false).Selected = true;
                else
                {
                    cmbSubSegmento.Text = String.Empty;
                    cmbSubSegmento.ClearSelection();
                }

                listasDesplegables = clientesFinales.Rows[0]["CITY"].ToString();
                if (!listasDesplegables.Equals("N/A"))
                    cmbCiudad.FindItemByValue(listasDesplegables, true).Selected = true;
                else
                {
                    cmbCiudad.Text = String.Empty;
                    cmbCiudad.ClearSelection();
                }

                listasDesplegables = clientesFinales.Rows[0]["ID_PAYMENT_CONDITION"].ToString();
                cmbCondicionPago.FindItemByValue(listasDesplegables, true).Selected = true;

                listasDesplegables = clientesFinales.Rows[0]["PURCHASE_FREQUENCY"].ToString();
                cmbFrecuenciaCompra.FindItemByText(listasDesplegables, true).Selected = true;

                listasDesplegables = clientesFinales.Rows[0]["MAINTENANCE_FREQUENCY"].ToString();
                cmbFrecuenciaMantenimiento.FindItemByValue(listasDesplegables, true).Selected = true;

                listasDesplegables = clientesFinales.Rows[0]["STRATEGIC_CUSTOMER"].ToString();
                cmbClienteEstrategico.FindItemByValue(listasDesplegables, true).Selected = true;

                listasDesplegables = clientesFinales.Rows[0]["TRAFFIC_TYPE"].ToString();
                cmbTipoTrafico.FindItemByText(listasDesplegables, true).Selected = true;

                listasDesplegables = clientesFinales.Rows[0]["TERTIARY_CLEANING"].ToString();
                cmbLimpiezaTercerizada.FindItemByValue(listasDesplegables, true).Selected = true;

                grdDispensadoresProducto.Enabled = true;
                btEnviar.Enabled = true;
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Connection conexion = new Connection();

                DateTime hoy = DateTime.Now;
                string clientId = conexion.getUsersInfo("CLIENT_ID", "USER_ID", Session["userid"].ToString());

                if (Session["rol"].Equals("KCPCCR") || Session["rol"].Equals("KCPADM"))
                {
                    parrafo1.Text = "Desde aqui podras autorizar, revisar y rechazar solicitudes de nuestros socios comerciales. " +
                        "¿Cómo dar seguimiento a las solicitudues? ahora te decimos:";

                    parrafo2.Visible = false;

                    string query = String.Format("SELECT COUNT(DR_ID) AS PENDIENTE "
                    + "FROM SOLICITUD_DISPENSADORES "
                    + "WHERE ID_COUNTRY = '{0}' AND (STATUS_ID = 1 OR STATUS_ID = 5) AND CLIENT_ID <> '40000000'"
                    , conexion.getUsersInfo("ID_COUNTRY", "USER_ID", Session.Contents["userid"].ToString()));

                    DataTable dataset = conexion.getGridDataSource(query);
                    lblTP.Text = "<b>Pendientes Total:</b> " + Convert.ToString(dataset.Rows[0]["PENDIENTE"]);

                    query = String.Format("SELECT COUNT(DR_ID) AS APROBADO "
                    + "FROM SOLICITUD_DISPENSADORES "
                    + "WHERE ID_COUNTRY = '{0}' AND STATUS_ID = 2 AND CLIENT_ID <> '40000000'"
                    , conexion.getUsersInfo("ID_COUNTRY", "USER_ID", Session.Contents["userid"].ToString()));

                    dataset = conexion.getGridDataSource(query);
                    lblInvAut.Text = "<b>Aprobados Total:</b> " + Convert.ToString(dataset.Rows[0]["APROBADO"]);

                    query = String.Format("SELECT COUNT(DR_ID) AS RECHAZADO "
                    + "FROM SOLICITUD_DISPENSADORES "
                    + "WHERE ID_COUNTRY = '{0}' AND STATUS_ID = 3 AND CLIENT_ID <> '40000000'"
                    , conexion.getUsersInfo("ID_COUNTRY", "USER_ID", Session.Contents["userid"].ToString()));

                    dataset = conexion.getGridDataSource(query);
                    lblInvPend.Text = "<b>Rechazados Total:</b> " + Convert.ToString(dataset.Rows[0]["RECHAZADO"]);

                    query = String.Format("SELECT COUNT(DR_ID) AS CERRADA "
                    + "FROM SOLICITUD_DISPENSADORES "
                    + "WHERE ID_COUNTRY = '{0}' AND STATUS_ID = 4 AND CLIENT_ID <> '40000000'"
                    , conexion.getUsersInfo("ID_COUNTRY", "USER_ID", Session.Contents["userid"].ToString()));

                    dataset = conexion.getGridDataSource(query);
                    lblInvUsada.Text = "<b>Cerradas Total:</b> " + Convert.ToString(dataset.Rows[0]["CERRADA"]);
                }

                DateTime vencimiento = Convert.ToDateTime(conexion.getPExpiration(Session["userid"].ToString()));

                if (!clientId.Equals(String.Empty))
                {
                    string query = String.Format("SELECT BUDGET_TP, INVERSION, INVERSION_FLOTANTE FROM CLIENTES_KC WHERE CLIENT_ID = '{0}'", clientId);
                    DataTable tabla = conexion.getGridDataSource(query);

                    foreach (DataRow fila in tabla.Rows)
                    {
                        double tp = Convert.ToDouble(fila["BUDGET_TP"]);
                        double inversion = Convert.ToDouble(fila["INVERSION"]);
                        double inversionF = Convert.ToDouble(fila["INVERSION_FLOTANTE"]);
                        double disponibilidad = tp - (inversion + inversionF);
                        double porcentaje = ((disponibilidad) / tp) * 100;

                        lblTP.Text = "<b>Presupuesto:</b> $" + tp.ToString();
                        lblInvAut.Text = "<b>Inversion Aprobada:</b> $" + inversion.ToString("0.00");
                        lblInvPend.Text = "<b>Inversion Pendiente:</b> $" + inversionF.ToString("0.00");

                        if (disponibilidad > 0)
                            lblRestante.Text = "<b>Presupuesto Restante:</b> $" + disponibilidad.ToString("0.00");
                        else
                        {
                            lblRestante.ForeColor = System.Drawing.Color.Red;
                            lblRestante.Text = "Presupuesto Restante: <b>$0.0</b>";
                        }

                        if (porcentaje > 0)
                            lblInvUsada.Text = "<b>% Disponibilidad:</b> " + porcentaje.ToString("0.00") + "%";
                        else
                        {
                            lblInvUsada.ForeColor = System.Drawing.Color.Red;
                            lblInvUsada.Text = "% Disponibilidad: <b>0%</b>";
                        }

                        Session.Add("presupuesto", tp);
                        Session.Add("aprobado", inversion);
                        Session.Add("pendiente", inversionF);
                        Session.Add("porcentaje", Convert.ToDouble(((inversion + inversionF) / tp) * 100));
                        Session.Add("correoBajo", false);
                        Session.Add("correoSobre", false);
                    }
                }

                int diferencia = vencimiento.DayOfYear - hoy.DayOfYear;

                //para cambio de año
                if (diferencia < 0)
                    diferencia = diferencia * -1;

                if (diferencia <= 5)
                {
                    mensajes.Text = String.Format("<script languaje='javascript'>" +
                                        "alert('Su contraseña vencera dentro de {0} dias');" +
                                     "</script>", diferencia);
                }
            }
            catch (Exception error)
            {
                mensajes.Text = String.Format("<script languaje='javascript'>" +
                                        "alert('{0}');" +
                                        "window.location.href = 'About.aspx';" +
                                     "</script>", error.Message);
            }
        }