protected void grdUsuarios_ItemUpdated(object source, GridUpdatedEventArgs e)
        {
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                string userId = item.GetDataKeyValue("USER_ID").ToString();

                Connection conexion = new Connection();
                conexion.Actualizar(String.Format("UPDATE USUARIOS SET P_EXPIRATION = '{0}' WHERE USER_ID = '{1}'", DateTime.Now.AddMonths(1).ToString("yyyMMdd"), userId));

                if (e.Exception != null)
                {
                    e.KeepInEditMode = true;
                    e.ExceptionHandled = true;
                    RadAjaxManager1.ResponseScripts.Add(String.Format("errorEdicion('{0}');", e.Exception.Message.ToString()));
                }
                else
                {
                    RadAjaxManager1.ResponseScripts.Add(String.Format("alert('Usuario actualizado.');"));
                }
            }
            catch (Exception error)
            {
                RadAjaxManager1.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        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 double cantidad(string dispensador, string producto)
        {
            try
            {
                Connection conexion = new Connection();

                string cantidad = conexion.getDetalleSol("APPROVAL_QTY", dispensador, producto, lblNumeroSol.Text);
                double cantidadAutorizada = 0;
                double cantidadDispensador = Convert.ToDouble(conexion.getDetalleSol("DISPENSER_QUANTITY", dispensador, producto, lblNumeroSol.Text));

                if (!cantidad.Equals(String.Empty))
                    cantidadAutorizada = Convert.ToDouble(cantidad);

                if (cantidadAutorizada > 0)
                    return cantidadAutorizada;
                else
                {
                    string query = String.Format("UPDATE DESCRIPCION_DISPENSADORES SET APPROVAL_QTY = {0} WHERE DR_ID = '{1}' AND DISPENSER_ID = '{2}' AND PRODUCT_ID = '{3}'",
                        cantidadDispensador, lblNumeroSol.Text, dispensador, producto);

                    conexion.Actualizar(query);
                    return cantidadDispensador;
                }
            }
            catch (Exception error)
            {
                radajaxmanager.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }

            return 0;
        }
        protected void btEditar_Click(object sender, EventArgs e)
        {
            try
            {
                if (lbxCuentasDestino.Items.Count == 0 && chkHabilitarKam.Checked)
                {
                    RadAjaxManager1.ResponseScripts.Add("alert('No se encontraron cuentas asignadas, un KAM activo debe tener por lo menos una cuenta.');");
                    return;
                }

                Connection conexion = new Connection();
                string query = String.Format("UPDATE KAM SET KAM_NAME = '{0}', KAM_MAIL = '{1}', KAM_ACTIVE = '{2}', RECEIVE_MAIL = '{3}' WHERE KAM_ID = '{4}'",
                    txtNombreKAM.Text, txtCorreo.Text, chkHabilitarKam.Checked, chkHabilitarCorreo.Checked, cmbKAM.SelectedValue);

                if (conexion.Actualizar(query))
                {
                    valoresFinales = new List<string>();
                    bool encontrado = false;

                    foreach (RadListBoxItem item in lbxCuentasDestino.Items)
                        valoresFinales.Add(item.Value);

                    for (int i = 0; i < valoresInicio.Count; i++)
                    {
                        for (int j = 0; j < valoresFinales.Count; j++)
                        {
                            if (valoresInicio[i].Equals(valoresFinales[j]))
                            {
                                valoresFinales.RemoveAt(j);
                                encontrado = true;
                            }
                        }

                        if (!encontrado)
                        {
                            query = String.Format("DELETE FROM CUENTAS_KAM WHERE KAM_ID = '{0}' AND CLIENT_ID = '{1}'", cmbKAM.SelectedValue, valoresInicio[i]);
                            conexion.Actualizar(query);
                        }

                        encontrado = false;
                    }

                    for (int i = 0; i < valoresFinales.Count; i++)
                    {
                        query = String.Format("INSERT INTO CUENTAS_KAM (KAM_ID, CLIENT_ID) VALUES ('{0}', '{1}')", cmbKAM.SelectedValue, valoresFinales[i]);
                        conexion.Actualizar(query);
                    }

                    if (!chkHabilitarKam.Checked)
                    {
                        foreach (RadListBoxItem item in lbxCuentasDestino.Items)
                        {
                            query = String.Format("DELETE FROM CUENTAS_KAM WHERE KAM_ID = '{0}' AND CLIENT_ID = '{1}'", cmbKAM.SelectedValue, item.Value);
                            conexion.Actualizar(query);
                        }
                    }

                    RadAjaxManager1.ResponseScripts.Add("editarKam();");
                }
                else
                {
                    RadAjaxManager1.ResponseScripts.Add("alert('Error inesperado de conexion intentelo de nuevo.');");
                    return;
                }
            }
            catch (Exception error)
            {
                RadAjaxManager1.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }
        protected void btProcesar_Click(object sender, EventArgs e)
        {
            try
            {
                Connection conexion = new Connection();
                string query = String.Empty;
                string password = String.Empty;

                Random random = new Random(DateTime.Now.Millisecond);

                for (int i = 0; i < 5; i++)
                    password += (char)random.Next(97, 123);

                for (int j = 0; j < 5; j++)
                    password += Convert.ToString(random.Next(0, 9));

                if (cmbUbicacion.SelectedValue.Equals("0"))
                {
                    query = String.Format("SELECT USER_ID FROM USUARIOS WHERE ID_COUNTRY = '{0}' AND CLIENT_ID IS NULL",
                        conexion.getUserCountry(Session.Contents["userid"].ToString()));

                    DataTable usuariosExistentes = conexion.getGridDataSource(query);
                    foreach (DataRow fila in usuariosExistentes.Rows)
                    {
                        if (fila["USER_ID"].ToString().Equals(txtCodigo.Text.ToUpper()))
                        {
                            RadAjaxManager1.ResponseScripts.Add(String.Format("alert('El codigo ya existe.');"));
                            return;
                        }
                    }

                    query = String.Format("SELECT KAM_ID FROM KAM WHERE COUNTRY = '{0}' AND KAM_ACTIVE = 1", conexion.getUserCountry(Session.Contents["userid"].ToString()));
                    usuariosExistentes = conexion.getGridDataSource(query);

                    foreach (DataRow fila in usuariosExistentes.Rows)
                    {
                        if (fila["KAM_ID"].ToString().Equals(txtCodigo.Text.ToUpper()))
                        {
                            RadAjaxManager1.ResponseScripts.Add(String.Format("alert('El codigo ya existe para un KAM.');"));
                            return;
                        }
                    }

                    query = String.Format("INSERT INTO USUARIOS (USER_ID, USER_NAME, PASSWORD, P_EXPIRATION, ID_ROL, LOGIN_ID, STATUS, ID_COUNTRY, E_MAIL) "
                    + "VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', 1, '{6}', '{7}')"
                    , txtCodigo.Text, txtUsuario.Text, password, DateTime.Now.AddMonths(1).ToString("yyyMMdd"), cmbRol.SelectedValue, txtCodigo.Text,
                    conexion.getUserCountry(Session.Contents["userid"].ToString()), txtCorreo.Text);
                }
                else
                    query = String.Format("INSERT INTO USUARIOS (USER_ID, USER_NAME, PASSWORD, P_EXPIRATION, ID_ROL, LOGIN_ID, STATUS, ID_COUNTRY, E_MAIL, CLIENT_ID) "
                    + "VALUES ('{0}', '{1}', '{2}', '{3}', 'DSTADM', '{4}', 1, '{5}', '{6}', '{7}')", txtCodigo.Text, txtUsuario.Text, password,
                    DateTime.Now.AddMonths(1).ToString("yyyMMdd"), txtCodigo.Text, conexion.getUserCountry(Session.Contents["userid"].ToString()),
                    txtCorreo.Text, cmbUbicacion.SelectedValue);

                List<string> datos = new List<string>();
                datos.Add(cmbUbicacion.SelectedValue);
                datos.Add(txtCodigo.Text);
                datos.Add(txtUsuario.Text);
                datos.Add(password);
                datos.Add(txtCorreo.Text);

                if (conexion.Actualizar(query))
                    if(conexion.notificacionNuevoUsuario(datos))
                        RadAjaxManager1.ResponseScripts.Add(String.Format("exitoNuevoUsuario(1);"));
                    else
                        RadAjaxManager1.ResponseScripts.Add(String.Format("exitoNuevoUsuario(0);"));
                else
                    RadAjaxManager1.ResponseScripts.Add(String.Format("alert('Error inesperado de conexion, intentelo mas tarde');"));
            }
            catch (Exception error)
            {
                RadAjaxManager1.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message));
            }
        }